PackagesController.php 134 KB

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