PackagesController.php 147 KB

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