PackagesController.php 139 KB

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