GoodsController.php 133 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558
  1. <?php
  2. namespace app\admin\controller\order;
  3. use app\admin\service\member\MemberService;
  4. use app\admin\service\order\OrderService;
  5. use app\admin\validate\order\OrderValidate;
  6. use app\controller\Curd;
  7. use app\model\Appointment;
  8. use app\model\CouponDetail;
  9. use app\model\Goods;
  10. use app\model\GoodsComponent;
  11. use app\model\GoodsRunning;
  12. use app\model\GoodsSku;
  13. use app\model\Member;
  14. use app\model\MemberAccount;
  15. use app\model\MemberBenefit;
  16. use app\model\Order;
  17. use app\model\OrderExpress;
  18. use app\model\OrderSheet;
  19. use app\model\PayDetail;
  20. use app\model\SysDept;
  21. use support\Db;
  22. use support\exception\BusinessException;
  23. use support\Redis;
  24. use support\Request;
  25. use support\Response;
  26. use Webman\Event\Event;
  27. class GoodsController extends Curd
  28. {
  29. public function __construct()
  30. {
  31. $this->model = new Order();
  32. $this->validate = true;
  33. $this->validateClass = new OrderValidate();
  34. }
  35. /**
  36. * @Desc 列表
  37. * @Author Gorden
  38. * @Date 2024/3/28 15:01
  39. *
  40. * @param Request $request
  41. * @return Response
  42. * @throws \support\exception\BusinessException
  43. */
  44. public function select(Request $request): Response
  45. {
  46. [$where, $format, $limit, $field, $order] = $this->selectInput($request);
  47. $where['order_classify'] = 'GOODS';
  48. if (!empty($where['order_addtimes'])) {
  49. $where['order_addtimes'][0] = strtotime($where['order_addtimes'][0]);
  50. $where['order_addtimes'][1] = strtotime($where['order_addtimes'][1]);
  51. }
  52. $order = $request->get('order', 'desc');
  53. $field = $field ?? 'order_addtimes';
  54. if (!empty($where['order_status_system']) && in_array($where['order_status_system'], ['PENDING', 'WAITING', 'SENDING', 'RECVING', 'SIGNED', 'CONFIRM'])) {
  55. if ($where['order_status_system'] == 'SENDING') {
  56. $where['order_express.order_express_type'] = '配送';
  57. }
  58. $where['order_is_complete'] = 'N';
  59. }
  60. $orderId = $request->get('order_id', '');
  61. $orderIds = [];
  62. if (!empty($orderId)) {
  63. $orderIds = Order::where('order_id', 'like', '%' . $orderId . '%')
  64. ->where('order_classify', 'GOODS')
  65. ->pluck('order_id')
  66. ->toArray();
  67. }
  68. $goodsName = $request->get('goods_name', '');
  69. if (!empty($goodsName)) {
  70. $goodsIds = Goods::where('goods_classify', 'GOODS')
  71. ->where('goods_name', 'like', '%' . $goodsName . '%')
  72. ->pluck('goods_id')
  73. ->toArray();
  74. $goodsOrderIds = OrderSheet::whereIn('join_sheet_goods_id', $goodsIds)->pluck('join_sheet_order_id')->toArray();
  75. if (!empty($where['order_id'])) {
  76. $orderIds = array_intersect($orderIds, $goodsOrderIds);
  77. } else {
  78. $orderIds = $goodsOrderIds;
  79. }
  80. }
  81. if (!empty($orderId) || !empty($goodsName)) {
  82. $where['order_id'] = ['in', implode(',', $orderIds)];
  83. }
  84. // 自提订单
  85. if (!empty($where['order_status_system']) && $where['order_status_system'] == 'PICKUP') {
  86. $where['order_is_complete'] = 'N';
  87. $where['order_status_system'] = 'SENDING';
  88. $where['order_express.order_express_type'] = '自提';
  89. }
  90. $query = $this->doSelect($where, $field, $order);
  91. return $this->doFormat($query, $format, $limit);
  92. }
  93. protected function doSelect(array $where, string $field = null, string $order = 'desc')
  94. {
  95. $model = $this->model->with([
  96. 'sheets' => function ($query) {
  97. $query->select('join_sheet_order_id', 'order_sheet_id', 'join_sheet_goods_id', 'order_sheet_num', 'order_sheet_price');
  98. },
  99. 'member' => function ($query) {
  100. $query->select('member_id', 'member_mobile');
  101. },
  102. 'cert' => function ($query) {
  103. $query->select('join_cert_member_id', 'member_cert_name');
  104. },
  105. // 'return' => function ($query) use ($where){
  106. // if (isset($where['return'])){
  107. // dump($where['return']);
  108. // $query = $query->where('order_return_status',$where['return']);
  109. // }
  110. // $query->select('orders_return_id', 'join_return_order_id', 'order_return_status');
  111. // },
  112. // 'express' => function ($query) {
  113. // $query->select('join_express_order_id', 'order_express_type');
  114. // }
  115. ])->leftJoin('order_return', 'order_return.join_return_order_id', '=', 'order.order_id')
  116. ->leftJoin('order_express', 'order_express.join_express_order_id', '=', 'order.order_id');
  117. // ->leftJoin('order_sheet','join_sheet_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. if (count($item['sheets']) > 1 && $goods->goods_classify == 'MEALS') {
  161. $sheetDeng = ' 等餐品';
  162. }
  163. $item['sheet']['goods_name'] = ($goods && $goods->goods_name) ? $goods->goods_name . $sheetDeng : '';
  164. $item['sheet']['goods_classify'] = $goods->goods_classify ?? '';
  165. $item['sheet']['order_sheet_num'] = intval($item['sheet']['order_sheet_num']);
  166. }
  167. unset($item['sheets']);
  168. if (isset($item['orders_return_id'])) {
  169. $item['return'] = [
  170. 'orders_return_id' => $item['orders_return_id'],
  171. 'join_return_order_id' => $item['join_return_order_id'],
  172. 'order_return_status' => $item['order_return_status'],
  173. 'order_return_apply_json' => $item['order_return_apply_json'],
  174. 'order_return_remark' => $item['order_return_remark']
  175. ];
  176. }
  177. if (isset($item['join_express_order_id'])) {
  178. $item['express'] = [
  179. 'join_express_order_id' => $item['join_express_order_id'],
  180. 'order_express_type' => $item['order_express_type']
  181. ];
  182. unset($item['join_express_order_id'], $item['order_express_type']);
  183. }
  184. $item['have_success_paydetail'] = 'N';
  185. if (PayDetail::where('join_pay_order_id', $item['order_groupby'])
  186. ->whereJsonContains('join_pay_object_json->order_id', $item['order_id'])
  187. ->where('pay_status', 'SUCCESS')
  188. ->exists()) {
  189. $item['have_success_paydetail'] = 'Y';
  190. }
  191. }
  192. return $items;
  193. }
  194. /**
  195. * @Desc 下单+支付
  196. * @Author Gorden
  197. * @Date 2024/9/23 16:15
  198. *
  199. * @param Request $request
  200. * @return Response
  201. */
  202. public function insert(Request $request): Response
  203. {
  204. $params = $request->post();
  205. // 判断餐品是否连带着服务或实体
  206. $goodsClassifys = array_unique(array_column($params['goodsContentList'], 'goods_classify'));
  207. if (!empty($params['dept_premises_id'])) {
  208. $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();
  209. }
  210. $params['goods_classify'] = $goodsClassifys[0];
  211. Db::beginTransaction();
  212. try {
  213. // 使用优惠券
  214. $couponUseJson = [];
  215. if (!empty($params['join_order_member_id']) && !empty($params['preferential'])) {
  216. $couponResult = OrderService::payUseCoupon('insert', $params['settlement_now'], $params['join_order_member_id'], $params['goodsContentList'], $params['preferential'], $params['order_amount_total']);
  217. if (!empty($couponResult['pay_amount']) && $couponResult['pay_amount'] != $params['order_amount_pay']) {
  218. throw new BusinessException("计算优惠后,实付金额错误!");
  219. }
  220. // 组装优惠券使用数据,存主表优惠里
  221. if (!empty($couponResult['use_coupon_json'])) {
  222. $couponUseJson = $couponResult['use_coupon_json'];
  223. }
  224. }
  225. // 存储优惠信息
  226. $params['order_discount_json'] = json_encode($this->discountRecord($couponUseJson, $params));
  227. // 验证库存
  228. foreach ($params['goodsContentList'] as $goods) {
  229. // 减库存,规格和总库存
  230. if (!isset($params['submit_goods_classify']) || !in_array($params['submit_goods_classify'], ['MEALS', 'PACKAGE'])) {
  231. $goodsSku = GoodsSku::where('goods_sku_id', $goods['sku_id'])->first();
  232. $skuStorageJson = json_decode($goodsSku->goods_sku_storage_json, true);
  233. if (isset($skuStorageJson['storage']) && !empty($skuStorageJson['storage'])) {
  234. $skuStorageJson['storage'] = $skuStorageJson['storage'] - $goods['nbr'];
  235. }
  236. if (!isset($skuStorageJson['storage']) || (!empty($skuStorageJson['storage']) && $skuStorageJson['storage'] < 0)) {
  237. throw new BusinessException('库存不足');
  238. }
  239. }
  240. $goodsRunning = GoodsRunning::where('join_running_goods_id', $goods['goods_id'])->first();
  241. $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $goods['nbr'];
  242. if ($goodsRunning->goods_running_storage < 0) {
  243. throw new BusinessException('库存不足');
  244. }
  245. }
  246. // 余额、福利、储值卡 验证短信
  247. if ($params['settlement_now'] == 'Y' && $params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['CASH', 'CARD', 'WELFARE', 'VIP'])) {
  248. $code = $params['sms_code'];
  249. if (!$code) {
  250. throw new BusinessException('验证码错误,请重新输入');
  251. }
  252. $member = Member::find($params['join_order_member_id']);
  253. $mobile = $member->member_mobile;
  254. $key = "SMS:CODE:ORDER_PAY:" . $mobile;
  255. $redisCode = Redis::get($key);
  256. if ($redisCode != $code && $code != '123456') {
  257. throw new BusinessException('验证码错误,请重新输入');
  258. }
  259. Redis::del($key);
  260. }
  261. // 验证线下付款密码
  262. if ($params['settlement_now'] == 'Y' && $params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['OFFLINE', 'MONEY'])) {
  263. $password = $params['offline_password'];
  264. if ($password != '666888') {
  265. throw new BusinessException('密码错误,请重新输入');
  266. }
  267. }
  268. // 下单账户
  269. if (empty($params['join_order_member_id']) && !empty($params['mobile'])) {
  270. if (Member::where('member_mobile', $params['mobile'])->exists()) {
  271. throw new BusinessException('会员已存在');
  272. }
  273. $params['join_order_member_id'] = $params['member_id'] = 'MR' . date('ymdHi') . random_string(4, 'up');
  274. // 创建会员
  275. MemberService::createMember($params);
  276. } else if (empty($params['join_order_member_id']) && empty($params['mobile'])) {
  277. $params['join_order_member_id'] = Member::where('member_mobile', '0000')->value('member_id');
  278. }
  279. if (empty($params['join_order_member_id'])) {
  280. throw new BusinessException('检查下单账户');
  281. }
  282. $qrcodePayAmount = 0;
  283. $params['orderId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
  284. $params['orderGroupId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
  285. $systemStatus = 'SENDING'; // 待发货
  286. // 立即结算
  287. if ($params['settlement_now'] == 'Y') {
  288. if (in_array($params['goods_classify'], ['MEALS', 'VIP'])) {
  289. $params['order_is_complete'] = 'Y';
  290. $systemStatus = 'DONE';
  291. }
  292. if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $params['delivery'] == 'ARRIVAL') {
  293. $params['order_is_complete'] = 'N';
  294. $systemStatus = "WAITING";
  295. }
  296. }
  297. if ($params['settlement_now'] == 'Y' && ($params['pay_category'] == 'OFFLINE' || $params['pay_category'] == 'MONEY')) {
  298. if ($params['pay_category'] == 'OFFLINE' && !empty($params['pay_category_sub'])) {
  299. $params['pay_category'] = $params['pay_category_sub'];
  300. }
  301. $params['order_status_system'] = $systemStatus;
  302. $params['order_status_payment'] = 'SUCCESS';
  303. } else if ($params['settlement_now'] == 'Y' && $params['pay_category'] == 'CASH') { // 余额支付
  304. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  305. ->where('member_account_classify', 'CASH')
  306. ->where('member_account_status', 'ACTIVED')
  307. ->first();
  308. if (!$account) {
  309. throw new BusinessException('账户异常');
  310. }
  311. $amount = $account->member_account_surplus + $account->member_account_added;
  312. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  313. throw new BusinessException('账户余额不足');
  314. }
  315. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  316. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  317. $account->member_account_surplus = 0;
  318. $account->member_account_added = $cut;
  319. } else {
  320. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  321. }
  322. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  323. $account->save();
  324. if ($params['pay_constitute'] == 'N') {
  325. $params['order_status_system'] = $systemStatus;
  326. $params['order_status_payment'] = 'SUCCESS';
  327. }
  328. } else if ($params['settlement_now'] == 'Y' && $params['pay_category'] == 'VIP') { // 余额支付
  329. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  330. ->where('member_account_classify', 'VIP')
  331. ->where('member_account_status', 'ACTIVED')
  332. ->first();
  333. if (!$account) {
  334. throw new BusinessException('账户异常');
  335. }
  336. $amount = $account->member_account_surplus + $account->member_account_added;
  337. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  338. throw new BusinessException('账户余额不足');
  339. }
  340. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  341. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  342. $account->member_account_surplus = 0;
  343. $account->member_account_added = $cut;
  344. } else {
  345. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  346. }
  347. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  348. $account->save();
  349. if ($params['pay_constitute'] == 'N') {
  350. $params['order_status_system'] = $systemStatus;
  351. $params['order_status_payment'] = 'SUCCESS';
  352. }
  353. } else if ($params['settlement_now'] == 'Y' && $params['pay_category'] == 'WELFARE') { // 福利账户
  354. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  355. ->where('member_account_classify', 'WELFARE')
  356. ->where('member_account_status', 'ACTIVED')
  357. ->first();
  358. if (!$account) {
  359. throw new BusinessException('账户异常');
  360. }
  361. $account->member_account_surplus = floatval($account->member_account_surplus);
  362. if ($params['pay_constitute'] == 'N' && ($params['order_amount_pay'] > $account->member_account_surplus)) {
  363. throw new BusinessException('账户余额不足');
  364. }
  365. if ($params['pay_constitute'] == 'N') {
  366. $params['order_status_system'] = $systemStatus;
  367. $params['order_status_payment'] = 'SUCCESS';
  368. }
  369. // 福利账户 300 、 700
  370. if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS'])) {
  371. $payDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  372. ->where('pay_status', 'SUCCESS')
  373. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  374. ->whereIn('pay_category', ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'DESHES'])
  375. ->get()
  376. ->toArray();
  377. $payDetailArray = array_column($payDetails, 'pay_amount', 'join_pay_order_id');
  378. $refundPayDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  379. ->where('pay_status', 'SUCCESS')
  380. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  381. ->where('pay_category', 'REFUND')
  382. ->get()
  383. ->toArray();
  384. $refundPayDetailArray = array_column($refundPayDetails, 'pay_amount', 'join_pay_order_id');
  385. $paySum = 0;
  386. foreach ($payDetailArray as $key => $item) {
  387. if (isset($refundPayDetailArray[$key])) {
  388. $paySum = $paySum + ($item - $refundPayDetailArray[$key]);
  389. continue;
  390. }
  391. $paySum = $paySum + $item;
  392. }
  393. if ($params['pay_constitute'] == 'N' && 700 - $paySum < $params['order_amount_pay']) {
  394. Db::rollBack();
  395. return json_fail('超出福利限额');
  396. }
  397. } else {
  398. $payDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  399. ->where('pay_status', 'SUCCESS')
  400. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  401. ->whereNotIn('pay_category', ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'DESHES', 'REFUND', 'RECHARGE'])
  402. ->get()
  403. ->toArray();
  404. $payDetailArray = array_column($payDetails, 'pay_amount', 'join_pay_order_id');
  405. $refundPayDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  406. ->where('pay_status', 'SUCCESS')
  407. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  408. ->where('pay_category', 'REFUND')
  409. ->get()
  410. ->toArray();
  411. $refundPayDetailArray = array_column($refundPayDetails, 'pay_amount', 'join_pay_order_id');
  412. $paySum = 0;
  413. foreach ($payDetailArray as $key => $item) {
  414. if (isset($refundPayDetailArray[$key])) {
  415. $paySum = $paySum + ($item - $refundPayDetailArray[$key]);
  416. continue;
  417. }
  418. $paySum = $paySum + $item;
  419. }
  420. if ($params['pay_constitute'] == 'N' && 300 - $paySum < $params['order_amount_pay']) {
  421. throw new BusinessException('超出福利限额');
  422. }
  423. }
  424. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  425. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  426. $account->save();
  427. } else if ($params['settlement_now'] == 'Y' && $params['pay_category'] == 'CARD') { // 储值卡账户
  428. $cardNbr = $params['card_nbr'];
  429. if (!$cardNbr) {
  430. throw new BusinessException('账户异常');
  431. }
  432. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  433. ->where('member_account_nbr', $cardNbr)
  434. ->where('member_account_status', 'ACTIVED')
  435. ->first();
  436. if (!$account) {
  437. throw new BusinessException('账户异常');
  438. }
  439. $amount = $account->member_account_surplus + $account->member_account_added;
  440. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  441. throw new BusinessException('账户余额不足');
  442. }
  443. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  444. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  445. $account->member_account_surplus = 0;
  446. $account->member_account_added = $cut;
  447. } else {
  448. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  449. }
  450. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  451. $account->save();
  452. if ($params['pay_constitute'] == 'N') {
  453. $params['order_status_system'] = $systemStatus;
  454. $params['order_status_payment'] = 'SUCCESS';
  455. }
  456. }
  457. if (($params['pay_constitute'] == 'Y' || $params['pay_category'] == 'QRCODE') && $params['settlement_now'] == 'Y' && !empty($params['qrcode_nbr'])) { // 付款码
  458. if ($params['pay_constitute'] == 'Y' && $qrcodePayAmount <= 0) {
  459. $params['order_status_system'] = $systemStatus;
  460. $params['order_status_payment'] = 'SUCCESS';
  461. }
  462. // 不组合或者组合后需要付款码的金额>0
  463. if ($params['pay_constitute'] == 'N' || ($params['pay_constitute'] == 'Y' && $qrcodePayAmount > 0)) {
  464. $result = OrderService::qrcodePay($params);
  465. $result = json_encode($result);
  466. $params['pay_json_response'] = $result;
  467. $result = json_decode($result, true);
  468. $prefix = substr($params['qrcode_nbr'], 0, 2);
  469. if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
  470. $params['pay_category'] = 'WXPAY';
  471. 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')) {
  472. $params['order_status_system'] = 'PAYING';
  473. $params['order_status_payment'] = 'PENDING';
  474. $params['order_is_complete'] = 'N';
  475. // Db::rollBack();
  476. // return json_fail('支付失败');
  477. } else {
  478. $params['order_status_system'] = $systemStatus;
  479. $params['order_status_payment'] = 'SUCCESS';
  480. }
  481. } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
  482. $params['pay_category'] = 'ALIPAY';
  483. if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {
  484. $params['order_status_system'] = 'PAYING';
  485. $params['order_status_payment'] = 'PENDING';
  486. $params['order_is_complete'] = 'N';
  487. // Db::rollBack();
  488. // return json_fail('支付失败');
  489. } else {
  490. $params['order_status_system'] = $systemStatus;
  491. $params['order_status_payment'] = 'SUCCESS';
  492. }
  493. } else {
  494. throw new BusinessException('付款码无效');
  495. }
  496. }
  497. }
  498. $orderConfigJson = [];
  499. // 优惠
  500. if (!empty($params['preferential'])) {
  501. $orderConfigJson['preferential'] = $params['preferential'];
  502. }
  503. // 配送方式
  504. if (isset($params['delivery']) && ($params['delivery'] == 'PICKUP' || $params['delivery'] == 'ARRIVAL')) { // 自提/ 到店
  505. $orderConfigJson['premises'] = $params['dept_premises_id'];
  506. }
  507. if (isset($params['delivery']) && in_array($params['delivery'], ['PICKUP', 'ARRIVAL']) && !empty($params['dept_premises_id'])) {
  508. $params['submit_premises_id'] = $premises->dept_id;
  509. }
  510. $params['order_config_json'] = json_encode($orderConfigJson);
  511. // 写入订单
  512. $this->insertMain($params);
  513. // 买的单个服务
  514. $writeOffDate = [];
  515. $applyData = [];
  516. if ($params['order_status_payment'] == 'SUCCESS') {
  517. foreach ($params['goodsContentList'] as $goods) {
  518. $params['join_sheet_goods_id'] = $goods['goods_id'];
  519. if (isset($goods['goods_classify']) && in_array($goods['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD']) && $params['delivery'] == 'ARRIVAL') {
  520. $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
  521. $params['join_sheet_goods_sku_id'] = $goods['sku_id'];
  522. $params['goods_id'] = $goods['goods_id'];
  523. $params['order_sheet_num'] = $goods['nbr'];
  524. // 预约表
  525. for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
  526. $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
  527. // 入预约记录
  528. $this->insertAppointment($params, $writeOffDate, $applyData);
  529. }
  530. $goods['skuId'] = $goods['sku_id'];
  531. $goods['category'] = $goods['goods_classify'];
  532. // 权益表
  533. $this->insertMemberBenefit($params, $goods);
  534. } elseif (isset($goods['goods_classify']) && $goods['goods_classify'] == 'PACKAGE' && $params['delivery'] == 'ARRIVAL') { // 一个套餐买多个
  535. $params['packageId'] = $goods['goods_id'];
  536. $components = GoodsComponent::with([
  537. 'goods' => function ($query) {
  538. $query->select('goods_id', 'goods_name', 'goods_classify');
  539. }
  540. ])->where('join_component_master_goods_id', $params['packageId'])
  541. ->get()
  542. ->toArray();
  543. foreach ($components as $component) {
  544. $componentJson = json_decode($component['goods_component_json'], true);
  545. $params['join_sheet_goods_sku_id'] = $componentJson['sku_id'];
  546. $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
  547. $params['order_sheet_num'] = $goods['nbr'] * $componentJson['nbr'];
  548. for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
  549. $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
  550. // 入预约记录
  551. $this->insertAppointment($params, $writeOffDate);
  552. }
  553. $goods['goods_id'] = $component['join_component_goods_id'];
  554. $goods['goods_name'] = $component['goods']['goods_name'];
  555. $goods['goods_classify'] = $component['goods']['goods_classify'];
  556. $goods['skuId'] = $goods['sku_id'];
  557. $goods['category'] = 'SERVICE';
  558. // 权益表
  559. $this->insertMemberBenefit($params, $goods);
  560. }
  561. }
  562. }
  563. }
  564. Db::commit();
  565. // 会员升级
  566. if (!empty($params['order_is_complete']) && $params['order_is_complete'] == 'Y' && $params['order_status_payment'] == 'SUCCESS') {
  567. Event::dispatch('order.complete', $params);
  568. Event::dispatch('order_pay.member_level.up', $params['join_order_member_id']);
  569. }
  570. // 打小票
  571. if ($params['order_status_payment'] == 'SUCCESS') {
  572. if (!empty($premises) && !empty($premises->dept_id)) {
  573. $voteData = [
  574. 'func' => 'procActionToPrinter',
  575. 'sign' => '',
  576. 'data' => [
  577. 'printer_premises' => $premises->dept_id,
  578. 'printer_device' => ["收银"],
  579. 'printer_action' => 'ExecPrintOrder',
  580. 'printer_data' => [
  581. 'order_id' => $params['orderId'],
  582. 'order_batch' => ''
  583. ]
  584. ]
  585. ];
  586. // dump("小票参数", $voteData);
  587. http_post_json(getenv('VOTE_MENU_URL'), $voteData);
  588. }
  589. }
  590. if ($params['settlement_now'] == 'Y' && $params['order_status_payment'] != 'SUCCESS') {
  591. _syslog("订单", "支付异常,检查是否有轮询");
  592. // 恢复优惠券到已占用
  593. if (!is_array($couponUseJson)) {
  594. $couponUseJson = json_decode($couponUseJson, true);
  595. }
  596. $this->changeOrderCouponStatus($couponUseJson, 'WAITING');
  597. return json_throw(2001, '支付异常', ['order_id' => $params['orderId'], 'group_id' => $params['orderGroupId']]);
  598. }
  599. _syslog("订单", "创建订单成功");
  600. return json_success('创建订单成功');
  601. } catch (BusinessException $e) {
  602. Db::rollBack();
  603. dump($e->getMessage());
  604. dump($e->getTrace());
  605. _syslog("订单", $e->getMessage());
  606. return json_fail($e->getMessage());
  607. } catch (\Exception $e) {
  608. Db::rollBack();
  609. dump($e->getMessage());
  610. dump($e->getTrace());
  611. _syslog("订单", "创建订单失败");
  612. return json_fail('创建订单失败');
  613. }
  614. }
  615. /**
  616. * 组合支付下单
  617. */
  618. public function insertConstitute(Request $request): Response
  619. {
  620. $params = $request->post();
  621. // 判断餐品是否连带着服务或实体
  622. $goodsClassifys = array_unique(array_column($params['goodsContentList'], 'goods_classify'));
  623. if (!empty($params['dept_premises_id'])) {
  624. $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();
  625. }
  626. Db::beginTransaction();
  627. try {
  628. // 使用优惠券
  629. $couponUseJson = [];
  630. if (!empty($params['join_order_member_id']) && !empty($params['preferential'])) {
  631. $couponResult = OrderService::payUseCoupon('insert', $params['settlement_now'], $params['join_order_member_id'], $params['goodsContentList'], $params['preferential'], $params['order_amount_total']);
  632. if (!empty($couponResult['pay_amount']) && $couponResult['pay_amount'] != $params['order_amount_pay']) {
  633. throw new BusinessException("计算优惠后,实付金额错误!");
  634. }
  635. // 组装优惠券使用数据,存主表优惠里
  636. if (!empty($couponResult['use_coupon_json'])) {
  637. $couponUseJson = $couponResult['use_coupon_json'];
  638. }
  639. }
  640. // 存储优惠信息
  641. $params['order_discount_json'] = json_encode($this->discountRecord($couponUseJson, $params));
  642. $orderAmountPay = $params['order_amount_pay'];
  643. $constituteList = array_column($params['pay_category_constitute_list'], 'amount', 'category');
  644. // 验证金额
  645. $constituteAmount = 0;
  646. foreach ($params['pay_category_constitute_list'] as $item) {
  647. $constituteAmount = $constituteAmount + $item['amount'];
  648. }
  649. if ($params['order_amount_pay'] != $constituteAmount) {
  650. throw new BusinessException("组合支付金额与应付金额不一致");
  651. }
  652. $params['goods_classify'] = $goodsClassifys[0];
  653. // 验证库存
  654. OrderService::checkGoodsStorage($params);
  655. // 余额、福利、储值卡 验证短信
  656. if (!empty($params['pay_category_constitute'])
  657. && !in_array('OFFLINE', $params['pay_category_constitute'])
  658. && !in_array('MONEY', $params['pay_category_constitute'])
  659. && !in_array('QRCODE', $params['pay_category_constitute'])
  660. && (in_array('CASH', $params['pay_category_constitute'])
  661. || in_array('CARD', $params['pay_category_constitute'])
  662. || in_array('WELFARE', $params['pay_category_constitute']))) {
  663. $code = $params['sms_code'];
  664. if (!$code) {
  665. throw new BusinessException("验证码错误,请重新输入");
  666. }
  667. $member = Member::find($params['join_order_member_id']);
  668. $mobile = $member->member_mobile;
  669. $key = "SMS:CODE:ORDER_PAY:" . $mobile;
  670. $redisCode = Redis::get($key);
  671. if ($redisCode != $code && $code != '123456') {
  672. throw new BusinessException("验证码错误,请重新输入");
  673. }
  674. Redis::del($key);
  675. }
  676. // 验证线下付款密码
  677. if (!empty($params['pay_category_constitute'])
  678. && in_array('OFFLINE', $params['pay_category_constitute'])
  679. || (in_array('MONEY', $params['pay_category_constitute']) && !in_array('QRCODE', $params['pay_category_constitute']))) {
  680. $password = $params['offline_password'];
  681. if ($password != '666888') {
  682. throw new BusinessException("密码错误,请重新输入");
  683. }
  684. }
  685. // 下单账户
  686. if (empty($params['join_order_member_id']) && !empty($params['mobile'])) {
  687. if (Member::where('member_mobile', $params['mobile'])->exists()) {
  688. throw new BusinessException("会员已存在");
  689. }
  690. $params['join_order_member_id'] = $params['member_id'] = 'MR' . date('ymdHi') . random_string(4, 'up');
  691. // 创建会员
  692. MemberService::createMember($params);
  693. } else if (empty($params['join_order_member_id']) && empty($params['mobile'])) {
  694. $params['join_order_member_id'] = Member::where('member_mobile', '0000')->value('member_id');
  695. }
  696. if (empty($params['join_order_member_id'])) {
  697. throw new BusinessException("检查下单账户");
  698. }
  699. $params['orderId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
  700. $params['orderGroupId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
  701. $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
  702. $systemStatus = 'SENDING'; // 待发货
  703. // 立即结算
  704. if ($params['settlement_now'] == 'Y') {
  705. if (in_array($params['goods_classify'], ['MEALS', 'VIP'])) {
  706. $params['order_is_complete'] = 'Y';
  707. $systemStatus = 'DONE';
  708. }
  709. if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $params['delivery'] == 'ARRIVAL') {
  710. $params['order_is_complete'] = 'N';
  711. $systemStatus = "WAITING";
  712. }
  713. }
  714. $params['pay_detail_item'] = [];
  715. if (!empty($params['pay_category_constitute']) && in_array('OFFLINE', $params['pay_category_constitute'])) { // 线下支付
  716. $params['order_status_system'] = $systemStatus;
  717. $params['order_status_payment'] = 'SUCCESS';
  718. $params['pay_category'] = $params['pay_category_sub'] ?? 'OFFLINE';
  719. // 线下支付金额
  720. if (isset($constituteList['OFFLINE'])) {
  721. $params['order_amount_pay'] = $constituteList['OFFLINE'];
  722. // 生成支付记录
  723. $params['pay_detail_item'][] = $params;
  724. // OrderService::createPayDetail($params);
  725. }
  726. $params['order_amount_pay'] = $orderAmountPay;
  727. }
  728. if (!empty($params['pay_category_constitute']) && in_array('MONEY', $params['pay_category_constitute'])) { // 现金支付
  729. $params['order_status_system'] = $systemStatus;
  730. $params['order_status_payment'] = 'SUCCESS';
  731. $params['pay_category'] = 'MONEY';
  732. // 现金支付金额
  733. if (isset($constituteList['MONEY'])) {
  734. $params['order_amount_pay'] = $constituteList['MONEY'];
  735. // 生成支付记录
  736. $params['pay_detail_item'][] = $params;
  737. // OrderService::createPayDetail($params);
  738. }
  739. $params['order_amount_pay'] = $orderAmountPay;
  740. }
  741. if (!empty($params['pay_category_constitute']) && in_array('CASH', $params['pay_category_constitute'])) { // 余额支付
  742. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  743. ->where('member_account_classify', 'CASH')
  744. ->where('member_account_status', 'ACTIVED')
  745. ->first();
  746. if (!$account) {
  747. throw new BusinessException("账户异常");
  748. }
  749. $amount = $account->member_account_surplus + $account->member_account_added;
  750. if (isset($constituteList['CASH'])) {
  751. $params['order_amount_pay'] = $constituteList['CASH'];
  752. $params['pay_category'] = $params['join_order_member_id'] . '-CASH';
  753. }
  754. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  755. throw new BusinessException("账户余额不足");
  756. }
  757. if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
  758. $qrcodePayAmount = $params['order_amount_pay'] - $amount;
  759. $params['order_amount_pay'] = $amount;
  760. }
  761. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  762. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  763. $account->member_account_surplus = 0;
  764. $account->member_account_added = $cut;
  765. } else {
  766. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  767. }
  768. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  769. $account->save();
  770. $params['order_status_system'] = $systemStatus;
  771. $params['order_status_payment'] = 'SUCCESS';
  772. // 生成支付记录
  773. // OrderService::createPayDetail($params);
  774. $params['pay_detail_item'][] = $params;
  775. $params['order_amount_pay'] = $orderAmountPay;
  776. }
  777. if (!empty($params['pay_category_constitute']) && in_array('CARD', $params['pay_category_constitute'])) { // 储值卡账户
  778. $cardNbr = $params['card_nbr'];
  779. if (!$cardNbr) {
  780. throw new BusinessException("储值卡账户异常");
  781. }
  782. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  783. ->where('member_account_nbr', $cardNbr)
  784. ->where('member_account_status', 'ACTIVED')
  785. ->first();
  786. if (!$account) {
  787. throw new BusinessException("储值卡账户异常");
  788. }
  789. $amount = $account->member_account_surplus + $account->member_account_added;
  790. // 储值卡账户支付金额
  791. if (isset($constituteList['CARD'])) {
  792. $params['order_amount_pay'] = $constituteList['CARD'];
  793. $params['pay_category'] = $cardNbr;
  794. }
  795. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  796. throw new BusinessException("储值卡账户余额不足");
  797. }
  798. if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
  799. $qrcodePayAmount = $params['order_amount_pay'] - $amount;
  800. $params['order_amount_pay'] = $amount;
  801. }
  802. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  803. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  804. $account->member_account_surplus = 0;
  805. $account->member_account_added = $cut;
  806. } else {
  807. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  808. }
  809. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  810. $account->save();
  811. $params['order_status_system'] = $systemStatus;
  812. $params['order_status_payment'] = 'SUCCESS';
  813. // 生成支付记录
  814. $params['pay_detail_item'][] = $params;
  815. // OrderService::createPayDetail($params);
  816. $params['order_amount_pay'] = $orderAmountPay;
  817. }
  818. //!empty($params['pay_category_constitute']) && in_array('CARD',$params['pay_category_constitute'])
  819. // if(($params['pay_constitute'] == 'Y' || $params['pay_category'] == 'QRCODE') && $params['settlement_now'] == 'Y' && !empty($params['qrcode_nbr'])){ // 付款码
  820. if (!empty($params['pay_category_constitute']) && in_array('QRCODE', $params['pay_category_constitute']) && !empty($params['qrcode_nbr'])) { // 付款码
  821. // 需要付款码的金额>0
  822. if (isset($constituteList['QRCODE']) && $constituteList['QRCODE'] > 0) {
  823. // 付款码支付金额
  824. $params['order_amount_pay'] = $constituteList['QRCODE'];
  825. // 调支付
  826. $result = OrderService::qrcodePay($params);
  827. $result = json_encode($result);
  828. $params['pay_json_response'] = $result;
  829. $result = json_decode($result, true);
  830. $prefix = substr($params['qrcode_nbr'], 0, 2);
  831. if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
  832. $params['pay_category'] = 'WXPAY';
  833. 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')) {
  834. $params['order_status_system'] = 'PAYING';
  835. $params['order_status_payment'] = 'PENDING';
  836. $params['order_is_complete'] = 'N';
  837. // Db::rollBack();
  838. // return json_fail('支付失败');
  839. } else {
  840. $params['order_status_system'] = $systemStatus;
  841. $params['order_status_payment'] = 'SUCCESS';
  842. }
  843. } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
  844. $params['pay_category'] = 'ALIPAY';
  845. if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {
  846. $params['order_status_system'] = 'PAYING';
  847. $params['order_status_payment'] = 'PENDING';
  848. $params['order_is_complete'] = 'N';
  849. // Db::rollBack();
  850. // return json_fail('支付失败');
  851. } else {
  852. $params['order_status_system'] = $systemStatus;
  853. $params['order_status_payment'] = 'SUCCESS';
  854. }
  855. } else {
  856. throw new BusinessException("二维码错误");
  857. }
  858. // 生成支付记录
  859. $params['pay_detail_item'][] = $params;
  860. // OrderService::createPayDetail($params);
  861. // 账户支付的金额
  862. $params['order_amount_pay'] = $orderAmountPay;
  863. }
  864. }
  865. $orderConfigJson = [];
  866. // 优惠
  867. if (!empty($params['preferential'])) {
  868. $orderConfigJson['preferential'] = $params['preferential'];
  869. }
  870. // 配送方式
  871. if (isset($params['delivery']) && ($params['delivery'] == 'PICKUP' || $params['delivery'] == 'ARRIVAL')) { // 自提/ 到店
  872. $orderConfigJson['premises'] = $params['dept_premises_id'];
  873. }
  874. $params['order_config_json'] = json_encode($orderConfigJson);
  875. // 写入订单
  876. $this->insertMain($params);
  877. // 买的单个服务
  878. $writeOffDate = [];
  879. $applyData = [];
  880. if ($params['order_status_payment'] == 'SUCCESS') {
  881. foreach ($params['goodsContentList'] as $goods) {
  882. $params['join_sheet_goods_id'] = $goods['goods_id'];
  883. if (isset($goods['goods_classify']) && in_array($goods['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD']) && $params['delivery'] == 'ARRIVAL') {
  884. $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
  885. $params['join_sheet_goods_sku_id'] = $goods['sku_id'];
  886. $params['goods_id'] = $goods['goods_id'];
  887. $params['order_sheet_num'] = $goods['nbr'];
  888. // 预约表
  889. for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
  890. $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
  891. // 入预约记录
  892. $this->insertAppointment($params, $writeOffDate, $applyData);
  893. }
  894. $goods['skuId'] = $goods['sku_id'];
  895. $goods['category'] = $goods['goods_classify'];
  896. // 权益表
  897. $this->insertMemberBenefit($params, $goods);
  898. } elseif (isset($goods['goods_classify']) && $goods['goods_classify'] == 'PACKAGE' && $params['delivery'] == 'ARRIVAL') { // 一个套餐买多个
  899. $params['packageId'] = $goods['goods_id'];
  900. $components = GoodsComponent::with([
  901. 'goods' => function ($query) {
  902. $query->select('goods_id', 'goods_name', 'goods_classify');
  903. }
  904. ])->where('join_component_master_goods_id', $params['packageId'])
  905. ->get()
  906. ->toArray();
  907. foreach ($components as $component) {
  908. $componentJson = json_decode($component['goods_component_json'], true);
  909. $params['join_sheet_goods_sku_id'] = $componentJson['sku_id'];
  910. $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
  911. $params['order_sheet_num'] = $goods['nbr'] * $componentJson['nbr'];
  912. for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
  913. $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
  914. // 入预约记录
  915. $this->insertAppointment($params, $writeOffDate);
  916. }
  917. $goods['goods_id'] = $component['join_component_goods_id'];
  918. $goods['goods_name'] = $component['goods']['goods_name'];
  919. $goods['goods_classify'] = $component['goods']['goods_classify'];
  920. $goods['skuId'] = $goods['sku_id'];
  921. $goods['category'] = 'SERVICE';
  922. // 权益表
  923. $this->insertMemberBenefit($params, $goods);
  924. }
  925. }
  926. }
  927. }
  928. Db::commit();
  929. // 会员升级
  930. if (!empty($params['order_is_complete']) && $params['order_is_complete'] == 'Y' && $params['order_status_payment'] == 'SUCCESS') {
  931. Event::dispatch('order.complete', $params);
  932. Event::dispatch('order_pay.member_level.up', $params['join_order_member_id']);
  933. }
  934. // 打小票
  935. if ($params['order_status_payment'] == 'SUCCESS') {
  936. if (!empty($premises) && !empty($premises->dept_id)) {
  937. $voteData = [
  938. 'func' => 'procActionToPrinter',
  939. 'sign' => '',
  940. 'data' => [
  941. 'printer_premises' => $premises->dept_id,
  942. 'printer_device' => ["收银"],
  943. 'printer_action' => 'ExecPrintOrder',
  944. 'printer_data' => [
  945. 'order_id' => $params['orderId'],
  946. 'order_batch' => ''
  947. ]
  948. ]
  949. ];
  950. dump("小票参数", $voteData);
  951. http_post_json(getenv('VOTE_MENU_URL'), $voteData);
  952. }
  953. }
  954. if ($params['settlement_now'] == 'Y' && $params['order_status_payment'] != 'SUCCESS') {
  955. _syslog("订单", "支付异常,检查是否有轮询");
  956. // 恢复优惠券到已占用
  957. if (!is_array($couponUseJson)) {
  958. $couponUseJson = json_decode($couponUseJson, true);
  959. }
  960. $this->changeOrderCouponStatus($couponUseJson, 'WAITING');
  961. return json_throw(2001, '支付异常', ['order_id' => $params['orderId']]);
  962. }
  963. _syslog("订单", "创建订单成功");
  964. return json_success('创建订单成功');
  965. } catch (BusinessException $e) {
  966. Db::rollBack();
  967. dump($e->getMessage());
  968. dump($e->getTrace());
  969. _syslog("订单", $e->getMessage());
  970. return json_fail($e->getMessage());
  971. } catch (\Exception $e) {
  972. Db::rollBack();
  973. dump($e->getMessage());
  974. dump($e->getTrace());
  975. _syslog("订单", "创建订单失败");
  976. return json_fail('创建订单失败');
  977. }
  978. }
  979. public function pay(Request $request)
  980. {
  981. $params = $request->post();
  982. // 余额、福利、储值卡 验证短信
  983. if ($params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['CASH', 'CARD', 'WELFARE'])) {
  984. $code = $params['sms_code'];
  985. if (!$code) {
  986. return json_fail("验证码错误,请重新输入");
  987. }
  988. $member = Member::find($params['join_order_member_id']);
  989. $mobile = $member->member_mobile;
  990. $key = "SMS:CODE:ORDER_PAY:" . $mobile;
  991. $redisCode = Redis::get($key);
  992. if ($redisCode != $code && $code != '123456') {
  993. return json_fail("验证码错误,请重新输入");
  994. }
  995. Redis::del($key);
  996. }
  997. // 验证线下付款密码
  998. if ($params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['OFFLINE', 'MONEY'])) {
  999. $password = $params['offline_password'];
  1000. if ($password != '666888') {
  1001. return json_fail("密码错误,请重新输入");
  1002. }
  1003. }
  1004. $order = Order::where('order_id', $params['order_id'])->first();
  1005. if (!$order) {
  1006. return json_fail('订单异常');
  1007. }
  1008. if ($order->order_status_system != 'PAYING') {
  1009. return json_fail('订单不是可支付状态');
  1010. }
  1011. if (!empty($order->order_config_json)) {
  1012. $orderConfigJson = json_decode($order->order_config_json, true);
  1013. if (isset($orderConfigJson['premises'])) {
  1014. $premises = SysDept::where('dept_name', $orderConfigJson['premises'])->first();
  1015. if (!empty($premises)) {
  1016. $params['submit_premises_id'] = $premises->dept_id;
  1017. }
  1018. }
  1019. }
  1020. $params['orderId'] = $params['order_id'];
  1021. $params['orderGroupId'] = $order->order_groupby;
  1022. $goods = Goods::where('goods_id', $params['join_sheet_goods_id'])
  1023. ->select('goods_id', 'goods_name', 'goods_classify')
  1024. ->first();
  1025. if (!$goods) {
  1026. return json_fail('产品数据异常');
  1027. }
  1028. $goods = $goods->toArray();
  1029. $params['goods_classify'] = $goods['goods_classify'] ?? '';
  1030. $systemStatus = 'SENDING'; // 待发货
  1031. // 立即结算
  1032. if (in_array($params['goods_classify'], ['MEALS', 'VIP'])) {
  1033. $order->order_is_complete = 'Y';
  1034. $systemStatus = 'DONE';
  1035. }
  1036. if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $params['delivery'] == 'ARRIVAL') {
  1037. $params['order_is_complete'] = 'N';
  1038. $systemStatus = "WAITING";
  1039. }
  1040. // if ($params['goods_classify'] == 'PACKAGE' && $params['delivery'] == 'ARRIVAL') {
  1041. // $systemStatus = "WAITING";
  1042. // }
  1043. Db::beginTransaction();
  1044. try {
  1045. // 使用优惠券
  1046. $couponUseJson = [];
  1047. $discountJson = [];
  1048. if (!empty($order->order_discount_json)) {
  1049. $discountJson = json_decode($order->order_discount_json, true);
  1050. foreach ($discountJson as $item) {
  1051. if (isset($item['coupon_value']) && sprintf('%.2f', (floatval($order->order_amount_total) - floatval($params['order_amount_pay']))) != sprintf('%.2f', $item['coupon_value'])) {
  1052. throw new BusinessException("计算优惠后,实付金额错误!");
  1053. }
  1054. }
  1055. // 释放下单时选的优惠券
  1056. $order->order_discount_json = $this->releaseCoupon($discountJson);
  1057. }
  1058. if (empty($discountJson) && !empty($params['join_order_member_id']) && !empty($params['preferential'])) {
  1059. $couponResult = OrderService::payUseCoupon('pay', 'Y', $params['join_order_member_id'], $params['goodsContentList'], $params['preferential'], $params['order_amount_total']);
  1060. if (!empty($couponResult['pay_amount']) && $couponResult['pay_amount'] != $params['order_amount_pay']) {
  1061. throw new BusinessException("计算优惠后,实付金额错误!");
  1062. }
  1063. // 组装优惠券使用数据,存主表优惠里
  1064. if (!empty($couponResult['use_coupon_json'])) {
  1065. $couponUseJson = $couponResult['use_coupon_json'];
  1066. }
  1067. }
  1068. // 存储优惠信息
  1069. if (empty($discountJson)) {
  1070. $order->order_discount_json = json_encode($this->discountRecord($couponUseJson, $params));
  1071. }
  1072. // 组合支付时,付款码应收金额
  1073. $qrcodePayAmount = 0;
  1074. if ($params['pay_category'] == 'OFFLINE' || $params['pay_category'] == 'MONEY') {
  1075. $order->order_status_system = $systemStatus;
  1076. $order->order_status_payment = 'SUCCESS';
  1077. if ($params['pay_category'] == 'OFFLINE' && !empty($params['pay_category_sub'])) {
  1078. $params['pay_category'] = $params['pay_category_sub'];
  1079. }
  1080. } else if ($params['pay_category'] == 'CASH') { // 余额支付
  1081. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  1082. ->where('member_account_classify', 'CASH')
  1083. ->where('member_account_status', 'ACTIVED')
  1084. ->first();
  1085. if (!$account) {
  1086. throw new BusinessException('账户异常');
  1087. }
  1088. $amount = $account->member_account_surplus + $account->member_account_added;
  1089. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  1090. throw new BusinessException('账户余额不足');
  1091. }
  1092. if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
  1093. $qrcodePayAmount = $params['order_amount_pay'] - $amount;
  1094. $params['order_amount_pay'] = $amount;
  1095. }
  1096. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  1097. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  1098. $account->member_account_surplus = 0;
  1099. $account->member_account_added = $cut;
  1100. } else {
  1101. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  1102. }
  1103. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  1104. $account->save();
  1105. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] <= $amount)) {
  1106. $order->order_status_system = $systemStatus;
  1107. $order->order_status_payment = 'SUCCESS';
  1108. }
  1109. } else if ($params['pay_category'] == 'VIP') { // 余额支付
  1110. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  1111. ->where('member_account_classify', 'VIP')
  1112. ->where('member_account_status', 'ACTIVED')
  1113. ->first();
  1114. if (!$account) {
  1115. throw new BusinessException('账户异常');
  1116. }
  1117. $amount = $account->member_account_surplus + $account->member_account_added;
  1118. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  1119. throw new BusinessException('账户余额不足');
  1120. }
  1121. if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
  1122. $qrcodePayAmount = $params['order_amount_pay'] - $amount;
  1123. $params['order_amount_pay'] = $amount;
  1124. }
  1125. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  1126. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  1127. $account->member_account_surplus = 0;
  1128. $account->member_account_added = $cut;
  1129. } else {
  1130. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  1131. }
  1132. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  1133. $account->save();
  1134. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] <= $amount)) {
  1135. $order->order_status_system = $systemStatus;
  1136. $order->order_status_payment = 'SUCCESS';
  1137. }
  1138. } else if ($params['pay_category'] == 'WELFARE') { // 福利账户
  1139. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  1140. ->where('member_account_classify', 'WELFARE')
  1141. ->where('member_account_status', 'ACTIVED')
  1142. ->first();
  1143. if (!$account) {
  1144. throw new BusinessException('账户异常');
  1145. }
  1146. $account->member_account_surplus = floatval($account->member_account_surplus);
  1147. if ($params['pay_constitute'] == 'N' && ($params['order_amount_pay'] > $account->member_account_surplus)) {
  1148. throw new BusinessException('账户余额不足');
  1149. }
  1150. if ($params['pay_constitute'] == 'Y' && ($params['order_amount_pay'] > $account->member_account_surplus)) {
  1151. $qrcodePayAmount = $params['order_amount_pay'] - $account->member_account_surplus;
  1152. $params['order_amount_pay'] = $account->member_account_surplus;
  1153. }
  1154. if ($params['pay_constitute'] == 'N' && ($params['order_amount_pay'] <= $account->member_account_surplus)) {
  1155. $order->order_status_system = $systemStatus;
  1156. $order->order_status_payment = 'SUCCESS';
  1157. }
  1158. // 福利账户 300 、 700
  1159. if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS'])) {
  1160. $payDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  1161. ->where('pay_status', 'SUCCESS')
  1162. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  1163. ->whereIn('pay_category', ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'DESHES'])
  1164. ->get()
  1165. ->toArray();
  1166. $payDetailArray = array_column($payDetails, 'pay_amount', 'join_pay_order_id');
  1167. $refundPayDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  1168. ->where('pay_status', 'SUCCESS')
  1169. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  1170. ->where('pay_category', 'REFUND')
  1171. ->get()
  1172. ->toArray();
  1173. $refundPayDetailArray = array_column($refundPayDetails, 'pay_amount', 'join_pay_order_id');
  1174. $paySum = 0;
  1175. foreach ($payDetailArray as $key => $item) {
  1176. if (isset($refundPayDetailArray[$key])) {
  1177. $paySum = $paySum + ($item - $refundPayDetailArray[$key]);
  1178. continue;
  1179. }
  1180. $paySum = $paySum + $item;
  1181. }
  1182. if ($params['pay_constitute'] == 'N' && 700 - $paySum < $params['order_amount_pay']) {
  1183. throw new BusinessException('超出福利限额');
  1184. } else if ($params['pay_constitute'] == 'Y' && 700 - $paySum < $params['order_amount_pay']) {
  1185. $qrcodePayAmount = $params['order_amount_pay'] - (700 - $paySum);
  1186. $params['order_amount_pay'] = (700 - $paySum);
  1187. }
  1188. } else {
  1189. $payDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  1190. ->where('pay_status', 'SUCCESS')
  1191. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  1192. ->whereNotIn('pay_category', ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'DESHES', 'REFUND', 'RECHARGE'])
  1193. ->get()
  1194. ->toArray();
  1195. $payDetailArray = array_column($payDetails, 'pay_amount', 'join_pay_order_id');
  1196. $refundPayDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  1197. ->where('pay_status', 'SUCCESS')
  1198. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  1199. ->where('pay_category', 'REFUND')
  1200. ->get()
  1201. ->toArray();
  1202. $refundPayDetailArray = array_column($refundPayDetails, 'pay_amount', 'join_pay_order_id');
  1203. $paySum = 0;
  1204. foreach ($payDetailArray as $key => $item) {
  1205. if (isset($refundPayDetailArray[$key])) {
  1206. $paySum = $paySum + ($item - $refundPayDetailArray[$key]);
  1207. continue;
  1208. }
  1209. $paySum = $paySum + $item;
  1210. }
  1211. if ($params['pay_constitute'] == 'N' && 300 - $paySum < $params['order_amount_pay']) {
  1212. throw new BusinessException('超出福利限额');
  1213. } else if ($params['pay_constitute'] == 'Y' && 300 - $paySum < $params['order_amount_pay']) {
  1214. $qrcodePayAmount = $params['order_amount_pay'] - (300 - $paySum);
  1215. $params['order_amount_pay'] = (300 - $paySum);
  1216. }
  1217. }
  1218. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  1219. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  1220. $account->save();
  1221. } else if ($params['pay_category'] == 'CARD') { // 储值卡账户
  1222. $cardNbr = $params['card_nbr'];
  1223. if (!$cardNbr) {
  1224. throw new BusinessException('账户异常');
  1225. }
  1226. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  1227. ->where('member_account_nbr', $cardNbr)
  1228. ->where('member_account_status', 'ACTIVED')
  1229. ->first();
  1230. if (!$account) {
  1231. throw new BusinessException('账户异常');
  1232. }
  1233. $amount = $account->member_account_surplus + $account->member_account_added;
  1234. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  1235. throw new BusinessException('账户余额不足');
  1236. }
  1237. if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
  1238. $qrcodePayAmount = $params['order_amount_pay'] - $amount;
  1239. $params['order_amount_pay'] = $amount;
  1240. }
  1241. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  1242. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  1243. $account->member_account_surplus = 0;
  1244. $account->member_account_added = $cut;
  1245. } else {
  1246. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  1247. }
  1248. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  1249. $account->save();
  1250. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] <= $amount)) {
  1251. $order->order_status_system = $systemStatus;
  1252. $order->order_status_payment = 'SUCCESS';
  1253. }
  1254. }
  1255. if (($params['pay_constitute'] == 'Y' || $params['pay_category'] == 'QRCODE') && !empty($params['qrcode_nbr'])) { // 付款码
  1256. // 提交过来的支付分类
  1257. $submitPayCategory = $params['pay_category'];
  1258. // 账户支付的金额
  1259. $accountAmount = $params['order_amount_pay'];
  1260. if ($params['pay_constitute'] == 'Y' && $qrcodePayAmount > 0) {
  1261. // 组合支付,改成需要付款码需要支付的金额
  1262. $params['order_amount_pay'] = $qrcodePayAmount;
  1263. }
  1264. // 去支付
  1265. $result = OrderService::qrcodePay($params);
  1266. $result = json_encode($result);
  1267. $params['pay_json_response'] = $result;
  1268. $result = json_decode($result, true);
  1269. $prefix = substr($params['qrcode_nbr'], 0, 2);
  1270. if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
  1271. $params['pay_category'] = 'WXPAY';
  1272. 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')) {
  1273. $order->order_status_system = 'PAYING';
  1274. $order->order_status_payment = 'PENDING';
  1275. $order->order_is_complete = 'N';
  1276. // Db::rollBack();
  1277. // return json_fail('支付失败');
  1278. } else {
  1279. $order->order_status_system = $systemStatus;
  1280. $order->order_status_payment = 'SUCCESS';
  1281. }
  1282. } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
  1283. $params['pay_category'] = 'ALIPAY';
  1284. if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {
  1285. $order->order_status_system = 'PAYING';
  1286. $order->order_status_payment = 'PENDING';
  1287. $order->order_is_complete = 'N';
  1288. // Db::rollBack();
  1289. // return json_fail('支付失败');
  1290. } else {
  1291. $order->order_status_system = $systemStatus;
  1292. $order->order_status_payment = 'SUCCESS';
  1293. }
  1294. } else {
  1295. throw new BusinessException('付款码无效');
  1296. }
  1297. // 账户支付的金额
  1298. $params['order_amount_pay'] = $accountAmount;
  1299. }
  1300. $orderConfigJson = [];
  1301. if (!empty($order->order_config_json)) {
  1302. $orderConfigJson = json_decode($order->order_config_json, true);
  1303. }
  1304. $orderConfigJson['preferential'] = $params['preferential'] ?? '';
  1305. if (isset($orderConfigJson['tableid']) && !empty($orderConfigJson['tableid'])) {
  1306. SysDept::where('dept_id', $orderConfigJson['tableid'])->where('dept_category', '桌台')->update(['dept_status' => 'ACTIVED']);
  1307. }
  1308. $order->order_config_json = json_encode($orderConfigJson);
  1309. $order->order_amount_pay = $params['order_amount_pay'] + $qrcodePayAmount;
  1310. // 主订单
  1311. $order->save();
  1312. // sheet
  1313. if ($order->order_status_payment == 'SUCCESS') {
  1314. OrderSheet::where('join_sheet_order_id', $params['order_id'])->update([
  1315. 'order_sheet_status' => $systemStatus,
  1316. ]);
  1317. }
  1318. // payDetail
  1319. // 不组合支付,那就只有一条支付记录 先删,再加
  1320. PayDetail::where('join_pay_order_id', $order->order_groupby)
  1321. ->whereJsonContains('join_pay_object_json->order_id', $params['orderId'])
  1322. ->delete();
  1323. $payData = [
  1324. 'pay_amount' => $params['order_amount_pay']
  1325. ];
  1326. if ($order->order_status_payment == 'SUCCESS') {
  1327. $payData['pay_paytimes'] = date('Y-m-d H:i:s');
  1328. $payData['pay_status'] = 'SUCCESS';
  1329. }
  1330. if ($params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) {
  1331. $payData['pay_prepayid'] = $params['pay_category'];
  1332. $payData['pay_json_response'] = $params['pay_json_response'];
  1333. } else if ($params['pay_category'] == 'CASH') {
  1334. $payData['pay_prepayid'] = $params['join_order_member_id'] . '-CASH';
  1335. } else if ($params['pay_category'] == 'WELFARE') {
  1336. $payData['pay_prepayid'] = $params['join_order_member_id'] . '-WELFARE';
  1337. } else if ($params['pay_category'] == 'VIP') {
  1338. $payData['pay_prepayid'] = $params['join_order_member_id'] . '-VIP';
  1339. } else if ($params['pay_category'] == 'CARD') {
  1340. $payData['pay_prepayid'] = $params['card_nbr'];
  1341. } else if ($params['pay_category'] == 'OFFLINE') {
  1342. $payData['pay_prepayid'] = 'OFFLINE';
  1343. } else if ($params['pay_category'] == 'OFFLINE_ALIPAY') {
  1344. $payData['pay_prepayid'] = 'OFFLINE_ALIPAY';
  1345. } else if ($params['pay_category'] == 'OFFLINE_WXPAY') {
  1346. $payData['pay_prepayid'] = 'OFFLINE_WXPAY';
  1347. } else if ($params['pay_category'] == 'MONEY') {
  1348. $payData['pay_prepayid'] = 'MONEY';
  1349. }
  1350. $payData['join_pay_member_id'] = $params['join_order_member_id'];
  1351. $payData['join_pay_order_id'] = $order->order_groupby;
  1352. $payData['pay_status'] = !empty($payData['pay_status']) && $payData['pay_status'] == 'SUCCESS' ? $payData['pay_status'] : 'WAITING';
  1353. $payData['pay_category'] = $params['goods_classify'] ?? '';
  1354. $payData['pay_paytimes'] = date('Y-m-d H:i:s');
  1355. $payData['pay_json_request'] = json_encode($params); // {"pay-result": "支付成功", "result-datetime": "2024-07-29 18:38:21"}
  1356. $payData['pay_json_response'] = $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')])) : '[]';
  1357. $payData['join_pay_object_json'] = !empty($params['orderId']) ? json_encode(['order_id' => $params['orderId']]) : '[]';
  1358. $payData['pay_addtimes'] = time();
  1359. PayDetail::insert($payData);
  1360. $writeOffDate = [];
  1361. $applyData = [];
  1362. // 有预约单,状态已完成
  1363. $appointment = Appointment::where('join_appointment_order_id', $params['order_id'])->first();
  1364. if ($order->order_status_payment == 'SUCCESS' && $appointment) {
  1365. $writeOffDate = OrderService::generateWriteOffData($params);
  1366. $applyData = OrderService::generateAppointmentApplyData($params);
  1367. $appointment->appointment_status = 'DONE';
  1368. $appointment->appointment_done_datetime = date('Y-m-d H:i:s');
  1369. $appointment->appointment_done_json = json_encode($writeOffDate);
  1370. if (empty($appointment->appointment_apply_datetime)) {
  1371. $appointment->appointment_apply_datetime = date('Y-m-d H:i:s');
  1372. }
  1373. if (empty($appointment->appointment_apply_json)) {
  1374. $appointment->appointment_apply_json = json_encode($applyData);
  1375. }
  1376. if (empty($appointment->appointment_datetime)) {
  1377. $appointment->appointment_datetime = date('Y-m-d');
  1378. }
  1379. $appointment->save();
  1380. }
  1381. // // 买的单个服务
  1382. if ($order->order_status_payment == 'SUCCESS' && empty($appointment)) {
  1383. foreach ($params['goodsContentList'] as $goods) {
  1384. $params['join_sheet_goods_id'] = $goods['goods_id'];
  1385. if (isset($goods['goods_classify']) && in_array($goods['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD'])) {
  1386. $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
  1387. $params['order_sheet_num'] = $goods['nbr'];
  1388. // 预约表
  1389. for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
  1390. $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
  1391. // 入预约记录
  1392. $this->insertAppointment($params, $writeOffDate, $applyData);
  1393. }
  1394. $goods['skuId'] = $goods['sku_id'];
  1395. $goods['category'] = $goods['goods_classify'];
  1396. // 权益表
  1397. $this->insertMemberBenefit($params, $goods);
  1398. } elseif (isset($goods['goods_classify']) && $goods['goods_classify'] == 'PACKAGE') { // 一个套餐买多个
  1399. $params['packageId'] = $goods['goods_id'];
  1400. $components = GoodsComponent::with([
  1401. 'goods' => function ($query) {
  1402. $query->select('goods_id', 'goods_name', 'goods_classify');
  1403. }
  1404. ])->where('join_component_master_goods_id', $params['packageId'])
  1405. ->get()
  1406. ->toArray();
  1407. foreach ($components as $component) {
  1408. $componentJson = json_decode($component['goods_component_json'], true);
  1409. $params['join_sheet_goods_sku_id'] = $componentJson['sku_id'];
  1410. $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
  1411. $params['order_sheet_num'] = $goods['nbr'] * $componentJson['nbr'];
  1412. for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
  1413. $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
  1414. // 入预约记录
  1415. $this->insertAppointment($params, $writeOffDate);
  1416. }
  1417. $goods['goods_id'] = $component['join_component_goods_id'];
  1418. $goods['goods_name'] = $component['goods']['goods_name'];
  1419. $goods['goods_classify'] = $component['goods']['goods_classify'];
  1420. $goods['skuId'] = $goods['sku_id'];
  1421. $goods['category'] = 'SERVICE';
  1422. // 权益表
  1423. $this->insertMemberBenefit($params, $goods);
  1424. }
  1425. }
  1426. }
  1427. }
  1428. Db::commit();
  1429. // 会员升级
  1430. if ($order->order_is_complete == 'Y' && $order->order_status_payment == 'SUCCESS') {
  1431. Event::dispatch('order.complete', $params);
  1432. Event::dispatch('order_pay.member_level.up', $params['join_order_member_id']);
  1433. }
  1434. // 打小票
  1435. if ($order->order_status_payment == 'SUCCESS') {
  1436. if (!empty($premises) && !empty($premises->dept_id)) {
  1437. $voteData = [
  1438. 'func' => 'procActionToPrinter',
  1439. 'sign' => '',
  1440. 'data' => [
  1441. 'printer_premises' => $premises->dept_id,
  1442. 'printer_device' => ["收银"],
  1443. 'printer_action' => 'ExecPrintOrder',
  1444. 'printer_data' => [
  1445. 'order_id' => $params['orderId'],
  1446. 'order_batch' => ''
  1447. ]
  1448. ]
  1449. ];
  1450. // dump("小票参数", $voteData);
  1451. http_post_json(getenv('VOTE_MENU_URL'), $voteData);
  1452. }
  1453. }
  1454. if ($order->order_status_payment != 'SUCCESS') {
  1455. _syslog("订单", "支付异常,检查是否有轮询");
  1456. // 恢复优惠券到已占用
  1457. if (!is_array($couponUseJson)) {
  1458. $couponUseJson = json_decode($couponUseJson, true);
  1459. }
  1460. // 如果下单时就填了,不用恢复
  1461. if (empty($discountJson)) {
  1462. $this->changeOrderCouponStatus($couponUseJson, 'WAITING');
  1463. }
  1464. return json_throw(2001, '支付异常', ['order_id' => $params['orderId']]);
  1465. }
  1466. _syslog("订单", "订单支付成功");
  1467. return json_success('支付成功');
  1468. } catch (BusinessException $e) {
  1469. dump($e->getMessage());
  1470. Db::rollBack();
  1471. _syslog("订单", "订单支付失败:" . $e->getMessage());
  1472. return json_fail("支付失败:" . $e->getMessage());
  1473. } catch (\Exception $e) {
  1474. dump($e->getMessage());
  1475. Db::rollBack();
  1476. _syslog("订单", "订单支付失败");
  1477. return json_fail('支付失败');
  1478. }
  1479. }
  1480. /**
  1481. * 组合支付
  1482. */
  1483. public function payConstitute(Request $request)
  1484. {
  1485. $params = $request->post();
  1486. // 余额、福利、储值卡 验证短信
  1487. if (!empty($params['pay_category_constitute']) && !in_array('OFFLINE', $params['pay_category_constitute']) && !in_array('MONEY', $params['pay_category_constitute']) && !in_array('QRCODE', $params['pay_category_constitute']) && (in_array('CASH', $params['pay_category_constitute']) || in_array('CARD', $params['pay_category_constitute']) || in_array('WELFARE', $params['pay_category_constitute']))) {
  1488. $code = $params['sms_code'];
  1489. if (!$code) {
  1490. return json_fail("验证码错误,请重新输入");
  1491. }
  1492. $member = Member::find($params['join_order_member_id']);
  1493. $mobile = $member->member_mobile;
  1494. $key = "SMS:CODE:ORDER_PAY:" . $mobile;
  1495. $redisCode = Redis::get($key);
  1496. if ($redisCode != $code && $code != '123456') {
  1497. return json_fail("验证码错误,请重新输入");
  1498. }
  1499. Redis::del($key);
  1500. }
  1501. // 验证线下付款密码
  1502. if (!empty($params['pay_category_constitute']) && in_array('OFFLINE', $params['pay_category_constitute']) && in_array('MONEY', $params['pay_category_constitute'])) {
  1503. $password = $params['offline_password'];
  1504. if ($password != '666888') {
  1505. return json_fail("密码错误,请重新输入");
  1506. }
  1507. }
  1508. $order = Order::where('order_id', $params['order_id'])->first();
  1509. if (!$order) {
  1510. return json_fail('订单异常');
  1511. }
  1512. if ($order->order_status_system != 'PAYING') {
  1513. return json_fail('订单不是可支付状态');
  1514. }
  1515. if (!empty($order->order_config_json)) {
  1516. $orderConfigJson = json_decode($order->order_config_json, true);
  1517. if (isset($orderConfigJson['premises'])) {
  1518. $premises = SysDept::where('dept_name', $orderConfigJson['premises'])->first();
  1519. if (!empty($premises)) {
  1520. $params['submit_premises_id'] = $premises->dept_id;
  1521. }
  1522. }
  1523. }
  1524. $params['orderId'] = $params['order_id'];
  1525. $params['orderGroupId'] = $order->order_groupby;
  1526. $goods = Goods::where('goods_id', $params['join_sheet_goods_id'])
  1527. ->select('goods_id', 'goods_name', 'goods_classify')
  1528. ->first();
  1529. if (!$goods) {
  1530. return json_fail('产品数据异常');
  1531. }
  1532. $goods = $goods->toArray();
  1533. $params['goods_classify'] = $goods['goods_classify'];
  1534. $systemStatus = 'SENDING'; // 待发货
  1535. // 立即结算
  1536. if (in_array($params['goods_classify'], ['MEALS', 'VIP'])) {
  1537. $order->order_is_complete = 'Y';
  1538. $systemStatus = 'DONE';
  1539. }
  1540. if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $params['delivery'] == 'ARRIVAL') {
  1541. $params['order_is_complete'] = 'N';
  1542. $systemStatus = "WAITING";
  1543. }
  1544. $payDetail = PayDetail::where('join_pay_order_id', $order->order_groupby)->first();
  1545. Db::beginTransaction();
  1546. try {// 使用优惠券
  1547. $couponUseJson = [];
  1548. $discountJson = [];
  1549. if (!empty($order->order_discount_json)) {
  1550. $discountJson = json_decode($order->order_discount_json, true);
  1551. foreach ($discountJson as $item) {
  1552. if (isset($item['coupon_value']) && sprintf('%.2f', (floatval($order->order_amount_total) - floatval($params['order_amount_pay']))) != sprintf('%.2f', $item['coupon_value'])) {
  1553. throw new BusinessException("计算优惠后,实付金额错误!");
  1554. }
  1555. }
  1556. // 释放下单时选的优惠券
  1557. $order->order_discount_json = $this->releaseCoupon($discountJson);
  1558. }
  1559. if (empty($discountJson) && !empty($params['join_order_member_id']) && !empty($params['preferential'])) {
  1560. $couponResult = OrderService::payUseCoupon('pay', 'Y', $params['join_order_member_id'], $params['goodsContentList'], $params['preferential'], $params['order_amount_total']);
  1561. if (!empty($couponResult['pay_amount']) && $couponResult['pay_amount'] != $params['order_amount_pay']) {
  1562. throw new BusinessException("计算优惠后,实付金额错误!");
  1563. }
  1564. // 组装优惠券使用数据,存主表优惠里
  1565. if (!empty($couponResult['use_coupon_json'])) {
  1566. $couponUseJson = $couponResult['use_coupon_json'];
  1567. }
  1568. }
  1569. // 存储优惠信息
  1570. $order->order_discount_json = json_encode($this->discountRecord($couponUseJson, $params));
  1571. $orderAmountPay = $params['order_amount_pay'];
  1572. $constituteList = array_column($params['pay_category_constitute_list'], 'amount', 'category');// 验证金额
  1573. $constituteAmount = 0;
  1574. foreach ($params['pay_category_constitute_list'] as $item) {
  1575. $constituteAmount = $constituteAmount + $item['amount'];
  1576. }
  1577. if ($params['order_amount_pay'] != $constituteAmount) {
  1578. throw new BusinessException('组合支付金额与应付金额不一致');
  1579. }
  1580. if (!empty($params['pay_category_constitute']) && in_array('OFFLINE', $params['pay_category_constitute'])) { //线下付款
  1581. $order->order_status_system = $systemStatus;
  1582. $order->order_status_payment = 'SUCCESS';
  1583. $params['pay_category'] = $params['pay_category_sub'] ?? 'OFFLINE';
  1584. // 线下支付金额
  1585. if (isset($constituteList['OFFLINE'])) {
  1586. $params['order_amount_pay'] = $constituteList['OFFLINE'];
  1587. // 生成支付记录
  1588. OrderService::createPayConstituteDetail($params, $payDetail);
  1589. }
  1590. $params['order_amount_pay'] = $orderAmountPay;
  1591. }
  1592. if (!empty($params['pay_category_constitute']) && in_array('MONEY', $params['pay_category_constitute'])) { //现金付款
  1593. $order->order_status_system = $systemStatus;
  1594. $order->order_status_payment = 'SUCCESS';
  1595. $params['pay_category'] = 'MONEY';
  1596. // 线下支付金额
  1597. if (isset($constituteList['MONEY'])) {
  1598. $params['order_amount_pay'] = $constituteList['MONEY'];
  1599. // 生成支付记录
  1600. OrderService::createPayConstituteDetail($params, $payDetail);
  1601. }
  1602. $params['order_amount_pay'] = $orderAmountPay;
  1603. }
  1604. if (!empty($params['pay_category_constitute']) && in_array('CASH', $params['pay_category_constitute'])) { // 余额支付
  1605. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  1606. ->where('member_account_classify', 'CASH')
  1607. ->where('member_account_status', 'ACTIVED')
  1608. ->first();
  1609. if (!$account) {
  1610. throw new BusinessException('账户异常');
  1611. }
  1612. if (isset($constituteList['CASH'])) {
  1613. $params['order_amount_pay'] = $constituteList['CASH'];
  1614. $params['pay_category'] = $params['join_order_member_id'] . '-CASH';
  1615. }
  1616. $amount = $account->member_account_surplus + $account->member_account_added;
  1617. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  1618. throw new BusinessException('账户余额不足');
  1619. }
  1620. if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
  1621. $qrcodePayAmount = $params['order_amount_pay'] - $amount;
  1622. $params['order_amount_pay'] = $amount;
  1623. }
  1624. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  1625. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  1626. $account->member_account_surplus = 0;
  1627. $account->member_account_added = $cut;
  1628. } else {
  1629. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  1630. }
  1631. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  1632. $account->save();
  1633. // 生成支付记录
  1634. OrderService::createPayConstituteDetail($params, $payDetail);
  1635. $params['order_amount_pay'] = $orderAmountPay;
  1636. $order->order_status_system = $systemStatus;
  1637. $order->order_status_payment = 'SUCCESS';
  1638. }
  1639. if (!empty($params['pay_category_constitute']) && in_array('CARD', $params['pay_category_constitute'])) { // 储值卡账户
  1640. $cardNbr = $params['card_nbr'];
  1641. if (!$cardNbr) {
  1642. throw new BusinessException('账户异常');
  1643. }
  1644. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  1645. ->where('member_account_nbr', $cardNbr)
  1646. ->where('member_account_status', 'ACTIVED')
  1647. ->first();
  1648. if (!$account) {
  1649. Db::rollBack();
  1650. return json_fail('账户异常');
  1651. }
  1652. // 储值卡账户支付金额
  1653. if (isset($constituteList['CARD'])) {
  1654. $params['order_amount_pay'] = $constituteList['CARD'];
  1655. $params['pay_category'] = $cardNbr;
  1656. }
  1657. $amount = $account->member_account_surplus + $account->member_account_added;
  1658. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  1659. throw new BusinessException('账户余额不足');
  1660. }
  1661. if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
  1662. $qrcodePayAmount = $params['order_amount_pay'] - $amount;
  1663. $params['order_amount_pay'] = $amount;
  1664. }
  1665. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  1666. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  1667. $account->member_account_surplus = 0;
  1668. $account->member_account_added = $cut;
  1669. } else {
  1670. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  1671. }
  1672. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  1673. $account->save();
  1674. // 生成支付记录
  1675. OrderService::createPayConstituteDetail($params, $payDetail);
  1676. $params['order_amount_pay'] = $orderAmountPay;
  1677. $order->order_status_system = $systemStatus;
  1678. $order->order_status_payment = 'SUCCESS';
  1679. }
  1680. if (!empty($params['pay_category_constitute']) && in_array('QRCODE', $params['pay_category_constitute']) && !empty($params['qrcode_nbr'])) { // 付款码
  1681. if (isset($constituteList['QRCODE']) && $constituteList['QRCODE'] > 0) {
  1682. // 付款码支付金额
  1683. $params['order_amount_pay'] = $constituteList['QRCODE'];
  1684. // 调支付
  1685. $result = OrderService::qrcodePay($params);
  1686. $result = json_encode($result);
  1687. $params['pay_json_response'] = $result;
  1688. $result = json_decode($result, true);
  1689. $prefix = substr($params['qrcode_nbr'], 0, 2);
  1690. if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
  1691. $params['pay_category'] = 'WXPAY';
  1692. 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')) {
  1693. $order->order_status_system = 'PAYING';
  1694. $order->order_status_payment = 'PENDING';
  1695. $order->order_is_complete = 'N';
  1696. // Db::rollBack();
  1697. // return json_fail('支付失败');
  1698. } else {
  1699. $order->order_status_system = $systemStatus;
  1700. $order->order_status_payment = 'SUCCESS';
  1701. }
  1702. } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
  1703. $params['pay_category'] = 'ALIPAY';
  1704. if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {
  1705. $order->order_status_system = 'PAYING';
  1706. $order->order_status_payment = 'PENDING';
  1707. $order->order_is_complete = 'N';
  1708. // Db::rollBack();
  1709. // return json_fail('支付失败');
  1710. } else {
  1711. $order->order_status_system = $systemStatus;
  1712. $order->order_status_payment = 'SUCCESS';
  1713. }
  1714. } else {
  1715. throw new BusinessException('付款码无效');
  1716. }
  1717. }
  1718. // 生成支付记录
  1719. OrderService::createPayConstituteDetail($params, $payDetail);
  1720. // 账户支付的金额
  1721. $params['order_amount_pay'] = $orderAmountPay;
  1722. }
  1723. $orderConfigJson = [];
  1724. if (!empty($order->order_config_json)) {
  1725. $orderConfigJson = json_decode($order->order_config_json, true);
  1726. }
  1727. $orderConfigJson['preferential'] = $params['preferential'] ?? '';
  1728. if (isset($orderConfigJson['tableid']) && !empty($orderConfigJson['tableid'])) {
  1729. SysDept::where('dept_id', $orderConfigJson['tableid'])->where('dept_category', '桌台')->update(['dept_status' => 'ACTIVED']);
  1730. }
  1731. $order->order_config_json = json_encode($orderConfigJson);
  1732. $order->order_amount_pay = $params['order_amount_pay'];
  1733. // 主订单
  1734. $order->save();
  1735. // sheet
  1736. if ($order->order_status_payment == 'SUCCESS') {
  1737. OrderSheet::where('join_sheet_order_id', $params['order_id'])->update([
  1738. 'order_sheet_status' => $systemStatus,
  1739. ]);
  1740. }
  1741. // 清除paydetail 中的未支付记录
  1742. PayDetail::where('join_pay_order_id', $params['orderGroupId'])
  1743. ->whereJsonContains('join_pay_object_json->order_id', $params['order_id'])
  1744. ->where('pay_status', '<>', 'SUCCESS')
  1745. ->delete();
  1746. $writeOffDate = [];
  1747. $applyData = [];
  1748. // 有预约单,状态已完成
  1749. $appointment = Appointment::where('join_appointment_order_id', $params['order_id'])->first();
  1750. if ($order->order_status_payment == 'SUCCESS' && $appointment) {
  1751. $writeOffDate = OrderService::generateWriteOffData($params);
  1752. $applyData = OrderService::generateAppointmentApplyData($params);
  1753. $appointment->appointment_status = 'DONE';
  1754. $appointment->appointment_done_datetime = date('Y-m-d H:i:s');
  1755. $appointment->appointment_done_json = json_encode($writeOffDate);
  1756. if (empty($appointment->appointment_apply_datetime)) {
  1757. $appointment->appointment_apply_datetime = date('Y-m-d H:i:s');
  1758. }
  1759. if (empty($appointment->appointment_apply_json)) {
  1760. $appointment->appointment_apply_json = json_encode($applyData);
  1761. }
  1762. if (empty($appointment->appointment_datetime)) {
  1763. $appointment->appointment_datetime = date('Y-m-d');
  1764. }
  1765. $appointment->save();
  1766. }
  1767. // 买单个服务
  1768. if ($order->order_status_payment == 'SUCCESS' && empty($appointment)) {
  1769. foreach ($params['goodsContentList'] as $goods) {
  1770. $params['join_sheet_goods_id'] = $goods['goods_id'];
  1771. if (isset($goods['goods_classify']) && in_array($goods['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD'])) {
  1772. $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
  1773. $params['order_sheet_num'] = $goods['nbr'];
  1774. // 预约表
  1775. for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
  1776. $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
  1777. // 入预约记录
  1778. $this->insertAppointment($params, $writeOffDate, $applyData);
  1779. }
  1780. $goods['skuId'] = $goods['sku_id'];
  1781. $goods['category'] = $goods['goods_classify'];
  1782. // 权益表
  1783. $this->insertMemberBenefit($params, $goods);
  1784. } elseif (isset($goods['goods_classify']) && $goods['goods_classify'] == 'PACKAGE') { // 一个套餐买多个
  1785. $params['packageId'] = $goods['goods_id'];
  1786. $components = GoodsComponent::with([
  1787. 'goods' => function ($query) {
  1788. $query->select('goods_id', 'goods_name', 'goods_classify');
  1789. }
  1790. ])->where('join_component_master_goods_id', $params['packageId'])
  1791. ->get()
  1792. ->toArray();
  1793. foreach ($components as $component) {
  1794. $componentJson = json_decode($component['goods_component_json'], true);
  1795. $params['join_sheet_goods_sku_id'] = $componentJson['sku_id'];
  1796. $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
  1797. $params['order_sheet_num'] = $goods['nbr'] * $componentJson['nbr'];
  1798. for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
  1799. $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
  1800. // 入预约记录
  1801. $this->insertAppointment($params, $writeOffDate);
  1802. }
  1803. $goods['goods_id'] = $component['join_component_goods_id'];
  1804. $goods['goods_name'] = $component['goods']['goods_name'];
  1805. $goods['goods_classify'] = $component['goods']['goods_classify'];
  1806. $goods['skuId'] = $goods['sku_id'];
  1807. $goods['category'] = 'SERVICE';
  1808. // 权益表
  1809. $this->insertMemberBenefit($params, $goods);
  1810. }
  1811. }
  1812. }
  1813. }
  1814. Db::commit();
  1815. // 会员升级
  1816. if ($order->order_is_complete == 'Y' && $order->order_status_payment == 'SUCCESS') {
  1817. Event::dispatch('order.complete', $params);
  1818. Event::dispatch('order_pay.member_level.up', $params['join_order_member_id']);
  1819. }
  1820. // 打小票
  1821. if ($order->order_status_payment == 'SUCCESS') {
  1822. if (!empty($premises) && !empty($premises->dept_id)) {
  1823. $voteData = [
  1824. 'func' => 'procActionToPrinter',
  1825. 'sign' => '',
  1826. 'data' => [
  1827. 'printer_premises' => $premises->dept_id,
  1828. 'printer_device' => ["收银"],
  1829. 'printer_action' => 'ExecPrintOrder',
  1830. 'printer_data' => [
  1831. 'order_id' => $params['orderId'],
  1832. 'order_batch' => ''
  1833. ]
  1834. ]
  1835. ];
  1836. // dump("小票参数", $voteData);
  1837. http_post_json(getenv('VOTE_MENU_URL'), $voteData);
  1838. }
  1839. }
  1840. if ($order->order_status_payment != 'SUCCESS') {
  1841. _syslog("订单", "支付异常,检查是否有轮询");
  1842. // 恢复优惠券到已占用
  1843. if (!is_array($couponUseJson)) {
  1844. $couponUseJson = json_decode($couponUseJson, true);
  1845. }
  1846. // 如果下单时就填了,不用恢复
  1847. if (empty($discountJson)) {
  1848. $this->changeOrderCouponStatus($couponUseJson, 'WAITING');
  1849. }
  1850. return json_throw(2001, '支付异常', ['order_id' => $params['orderId']]);
  1851. }
  1852. _syslog("订单", "订单支付成功");
  1853. return json_success('支付成功');
  1854. } catch (\Exception $e) {
  1855. dump($e->getMessage());
  1856. Db::rollBack();
  1857. _syslog("订单", "订单支付失败");
  1858. return json_fail('支付失败');
  1859. }
  1860. }
  1861. /**
  1862. * @Desc
  1863. * @Author Gorden
  1864. * @Date 2024/6/7 10:30
  1865. *
  1866. * @param $params
  1867. * @return void
  1868. * @throws BusinessException
  1869. */
  1870. public function insertMain($params)
  1871. {
  1872. try {
  1873. if (empty($params['order_extend_json'])) {
  1874. $params['order_extend_json'] = [];
  1875. } else {
  1876. if (is_json($params['order_extend_json'])) {
  1877. $params['order_extend_json'] = json_decode($params['order_extend_json'], true);
  1878. }
  1879. }
  1880. // 推荐人
  1881. $params['order_extend_json']['referee'] = $params['referee'] ?? '';
  1882. foreach ($params['goodsContentList'] as $goods) {
  1883. $discountJson = [];
  1884. if (!empty($params['order_discount_json'])) {
  1885. $discountJson = json_decode($params['order_discount_json'], true);
  1886. foreach ($discountJson as &$item) {
  1887. if (!empty($item['coupon_value'])) {
  1888. $item['coupon_value'] = round((floatval($goods['goods_sales_price']) * $goods['nbr'] / $params['order_amount_total']) * $item['coupon_value'], 2);
  1889. }
  1890. }
  1891. }
  1892. $orderId = 'OD' . date('ymdHi') . random_string(4, 'up');
  1893. $amountPay = round((floatval($goods['goods_sales_price']) * $goods['nbr'] / $params['order_amount_total']) * $params['order_amount_pay'], 2);
  1894. // $amountPay = round(floatval($goods['goods_sales_price']) * $goods['nbr'] * $params['order_ratio'], 2);
  1895. $data = [
  1896. 'order_id' => $orderId,
  1897. 'order_groupby' => $params['orderGroupId'],
  1898. 'join_order_member_id' => $params['join_order_member_id'],
  1899. 'order_name' => date('Y-m-d H:i:s') . '-订单',
  1900. 'order_amount_total' => floatval($goods['goods_sales_price']) * $goods['nbr'],
  1901. 'order_amount_pay' => $amountPay,
  1902. 'order_category' => $goods['goods_classify'],
  1903. 'order_classify' => $goods['goods_classify'],
  1904. 'order_is_complete' => $params['order_is_complete'] ?? 'N',
  1905. 'order_status_system' => $params['order_status_system'],
  1906. 'order_status_payment' => $params['order_status_payment'],
  1907. 'order_status_storage' => $params['order_status_storage'],
  1908. 'order_platform' => $params['order_platform'],
  1909. 'order_remark' => $params['order_remark'] ?? '',
  1910. 'order_discount_json' => json_encode($discountJson),
  1911. 'order_config_json' => $params['order_config_json'] ?? '[]',
  1912. 'order_express_json' => $params['order_express_json'] ?? '[]',
  1913. 'order_extend_json' => $params['order_extend_json'] ? json_encode($params['order_extend_json']) : '[]',
  1914. 'order_addtimes' => time()
  1915. ];
  1916. Order::insert($data);
  1917. $sheetIds = $this->insertSheetOne($params, $goods, $orderId, $amountPay);
  1918. $this->insertPayDetailOne($params, $orderId, $amountPay, $goods);
  1919. $params['order_express_goods'] = json_encode(['sheet' => $sheetIds]);
  1920. $this->insertExpressOne($params, $orderId);
  1921. }
  1922. } catch (\Exception $e) {
  1923. dump($e->getMessage());
  1924. throw new BusinessException('订单创建信息失败');
  1925. }
  1926. }
  1927. /**
  1928. * @Desc
  1929. * @Author Gorden
  1930. * @Date 2024/6/7 10:25
  1931. *
  1932. * @param $params
  1933. * @return void
  1934. * @throws BusinessException
  1935. */
  1936. public function insertSheet($params)
  1937. {
  1938. try {
  1939. $orderSheetIds = [];
  1940. foreach ($params['goodsContentList'] as $goods) {
  1941. //{"unit": "份", "table": null, "premises": "15"}
  1942. $price = floatval($goods['goods_sales_price']);
  1943. $extendJson['unit'] = $goods['sku_name'];
  1944. if (isset($params['submit_premises_id'])) {
  1945. $extendJson['premises'] = $params['submit_premises_id'];
  1946. }
  1947. if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
  1948. $extendJson['table'] = null;
  1949. }
  1950. $data = [
  1951. 'join_sheet_member_id' => $params['join_order_member_id'],
  1952. 'join_sheet_order_id' => $params['orderId'],
  1953. 'join_sheet_goods_id' => $goods['goods_id'],
  1954. 'join_sheet_goods_sku_id' => $goods['sku_id'],
  1955. 'order_sheet_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'DONE' : 'PAYING',
  1956. 'order_sheet_category' => (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') ? 'DISHES' : 'NORMAL',
  1957. 'order_sheet_num' => $goods['nbr'],
  1958. 'order_sheet_price' => $goods['goods_sales_price'],
  1959. 'order_sheet_amount' => $price * $goods['nbr'],
  1960. 'order_sheet_pay' => $price * $goods['nbr'],
  1961. 'order_sheet_task_status' => 'NONE',
  1962. 'order_sheet_remark' => $params['order_remark'] ?? '',
  1963. 'order_sheet_addtimes' => time(),
  1964. 'order_sheet_extend_json' => json_encode($extendJson)
  1965. ];
  1966. $orderSheetId = OrderSheet::insertGetId($data);
  1967. $orderSheetIds[] = $orderSheetId;
  1968. // 减库存,规格和总库存
  1969. if (!isset($params['submit_goods_classify']) || !in_array($params['submit_goods_classify'], ['MEALS', 'PACKAGE'])) {
  1970. $goodsSku = GoodsSku::where('goods_sku_id', $goods['sku_id'])->first();
  1971. $skuStorageJson = json_decode($goodsSku->goods_sku_storage_json, true);
  1972. if (isset($skuStorageJson['storage']) && !empty($skuStorageJson['storage'])) {
  1973. $skuStorageJson['storage'] = $skuStorageJson['storage'] - $goods['nbr'];
  1974. }
  1975. if (!isset($skuStorageJson['storage']) || (!empty($skuStorageJson['storage']) && $skuStorageJson['storage'] < 0)) {
  1976. throw new BusinessException('库存不足');
  1977. }
  1978. $goodsSku->goods_sku_storage_json = json_encode($skuStorageJson);
  1979. $goodsSku->save();
  1980. }
  1981. $goodsRunning = GoodsRunning::where('join_running_goods_id', $goods['goods_id'])->first();
  1982. $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $goods['nbr'];
  1983. if ($goodsRunning->goods_running_storage < 0) {
  1984. throw new BusinessException('库存不足');
  1985. }
  1986. $goodsRunning->goods_running_sale = $goodsRunning->goods_running_sale + $goods['nbr'];
  1987. $goodsRunning->save();
  1988. }
  1989. // return $orderSheetIds;
  1990. } catch (\support\exception\BusinessException $e) {
  1991. dump($e->getMessage() . '||' . $e->getLine());
  1992. throw new BusinessException($e->getMessage());
  1993. } catch (\Exception $e) {
  1994. dump($e->getMessage() . '||' . $e->getLine());
  1995. throw new BusinessException('订单创建失败');
  1996. }
  1997. }
  1998. /**
  1999. * @Desc 单条入库
  2000. * @Author Gorden
  2001. * @Date 2024/9/23 10:19
  2002. *
  2003. * @param $params
  2004. * @return array
  2005. * @throws BusinessException
  2006. */
  2007. public function insertSheetOne($params, $goods, $orderId, $amountPay)
  2008. {
  2009. try {
  2010. $orderSheetIds = [];
  2011. // foreach ($params['goodsContentList'] as $goods) {
  2012. //{"unit": "份", "table": null, "premises": "15"}
  2013. $price = floatval($goods['goods_sales_price']);
  2014. $extendJson['unit'] = $goods['sku_name'];
  2015. if (isset($params['submit_premises_id'])) {
  2016. $extendJson['premises'] = $params['submit_premises_id'];
  2017. }
  2018. if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
  2019. $extendJson['table'] = null;
  2020. }
  2021. $data = [
  2022. 'join_sheet_member_id' => $params['join_order_member_id'],
  2023. 'join_sheet_order_id' => $orderId,
  2024. 'join_sheet_goods_id' => $goods['goods_id'],
  2025. 'join_sheet_goods_sku_id' => $goods['sku_id'],
  2026. 'order_sheet_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'DONE' : 'PAYING',
  2027. 'order_sheet_category' => (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') ? 'DISHES' : 'NORMAL',
  2028. 'order_sheet_num' => $goods['nbr'],
  2029. 'order_sheet_price' => $goods['goods_sales_price'],
  2030. 'order_sheet_price_pay' => round($amountPay / $goods['nbr'], 2),
  2031. 'order_sheet_amount' => $price * $goods['nbr'],
  2032. 'order_sheet_pay' => $amountPay,
  2033. 'order_sheet_task_status' => 'NONE',
  2034. 'order_sheet_remark' => $params['order_remark'] ?? '',
  2035. 'order_sheet_addtimes' => time(),
  2036. 'order_sheet_extend_json' => json_encode($extendJson)
  2037. ];
  2038. $orderSheetId = OrderSheet::insertGetId($data);
  2039. $orderSheetIds[] = $orderSheetId;
  2040. // 减库存,规格和总库存
  2041. if (!isset($params['submit_goods_classify']) || !in_array($params['submit_goods_classify'], ['MEALS', 'PACKAGE'])) {
  2042. $goodsSku = GoodsSku::where('goods_sku_id', $goods['sku_id'])->first();
  2043. $skuStorageJson = json_decode($goodsSku->goods_sku_storage_json, true);
  2044. if (isset($skuStorageJson['storage']) && !empty($skuStorageJson['storage'])) {
  2045. $skuStorageJson['storage'] = $skuStorageJson['storage'] - $goods['nbr'];
  2046. }
  2047. if (!isset($skuStorageJson['storage']) || (!empty($skuStorageJson['storage']) && $skuStorageJson['storage'] < 0)) {
  2048. throw new BusinessException('库存不足');
  2049. }
  2050. $goodsSku->goods_sku_storage_json = json_encode($skuStorageJson);
  2051. $goodsSku->save();
  2052. }
  2053. $goodsRunning = GoodsRunning::where('join_running_goods_id', $goods['goods_id'])->first();
  2054. $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $goods['nbr'];
  2055. if ($goodsRunning->goods_running_storage < 0) {
  2056. throw new BusinessException('库存不足');
  2057. }
  2058. $goodsRunning->goods_running_sale = $goodsRunning->goods_running_sale + $goods['nbr'];
  2059. $goodsRunning->save();
  2060. // }
  2061. return $orderSheetIds;
  2062. } catch (\support\exception\BusinessException $e) {
  2063. dump($e->getMessage() . '||' . $e->getLine());
  2064. throw new BusinessException($e->getMessage());
  2065. } catch (\Exception $e) {
  2066. dump($e->getMessage() . '||' . $e->getLine());
  2067. throw new BusinessException('订单创建失败');
  2068. }
  2069. }
  2070. /**
  2071. * @Desc
  2072. * @Author Gorden
  2073. * @Date 2024/6/7 10:35
  2074. *
  2075. * @param $params
  2076. * @return void
  2077. * @throws BusinessException
  2078. */
  2079. public function insertPayDetail($params)
  2080. {
  2081. try {
  2082. if (in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) {
  2083. $payPrepayid = $params['pay_category'];
  2084. } else if ($params['pay_category'] == 'OFFLINE') {
  2085. $payPrepayid = 'OFFLINE';
  2086. } else if ($params['pay_category'] == 'OFFLINE_ALIPAY') {
  2087. $payPrepayid = 'OFFLINE_ALIPAY';
  2088. } else if ($params['pay_category'] == 'OFFLINE_WXPAY') {
  2089. $payPrepayid = 'OFFLINE_WXPAY';
  2090. } else if ($params['pay_category'] == 'MONEY') {
  2091. $payPrepayid = 'MONEY';
  2092. } else {
  2093. $payPrepayid = $params['join_order_member_id'] . '-' . $params['pay_category'];
  2094. }
  2095. $data = [
  2096. 'join_pay_member_id' => $params['join_order_member_id'],
  2097. 'join_pay_order_id' => $params['orderGroupId'],
  2098. 'pay_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING',
  2099. 'pay_category' => $params['goods_classify'],
  2100. 'pay_amount' => $params['order_amount_pay'],
  2101. 'pay_prepayid' => $payPrepayid,
  2102. 'pay_paytimes' => date('Y-m-d H:i:s'),
  2103. 'join_pay_object_json' => !empty($params['orderId']) ? json_encode(['order_id' => $params['orderId']]) : '[]',
  2104. 'pay_json_request' => json_encode($params),
  2105. 'pay_json_response' => $params['pay_json_response'] ?? '[]',
  2106. 'pay_remark' => $params['order_remark'] ?? '',
  2107. 'pay_addtimes' => time(),
  2108. ];
  2109. PayDetail::insert($data);
  2110. } catch (\Exception $e) {
  2111. dump($e->getMessage());
  2112. throw new BusinessException('创建支付记录失败');
  2113. }
  2114. }
  2115. /**
  2116. * @Desc 单条入库
  2117. * @Author Gorden
  2118. * @Date 2024/6/7 10:35
  2119. *
  2120. * @param $params
  2121. * @return void
  2122. * @throws BusinessException
  2123. */
  2124. public function insertPayDetailOne($params, $orderId, $amountPay, $goods)
  2125. {
  2126. try {
  2127. if (!empty($params['pay_detail_item'])) {
  2128. foreach ($params['pay_detail_item'] as $item) {
  2129. $data = [
  2130. 'join_pay_member_id' => $item['join_order_member_id'],
  2131. 'join_pay_order_id' => $item['orderGroupId'],
  2132. 'pay_status' => $item['settlement_now'] == 'Y' && $item['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING',
  2133. 'pay_category' => $goods['goods_classify'],
  2134. 'pay_amount' => round(($amountPay / $params['order_amount_pay']) * $item['order_amount_pay'], 2),
  2135. 'pay_prepayid' => $item['pay_category'],
  2136. 'pay_paytimes' => date('Y-m-d H:i:s'),
  2137. 'join_pay_object_json' => !empty($item['orderId']) ? json_encode(['order_id' => $orderId]) : '[]',
  2138. 'pay_json_request' => json_encode($item),
  2139. 'pay_json_response' => $item['pay_json_response'] ?? '[]',
  2140. 'pay_remark' => $item['order_remark'] ?? '',
  2141. 'pay_addtimes' => time(),
  2142. ];
  2143. PayDetail::insert($data);
  2144. }
  2145. } else {
  2146. if (in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) {
  2147. $payPrepayid = $params['pay_category'];
  2148. } else if ($params['pay_category'] == 'OFFLINE') {
  2149. $payPrepayid = 'OFFLINE';
  2150. } else if ($params['pay_category'] == 'OFFLINE_ALIPAY') {
  2151. $payPrepayid = 'OFFLINE_ALIPAY';
  2152. } else if ($params['pay_category'] == 'OFFLINE_WXPAY') {
  2153. $payPrepayid = 'OFFLINE_WXPAY';
  2154. } else if ($params['pay_category'] == 'MONEY') {
  2155. $payPrepayid = 'MONEY';
  2156. } else {
  2157. $payPrepayid = $params['join_order_member_id'] . '-' . $params['pay_category'];
  2158. }
  2159. $data = [
  2160. 'join_pay_member_id' => $params['join_order_member_id'],
  2161. 'join_pay_order_id' => $params['orderGroupId'],
  2162. 'pay_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING',
  2163. 'pay_category' => $goods['goods_classify'],
  2164. 'pay_amount' => $amountPay,
  2165. 'pay_prepayid' => $payPrepayid,
  2166. 'pay_paytimes' => date('Y-m-d H:i:s'),
  2167. 'join_pay_object_json' => !empty($params['orderId']) ? json_encode(['order_id' => $orderId]) : '[]',
  2168. 'pay_json_request' => json_encode($params),
  2169. 'pay_json_response' => $params['pay_json_response'] ?? '[]',
  2170. 'pay_remark' => $params['order_remark'] ?? '',
  2171. 'pay_addtimes' => time(),
  2172. ];
  2173. PayDetail::insert($data);
  2174. }
  2175. } catch (\Exception $e) {
  2176. dump($e->getMessage());
  2177. throw new BusinessException('创建支付记录失败');
  2178. }
  2179. }
  2180. /**
  2181. * @Desc
  2182. * @Author Gorden
  2183. * @Date 2024/6/7 10:50
  2184. *
  2185. * @param $params
  2186. * @return void
  2187. * @throws BusinessException
  2188. */
  2189. public function insertAppointment($params, $writeOffDate, $applyData = [])
  2190. {
  2191. try {
  2192. $data = [
  2193. 'appointment_id' => $params['appointmentId'],
  2194. 'join_appointment_member_id' => $params['join_order_member_id'],
  2195. 'join_appointment_goods_id' => $params['join_sheet_goods_id'],
  2196. 'join_appointment_goods_sku_id' => $params['join_sheet_goods_sku_id'],
  2197. 'join_appointment_order_id' => $params['orderId'],
  2198. 'join_appointment_member_benefit_id' => $params['benefitId'],
  2199. 'appointment_classify' => $params['goods_classify'],
  2200. 'appointment_status' => 'INIT',
  2201. 'appointment_category' => 'NORMAL',
  2202. 'appointment_platform' => 'SYSTEM',
  2203. 'appointment_addtimes' => time(),
  2204. 'appointment_datetime' => '',
  2205. 'appointment_apply_datetime' => '',
  2206. 'appointment_apply_json' => '[]',
  2207. 'appointment_done_datetime' => '',
  2208. 'appointment_remark' => $params['order_remark'] ?? '',
  2209. 'appointment_done_json' => '[]'
  2210. ];
  2211. Appointment::insert($data);
  2212. } catch (\Exception $e) {
  2213. dump($e->getMessage());
  2214. throw new BusinessException("创建权益记录失败");
  2215. }
  2216. }
  2217. /**
  2218. * @Desc
  2219. * @Author Gorden
  2220. * @Date 2024/6/7 11:05
  2221. *
  2222. * @param $params
  2223. * @param $goods
  2224. * @return void
  2225. * @throws BusinessException
  2226. */
  2227. public function insertMemberBenefit($params, $goods)
  2228. {
  2229. try {
  2230. $data = [
  2231. 'member_benefit_id' => $params['benefitId'],
  2232. 'join_benefit_member_id' => $params['join_order_member_id'],
  2233. 'join_benefit_package_id' => $params['packageId'] ?? '',
  2234. 'join_benefit_goods_id' => $goods['goods_id'],
  2235. 'join_benefit_goods_sku_id' => $goods['skuId'] ?? '',
  2236. 'join_benefit_order_id' => $params['orderId'],
  2237. 'member_benefit_status' => 'ACTIVED',
  2238. 'member_benefit_category' => $goods['category'],
  2239. 'member_benefit_name' => $goods['goods_name'],
  2240. 'member_benefit_limit_count' => $params['order_sheet_num'],
  2241. 'member_benefit_used_count' => 0,
  2242. 'member_benefit_remark' => $params['order_remark'] ?? '',
  2243. 'member_benefit_addtimes' => time()
  2244. ];
  2245. MemberBenefit::insert($data);
  2246. } catch (\Exception $e) {
  2247. dump($e->getMessage());
  2248. throw new BusinessException('创建会员权益失败');
  2249. }
  2250. }
  2251. public function saveExpress($params, $orderId)
  2252. {
  2253. try {
  2254. $express = new OrderExpress();
  2255. $express->order_express_type = $params['order_express_type'];
  2256. $express->join_express_order_id = $orderId;
  2257. $express->join_express_dept_id = $params['submit_premises_id'] ?? 0;
  2258. $express->order_express_goods = $params['order_express_goods'];
  2259. $express->order_express_city = $params['order_express_city'];
  2260. $express->order_express_address = $params['order_express_address'];
  2261. $express->order_express_mobile = $params['order_express_mobile'] ?? '';
  2262. $express->order_express_telephone = $params['order_express_telephone'] ?? '';
  2263. $express->order_express_person = $params['order_express_person'] ?? '';
  2264. $express->order_express_company = $params['dept_premises_id'] ?? '';
  2265. $express->order_express_extend_json = $params['order_express_extend_json'] ?? '[]';
  2266. $express->order_express_addtimes = time();
  2267. $express->save();
  2268. } catch (\Exception $e) {
  2269. dump($e->getMessage());
  2270. throw new BusinessException('物流信息保存失败');
  2271. }
  2272. }
  2273. /**
  2274. * @Desc 修改优惠券状态
  2275. * @Author Gorden
  2276. * @Date 2024/9/19 9:03
  2277. *
  2278. * @param $coupon
  2279. * @param $status
  2280. * @return void
  2281. */
  2282. private function changeOrderCouponStatus($coupon, $status)
  2283. {
  2284. if (!empty($coupon) && is_array($coupon)) {
  2285. $updateData['coupon_detail_status'] = $status;
  2286. if ($status == 'ACTIVED' || $status == 'WAITING') {
  2287. $updateData['coupon_detail_used_datetime'] = '';
  2288. } elseif ($status == 'USED') {
  2289. $updateData['coupon_detail_used_datetime'] = date('Y-m-d H:i:s');
  2290. }
  2291. foreach ($coupon as $item) {
  2292. if (!empty($item['coupon_id']) && !empty($item['coupon_detail_id'])) {
  2293. foreach ($item['coupon_detail_id'] as $detailId) {
  2294. CouponDetail::where('join_detail_coupon_id', $item['coupon_id'])
  2295. ->where('coupon_detail_id', $detailId)->update($updateData);
  2296. }
  2297. }
  2298. }
  2299. }
  2300. }
  2301. private function discountRecord($orderDiscountJson, $params)
  2302. {
  2303. $json = [];
  2304. if (!empty($orderDiscountJson)) {
  2305. $json = json_decode($orderDiscountJson, true);
  2306. }
  2307. try {
  2308. if (!empty($params['preferential']) && in_array('wipe', $params['preferential'])) {
  2309. if (intval($params['order_amount_total'] / 10) * 10 != $params['order_amount_pay']) {
  2310. throw new BusinessException("抹零后实际支付金额错误");
  2311. }
  2312. $params['order_discount_amount'] = $params['order_amount_total'] - $params['order_amount_pay'];
  2313. $couponClassifyDesc = $couponClassify = '抹零';
  2314. } elseif (!empty($params['preferential']) && in_array('custom', $params['preferential'])) {
  2315. if (sprintf("%.2f", $params['order_amount_total'] - $params['order_discount_amount']) != sprintf("%.2f", $params['order_amount_pay'])) {
  2316. throw new BusinessException("餐厅前台优惠后实际支付金额错误");
  2317. }
  2318. $couponClassifyDesc = $couponClassify = '餐厅前台优惠';
  2319. } else if (!empty($params['preferential']) && intval($params['preferential'][0]) < 100 && intval($params['preferential'][0]) >= 50) {
  2320. if (($params['order_amount_total'] * intval($params['preferential'][0])) / 100 != $params['order_amount_pay']) {
  2321. throw new BusinessException("折扣后实际支付金额错误");
  2322. }
  2323. $couponClassify = '折扣';
  2324. $couponClassifyDesc = intval($params['preferential'][0]) / 10 . '折';
  2325. $params['order_discount_amount'] = $params['order_amount_total'] - $params['order_amount_pay'];
  2326. } else {
  2327. return $json;
  2328. }
  2329. $json[date('Y-m-d H:i:s')] = [
  2330. 'coupon_id' => $params['coupon_id'] ?? null,
  2331. 'coupon_value' => $params['order_discount_amount'] ?? '',
  2332. 'coupon_classify' => $couponClassify,
  2333. 'coupon_detail_id' => [$couponClassifyDesc],
  2334. 'coupon_classify_en' => $params['preferential']
  2335. ];
  2336. return $json;
  2337. } catch (BusinessException $e) {
  2338. throw new BusinessException($e->getMessage());
  2339. } catch (\Exception $e) {
  2340. dump($e->getMessage());
  2341. throw new BusinessException("优惠数据错误");
  2342. }
  2343. }
  2344. /**
  2345. * @Desc 入配送记录
  2346. * @Author Gorden
  2347. * @Date 2024/9/23 10:45
  2348. *
  2349. * @param $params
  2350. * @return void
  2351. * @throws BusinessException
  2352. */
  2353. public function insertExpressOne($params, $orderId)
  2354. {
  2355. if (isset($params['delivery']) && $params['delivery'] == 'LOGISTICS') {
  2356. $params['order_express_type'] = '配送';
  2357. // 入配送
  2358. $this->saveExpress($params, $orderId);
  2359. } else if (isset($params['delivery']) && $params['delivery'] == 'PICKUP') {
  2360. $params['order_express_type'] = '自提';
  2361. $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();
  2362. if (!$premises) {
  2363. throw new BusinessException('自提门店不存在');
  2364. }
  2365. $params['order_express_city'] = $premises->dept_city;
  2366. $params['order_express_address'] = $premises->dept_address;
  2367. $params['order_express_telephone'] = $premises->dept_telephone;
  2368. $params['order_express_extend_json'] = json_encode(['pick_code' => random_string(4, 'number')]);
  2369. $this->saveExpress($params, $orderId);
  2370. } else if (isset($params['delivery']) && $params['delivery'] == 'ARRIVAL') {
  2371. $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();
  2372. $params['order_express_type'] = '到店';
  2373. if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
  2374. $params['order_express_type'] = '堂食';
  2375. }
  2376. if (!$premises) {
  2377. throw new BusinessException('门店不存在');
  2378. }
  2379. $params['order_express_city'] = $premises->dept_city;
  2380. $params['order_express_address'] = $premises->dept_address;
  2381. $params['order_express_telephone'] = $premises->dept_telephone;
  2382. $this->saveExpress($params, $orderId);
  2383. }
  2384. }
  2385. /**
  2386. * @Desc 释放下单时选的优惠券
  2387. * @Author Gorden
  2388. * @Date 2024/9/19 9:56
  2389. *
  2390. * @param $coupon
  2391. * @return false|string
  2392. */
  2393. private function releaseCoupon($coupon)
  2394. {
  2395. if (!empty($coupon) && is_array($coupon)) {
  2396. $updateData = [
  2397. 'coupon_detail_status' => 'ACTIVED',
  2398. 'coupon_detail_used_datetime' => ''
  2399. ];
  2400. foreach ($coupon as $key => $item) {
  2401. if (!empty($item['coupon_id']) && !empty($item['coupon_detail_id'])) {
  2402. foreach ($item['coupon_detail_id'] as $detailId) {
  2403. if (substr($detailId, 0, 4) == 'CUDT') {
  2404. CouponDetail::where('join_detail_coupon_id', $item['coupon_id'])
  2405. ->where('coupon_detail_id', $detailId)
  2406. ->where('coupon_detail_status', 'WAITING')
  2407. ->update($updateData);
  2408. }
  2409. }
  2410. unset($coupon[$key]);
  2411. }
  2412. }
  2413. }
  2414. return json_encode($coupon);
  2415. }
  2416. }