PackagesController.php 139 KB

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