WholeController.php 236 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719
  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\coupon\CouponValidate;
  7. use app\admin\validate\device\DeviceValidate;
  8. use app\admin\validate\order\OrderExpressValidate;
  9. use app\admin\validate\order\OrderValidate;
  10. use app\common\payment\AppUtil;
  11. use app\common\payment\Tlpay;
  12. use app\controller\Curd;
  13. use app\model\Appointment;
  14. use app\model\ClientConfig;
  15. use app\model\Coupon;
  16. use app\model\CouponDetail;
  17. use app\model\Device;
  18. use app\model\Goods;
  19. use app\model\GoodsComponent;
  20. use app\model\GoodsRunning;
  21. use app\model\GoodsSku;
  22. use app\model\Member;
  23. use app\model\MemberAccount;
  24. use app\model\MemberBenefit;
  25. use app\model\MemberRole;
  26. use app\model\Order;
  27. use app\model\OrderExpress;
  28. use app\model\OrderReturn;
  29. use app\model\OrderSheet;
  30. use app\model\PayDetail;
  31. use app\model\Premises;
  32. use app\model\Supplier;
  33. use app\model\SysDept;
  34. use app\model\SysSerial;
  35. use app\model\SysUser;
  36. use Payment\Common\PayException;
  37. use support\Db;
  38. use support\exception\BusinessException;
  39. use support\Redis;
  40. use support\Request;
  41. use support\Response;
  42. use Tinywan\Jwt\JwtToken;
  43. use Webman\Event\Event;
  44. use Yansongda\Pay\Pay;
  45. use function Qiniu\Http\Middleware\compose;
  46. class WholeController extends Curd
  47. {
  48. public function __construct()
  49. {
  50. $this->model = new Order();
  51. $this->validate = true;
  52. $this->validateClass = new OrderValidate();
  53. }
  54. /**
  55. * @Desc 列表
  56. * @Author Gorden
  57. * @Date 2024/3/28 15:01
  58. *
  59. * @param Request $request
  60. * @return Response
  61. * @throws \support\exception\BusinessException
  62. */
  63. public function select(Request $request): Response
  64. {
  65. [$where, $format, $limit, $field, $order] = $this->selectInput($request);
  66. if (!empty($where['order_addtimes'])) {
  67. $where['order_addtimes'][0] = strtotime($where['order_addtimes'][0]);
  68. $where['order_addtimes'][1] = strtotime($where['order_addtimes'][1]);
  69. }
  70. $order = $request->get('order', 'desc');
  71. $type = $request->get('type', '');
  72. if ($type == 'todayOrder' && empty($where['order_addtimes'])) {
  73. $where['order_addtimes'][0] = strtotime(date('Y-m-d') . ' 00:00:00');
  74. $where['order_addtimes'][1] = strtotime(date('Y-m-d') . ' 23:59:59');
  75. } else if ($type == 'todayOrderAmount') {
  76. $todayTimeUnix = strtotime(date('Y-m-d') . ' 00:00:00');
  77. $groupIds = PayDetail::whereRaw('CAST(UNIX_TIMESTAMP(pay_paytimes) as SIGNED) > ? ', [$todayTimeUnix])
  78. ->where('join_pay_order_id', '<>', '')
  79. ->where('pay_category', '<>', 'RETURN')
  80. ->where('pay_category', '<>', 'RECHARGE')
  81. ->where('pay_category', '<>', 'CLEAR')
  82. ->pluck('join_pay_order_id')
  83. ->toArray();
  84. $where['order_groupby'] = ['in', $groupIds];
  85. }
  86. $orderIds = [];
  87. if (!empty($where['order_id'])) {
  88. $orderIds = Order::where('order_id', 'like', '%' . $where['order_id'] . '%')->pluck('order_id')->toArray();
  89. }
  90. $field = $field ?? 'order_addtimes';
  91. if (!empty($where['order_status_system']) && in_array($where['order_status_system'], ['PENDING', 'WAITING', 'SENDING', 'RECVING', 'SIGNED', 'CONFIRM'])) {
  92. if ($where['order_status_system'] == 'SENDING') {
  93. $where['order_express.order_express_type'] = '配送';
  94. }
  95. $where['order_is_complete'] = 'N';
  96. $where['order_category'] = isset($where['order_category']) ? $where['order_category'] : ['in', 'SYSTEM,NORMAL,DISHES'];
  97. }
  98. if (!empty($where['order_status_system']) && $where['order_status_system'] == 'RETURN') {
  99. unset($where['order_status_system']);
  100. unset($where['order_is_complete']);
  101. $where['order_category'] = 'RETURN';
  102. }
  103. if ($request->get('return')) {
  104. $where['order_return.order_return_status'] = $request->get('return');
  105. }
  106. $goodsIds = [];
  107. if ($request->get('goods_classify') || $request->get('goods_name')) {
  108. // $where['order_id'] = '';
  109. $goodsClassify = $request->get('goods_classify', '');
  110. $goodsName = $request->get('goods_name', '');
  111. if (!empty($goodsName) && empty($goodsClassify)) {
  112. $goodsIds = Goods::where('goods_name', 'like', '%' . $request->get('goods_name') . '%')->pluck('goods_id')->toArray();
  113. } else if (!empty($goodsClassify)) {
  114. if ($goodsClassify == 'SERVICE') {
  115. $goodsModel = Goods::whereIn('goods_classify', ['SERVICE', 'CHNMED', 'CHNNCD']);
  116. } else {
  117. $goodsModel = Goods::where('goods_classify', $goodsClassify);
  118. }
  119. if (!empty($goodsName)) {
  120. $goodsModel->where('goods_name', 'like', '%' . $goodsName . '%');
  121. }
  122. $goodsIds = $goodsModel->pluck('goods_id')->toArray();
  123. }
  124. }
  125. if ($request->get('goods_classify') || $request->get('goods_name')) {
  126. $orderGoodsIds = OrderSheet::whereIn('join_sheet_goods_id', $goodsIds)->pluck('join_sheet_order_id')->toArray();
  127. // if ($orderGoodsIds) {
  128. if (!empty($where['order_id'])) {
  129. $orderIds = array_intersect($orderIds, $orderGoodsIds);
  130. $where['order_id'] = ['in', implode(',', $orderIds)];
  131. } else {
  132. $where['order_id'] = ['in', implode(',', $orderGoodsIds)];
  133. }
  134. // }
  135. } elseif (!empty($orderIds)) {
  136. $where['order_id'] = ['in', implode(',', $orderIds)];
  137. }
  138. if (empty($where['order_category'])) {
  139. // 充值订单不显示
  140. $where['order_category'] = ['<>', 'RECHARGE'];
  141. }
  142. // 自提订单
  143. if (!empty($where['order_status_system']) && $where['order_status_system'] == 'PICKUP') {
  144. $where['order_is_complete'] = 'N';
  145. $where['order_status_system'] = 'SENDING';
  146. $where['order_express.order_express_type'] = '自提';
  147. }
  148. $query = $this->doSelect($where, $field, $order);
  149. return $this->doFormat($query, $format, $limit);
  150. }
  151. protected function doSelect(array $where, string $field = null, string $order = 'desc')
  152. {
  153. $model = $this->model->with([
  154. 'sheets' => function ($query) {
  155. $query->select('join_sheet_order_id', 'order_sheet_id', 'join_sheet_goods_id', 'order_sheet_num', 'order_sheet_price');
  156. },
  157. 'member' => function ($query) {
  158. $query->select('member_id', 'member_mobile');
  159. },
  160. 'cert' => function ($query) {
  161. $query->select('join_cert_member_id', 'member_cert_name');
  162. },
  163. // 'return' => function ($query) use ($where){
  164. // if (isset($where['return'])){
  165. // dump($where['return']);
  166. // $query = $query->where('order_return_status',$where['return']);
  167. // }
  168. // $query->select('orders_return_id', 'join_return_order_id', 'order_return_status');
  169. // },
  170. // 'express' => function ($query) {
  171. // $query->select('join_express_order_id', 'order_express_type');
  172. // }
  173. ])->leftJoin('order_return', 'order_return.join_return_order_id', '=', 'order.order_id')
  174. ->leftJoin('order_express', 'order_express.join_express_order_id', '=', 'order.order_id');
  175. // ->leftJoin('pay_detail', 'pay_detail.join_pay_order_id', '=', 'order.order_groupby');
  176. // ->leftJoin('order_sheet','join_sheet_order_id','=','order.order_id');
  177. foreach ($where as $column => $value) {
  178. if (is_array($value)) {
  179. if ($value[0] === 'like' || $value[0] === 'not like') {
  180. $model = $model->where($column, $value[0], "%$value[1]%");
  181. } elseif (in_array($value[0], ['>', '=', '<', '<>'])) {
  182. $model = $model->where($column, $value[0], $value[1]);
  183. } elseif ($value[0] == 'in' && !empty($value[1])) {
  184. $valArr = $value[1];
  185. if (is_string($value[1])) {
  186. $valArr = explode(",", trim($value[1]));
  187. }
  188. $model = $model->whereIn($column, $valArr);
  189. } elseif ($value[0] == 'not in' && !empty($value[1])) {
  190. $valArr = $value[1];
  191. if (is_string($value[1])) {
  192. $valArr = explode(",", trim($value[1]));
  193. }
  194. $model = $model->whereNotIn($column, $valArr);
  195. } elseif ($value[0] == 'null') {
  196. $model = $model->whereNull($column);
  197. } elseif ($value[0] == 'not null') {
  198. $model = $model->whereNotNull($column);
  199. } elseif ($value[0] !== '' || $value[1] !== '') {
  200. $model = $model->whereBetween($column, $value);
  201. }
  202. } else {
  203. $model = $model->where($column, $value);
  204. }
  205. }
  206. if ($field) {
  207. $model = $model->orderBy($field, $order);
  208. }
  209. $model = $model->select('order.*', 'order_express.join_express_order_id', 'order_express.order_express_type', 'order_return.orders_return_id', 'order_return.join_return_order_id', 'order_return.order_return_status', 'order_return.order_return_apply_json', 'order_return.order_return_remark');
  210. return $model;
  211. }
  212. public function afterQuery($items)
  213. {
  214. foreach ($items as &$item) {
  215. $sheetDeng = '';
  216. $item['sheet'] = $item['sheets'][0] ?? [];
  217. if (!empty($item['sheet'])) {
  218. $goods = Goods::where('goods_id', $item['sheet']['join_sheet_goods_id'])->first();
  219. if (count($item['sheets']) > 1 && !empty($goods) && $goods->goods_classify == 'MEALS') {
  220. $sheetDeng = ' 等餐品';
  221. }
  222. $item['sheet']['goods_name'] = ($goods && $goods->goods_name) ? $goods->goods_name . $sheetDeng : '';
  223. $item['sheet']['goods_classify'] = $goods->goods_classify ?? '';
  224. $item['sheet']['order_sheet_num'] = intval($item['sheet']['order_sheet_num']);
  225. }
  226. unset($item['sheets']);
  227. if (isset($item['orders_return_id'])) {
  228. $item['return'] = [
  229. 'orders_return_id' => $item['orders_return_id'],
  230. 'join_return_order_id' => $item['join_return_order_id'],
  231. 'order_return_status' => $item['order_return_status'],
  232. 'order_return_apply_json' => $item['order_return_apply_json'],
  233. 'order_return_remark' => $item['order_return_remark']
  234. ];
  235. }
  236. if (isset($item['join_express_order_id'])) {
  237. $item['express'] = [
  238. 'join_express_order_id' => $item['join_express_order_id'],
  239. 'order_express_type' => $item['order_express_type']
  240. ];
  241. unset($item['join_express_order_id'], $item['order_express_type']);
  242. }
  243. $payDetails = PayDetail::where('join_pay_order_id', $item['order_groupby'])
  244. ->where('pay_category', '<>', 'REFUND')
  245. ->where('pay_status', 'SUCCESS')
  246. ->select('pay_id', 'pay_category', 'pay_prepayid', 'pay_paytimes', 'pay_status', 'pay_amount', 'pay_extend_json')
  247. ->get()
  248. ->toArray();
  249. if (count($payDetails) > 1) {
  250. $item['payWay'] = "CONSTITUTE";
  251. } elseif (count($payDetails) == 1) {
  252. $payDetail0 = $payDetails[0];
  253. $item['payWay'] = $payDetail0['pay_prepayid'];
  254. } else {
  255. $item['payWay'] = null;
  256. }
  257. if (count($payDetails) > 0) {
  258. $payDetail0 = $payDetails[0];
  259. $item['pay_times'] = $payDetail0['pay_paytimes'];
  260. }
  261. if (!empty($item['payWay']) && $item['order_status_payment'] == 'SUCCESS') {
  262. $payWay = explode('-', $item['payWay']);
  263. if (!empty($payWay[1]) && $payWay[1] == 'CASH') {
  264. $item['payWay'] = '账户余额';
  265. } else if (!empty($payWay[1]) && $payWay[1] == 'WELFARE') {
  266. $item['payWay'] = '福利账户';
  267. } else if (!empty($payWay[1]) && $payWay[1] == 'VIP') {
  268. $item['payWay'] = 'VIP账户';
  269. } else if (!empty($payWay[1]) && $payWay[1] == 'QRCODE') {
  270. $item['payWay'] = '付款码';
  271. } else if (!empty($payWay[0]) && $payWay[0] == 'OFFLINE') {
  272. $item['payWay'] = '线下支付';
  273. } else if (!empty($payWay[0]) && $payWay[0] == 'OFFLINE_ALIPAY') {
  274. $item['payWay'] = '线下支付-支付宝';
  275. } else if (!empty($payWay[0]) && $payWay[0] == 'OFFLINE_WXPAY') {
  276. $item['payWay'] = '线下支付-微信';
  277. } else if (!empty($payWay[0]) && $payWay[0] == 'WXPAY') {
  278. $item['payWay'] = '微信支付';
  279. } else if (!empty($payWay[0]) && $payWay[0] == 'ALIPAY') {
  280. $item['payWay'] = '支付宝';
  281. } else if (!empty($payWay[0]) && $payWay[0] == 'CONSTITUTE') {
  282. $item['payWay'] = '组合支付';
  283. } else if (!empty($payWay[0]) && $payWay[0] == 'MONEY') {
  284. $item['payWay'] = '现金';
  285. }
  286. } else {
  287. $item['payWay'] = null;
  288. }
  289. }
  290. return $items;
  291. }
  292. /**
  293. * @Desc 订单商品详情
  294. * @Author Gorden
  295. * @Date 2024/3/29 8:50
  296. *
  297. * @param Request $request
  298. * @return Response
  299. */
  300. public function sheet(Request $request)
  301. {
  302. try {
  303. $orderId = $request->get('order_id');
  304. $orderSheet = OrderSheet::with([
  305. 'member' => function ($query) {
  306. $query->select('member_id', 'member_mobile', 'member_is_owner', 'join_member_role_id');
  307. },
  308. 'goods' => function ($query) {
  309. $query->select('goods_id', 'goods_name', 'goods_cover', 'goods_market_price', 'goods_sales_price', 'goods_classify', 'goods_if_express');
  310. },
  311. 'memberInfo',
  312. 'cert',
  313. 'sku' => function ($query) {
  314. $query->where('goods_sku_status', 'ON')
  315. ->select('goods_sku_id', 'join_sku_goods_id', 'goods_sku_specs_json', 'goods_sku_sales_price');
  316. },
  317. 'skus',
  318. 'refund' => function ($query) {
  319. $query->select('join_return_order_id', 'order_return_status');
  320. }
  321. ])->where('join_sheet_order_id', $orderId)
  322. ->orderBy('order_sheet_id', 'DESC')
  323. ->get()
  324. ->toArray();
  325. $order = Order::where('order_id', $orderId)->first();
  326. $express = OrderExpress::where('join_express_order_id', $orderId)->first();
  327. $premises = '';
  328. if ($express && $express->order_express_type == '自提') {
  329. $premises = $express->order_express_company;
  330. }
  331. $sheetAmount = 0;
  332. foreach ($orderSheet as &$item) {
  333. $sheetAmount += $item['order_sheet_amount'];
  334. $item['goods']['goods_cover'] = getenv('STORAGE_DOMAIN') . $item['goods']['goods_cover'];
  335. if (!empty($item['goods']) && $item['goods']['goods_classify'] == 'PACKAGE') {
  336. $components = GoodsComponent::with('goods')
  337. ->where('join_component_master_goods_id', $item['goods']['goods_id'])
  338. ->select('join_component_master_goods_id', 'join_component_goods_id', 'goods_component_price',
  339. 'goods_component_price', 'goods_component_json')
  340. ->get()
  341. ->toArray();
  342. $goodsArr = [];
  343. foreach ($components as $component) {
  344. $configJson = !empty($component['goods_component_json']) ? json_decode($component['goods_component_json'], true) : [];
  345. if (!empty($component['goods'])) {
  346. $supplierName = Supplier::where('supplier_id', $component['goods']['join_goods_supplier_id'])->value('supplier_name');
  347. $benefit = MemberBenefit::where('join_benefit_member_id', $item['join_sheet_member_id'])
  348. ->where('join_benefit_goods_id', $component['goods']['goods_id'])
  349. ->where('join_benefit_order_id', $orderId)
  350. ->first();
  351. $goodsArr[] = [
  352. 'goods_name' => $component['goods']['goods_name'],
  353. 'goods_cover' => getenv('STORAGE_DOMAIN') . $component['goods']['goods_cover'],
  354. 'supplier_name' => $supplierName,
  355. 'nbr' => $configJson['nbr'] ?? 0,
  356. 'used' => !empty($benefit->member_benefit_used_count) ? intval($benefit->member_benefit_used_count) : ''
  357. ];
  358. }
  359. }
  360. $item['goods']['components'] = $goodsArr;
  361. }
  362. if (!empty($item['sku'])) {
  363. if (!empty($item['sku']['goods_sku_specs_json'])) {
  364. $specsJson = json_decode($item['sku']['goods_sku_specs_json'], true);
  365. $skuName = '';
  366. foreach ($specsJson as $specsKey => $skuSpecs) {
  367. if (is_array($skuSpecs)) {
  368. $skuName = $skuName . ' ' . implode(' ', $skuSpecs) . ';';
  369. } else {
  370. $skuName = $skuName . ' ' . $skuSpecs . ';';
  371. }
  372. }
  373. $item['sku']['goods_sku_title'] = rtrim($skuName, ';');
  374. }
  375. }
  376. if (!empty($item['skus'])) {
  377. foreach ($item['skus'] as $key => $skus) {
  378. if (!empty($skus['goods_sku_specs_json'])) {
  379. $item['skus'][$key]['goods_sku_specs_json'] = json_decode($skus['goods_sku_specs_json']);
  380. $skuName = '';
  381. foreach ($item['skus'][$key]['goods_sku_specs_json'] as $specsKey => $skuSpecs) {
  382. $keyStr = ($specsKey == '规格') ? '' : ($specsKey . ':');
  383. if (is_array($skuSpecs)) {
  384. $skuName = $skuName . $keyStr . ' ' . implode(' ', $skuSpecs) . '; ';
  385. } else {
  386. $skuName = $skuName . $keyStr . ' ' . $skuSpecs . '; ';
  387. }
  388. }
  389. $item['skus'][$key]['sku_name'] = rtrim($skuName, '; ');
  390. }
  391. }
  392. } else {
  393. $item['skus'] = [];
  394. }
  395. if (in_array($item['goods']['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD'])) {
  396. $item['appontment'] = [];
  397. $appontments = Appointment::where('join_appointment_order_id', $orderId)
  398. ->where('appointment_status', 'DONE')
  399. ->select('appointment_status', 'appointment_id', 'appointment_done_datetime', 'appointment_done_json', 'appointment_apply_json')
  400. ->get()
  401. ->toArray();
  402. foreach ($appontments as $appontment) {
  403. $doneJson = [];
  404. $username = '';
  405. if (!empty($appontment['appointment_done_json'])) {
  406. $doneJson = json_decode($appontment['appointment_done_json'], true);
  407. if (isset($doneJson['charge'])) {
  408. $username = SysUser::where('user_id', $doneJson['charge']['charge_user_id'])->value('user_name');
  409. }
  410. }
  411. $person = 1;
  412. if (!empty($appontment->appointment_apply_json)) {
  413. $applyJson = json_decode($appontment->appointment_apply_json, true);
  414. if (isset($applyJson['person'])) {
  415. $person = $applyJson['person'];
  416. }
  417. }
  418. $item['appontment'][] = [
  419. 'member' => ($item['cert'] ? $item['cert']['member_cert_name'] . '-' : '') . ($item['member'] ? $item['member']['member_mobile'] : ''),
  420. 'goods_name' => $item['goods']['goods_name'],
  421. 'premisses' => isset($doneJson['charge']) ? $doneJson['charge']['charge_premises'] : '',
  422. 'username' => $username,
  423. 'nbr' => $person,
  424. 'done_time' => $appontment['appointment_done_datetime'],
  425. 'appointment_status' => $appontment['appointment_status'],
  426. ];
  427. }
  428. }
  429. if (!empty($item['order_sheet_extend_json']) && !$express) {
  430. $extendJson = json_decode($item['order_sheet_extend_json'], true);
  431. if (isset($extendJson['address_id'])) {
  432. $address = ClientConfig::where('client_config_id', $extendJson['address_id'])->first();
  433. if (!empty($address)) {
  434. $valJson = json_decode($address->client_config_val_json, true);
  435. $express = [
  436. 'order_express_address' => $valJson['address'] . ($valJson['numbers'] ?? ''),
  437. 'order_express_city' => $valJson['city'],
  438. 'order_express_mobile' => $valJson['mobile'],
  439. 'order_express_person' => $valJson['person']
  440. ];
  441. }
  442. }
  443. }
  444. $item['member']['level'] = '普通用户';
  445. if (!empty($item['member']['join_member_role_id'])) {
  446. $item['member']['level'] = MemberRole::where('member_role_id', $item['member']['join_member_role_id'])->value('member_role_name');
  447. }
  448. }
  449. $order->sheet_amount = number_format($sheetAmount, 2);
  450. $payDetails = PayDetail::where('join_pay_order_id', $order->order_groupby)
  451. ->where('pay_category', '<>', 'REFUND')
  452. ->where('pay_status', 'SUCCESS')
  453. ->select('pay_id', 'pay_category', 'pay_prepayid', 'pay_paytimes', 'pay_status', 'pay_amount', 'pay_extend_json')
  454. ->get();
  455. if (count($payDetails) > 1) {
  456. $order->pay_category = 'CONSTITUTE';
  457. }
  458. $payDetail = !empty($payDetails) && count($payDetails) > 0 ? $payDetails[0] : [];
  459. if (!empty($payDetail) && !empty($payDetail->pay_extend_json)) {
  460. $payExtendJson = json_decode($payDetail->pay_extend_json, true);
  461. $order->cancel_times = $payExtendJson['cancel_times'] ?? '';
  462. // $payDetail->cancel_times = $payExtendJson['cancel_times'] ?? '';
  463. }
  464. if (!empty($payDetail) && !empty($payDetail->pay_prepayid)) {
  465. $categoryArray = explode('-', $payDetail->pay_prepayid);
  466. if (isset($categoryArray[1])) {
  467. $payDetail->pay_category = $categoryArray[1];
  468. } else if (in_array($categoryArray[0], ['WXPAY', 'ALIPAY', 'OFFLINE', 'OFFLINE_ALIPAY', 'OFFLINE_WXPAY', 'MONEY'])) {
  469. $payDetail->pay_category = $categoryArray[0];
  470. }
  471. }
  472. $refund = OrderReturn::where('join_return_order_id', $orderId)
  473. ->select('order_return_status', 'order_return_apply_datetime', 'order_return_apply_json', 'order_return_accept_datetime', 'order_return_refund_json', 'order_return_extend_json')
  474. ->first();
  475. if (!empty($refund->order_return_refund_json)) {
  476. $returnRefundJson = json_decode($refund->order_return_refund_json, true);
  477. if (isset($returnRefundJson['user_id'])) {
  478. $userName = SysUser::where('user_id', $returnRefundJson['user_id'])->value('user_name');
  479. $returnRefundJson['person'] = $userName;
  480. unset($returnRefundJson['user_id']);
  481. }
  482. $refund->order_return_refund_json = json_encode($returnRefundJson);
  483. }
  484. if (!empty($order->order_config_json)) {
  485. $orderConfigJson = json_decode($order->order_config_json, true);
  486. if (isset($orderConfigJson['reach'])) {
  487. $order->reach = $orderConfigJson['reach'];
  488. }
  489. if (isset($orderConfigJson['table'])) {
  490. $order->table = $orderConfigJson['table'];
  491. }
  492. if (isset($orderConfigJson['eat'])) {
  493. $order->eat = $orderConfigJson['eat'];
  494. }
  495. if (isset($orderConfigJson['express'])) {
  496. $order->express = $orderConfigJson['express'];
  497. }
  498. if (isset($orderConfigJson['premises'])) {
  499. $order->premises = $orderConfigJson['premises'];
  500. }
  501. if (isset($orderConfigJson['tableid'])) {
  502. $order->dept_table_id = $orderConfigJson['tableid'];
  503. }
  504. }
  505. if (!empty($order->order_extend_json)) {
  506. $orderExtendJson = json_decode($order->order_extend_json, true);
  507. $order->referee = $orderExtendJson['referee'] ?? '';
  508. if (isset($orderExtendJson['cancel_times'])) {
  509. $order->cancel_times = $orderExtendJson['cancel_times'];
  510. }
  511. if (isset($orderExtendJson['free_remark'])) {
  512. $order->free_remark = $orderExtendJson['free_remark'];
  513. }
  514. }
  515. $discount = ['coupon_name' => '', 'classify' => '', 'value' => 0];
  516. if (!empty($order->order_discount_json)) {
  517. $orderDiscountJson = json_decode($order->order_discount_json, true);
  518. foreach ($orderDiscountJson as $discountItem) {
  519. if (!empty($discountItem['coupon_id'])) {
  520. $coupon = Coupon::where('coupon_id', $discountItem['coupon_id'])
  521. ->select('coupon_name', 'coupon_classify', 'coupon_category', 'coupon_value', 'coupon_minimum_limit')
  522. ->first();
  523. if (!$coupon) {
  524. continue;
  525. }
  526. $classify = CouponService::couponClassifyInfo($coupon->coupon_classify, $coupon->coupon_category, $coupon->coupon_value, $coupon->coupon_minimum_limit);
  527. $discount['coupon_name'] .= $coupon->coupon_classify . ':' . $coupon->coupon_name . '(优惠¥' . sprintf("%.2f", $discountItem['coupon_value']) . '), ';
  528. }
  529. if ($discountItem['coupon_classify'] == '退款') {
  530. continue;
  531. }
  532. if (empty($discountItem['coupon_id']) && !empty($discountItem['coupon_classify'])) {
  533. if (!empty($discountItem['coupon_detail_id'])) {
  534. $discount['classify'] .= $discountItem['coupon_detail_id'][0] . '(优惠¥' . sprintf("%.2f", $discountItem['coupon_value']) . '), ';
  535. } else {
  536. $discount['classify'] .= $discountItem['coupon_classify'] . '(优惠¥' . sprintf("%.2f", $discountItem['coupon_value']) . '), ';
  537. }
  538. }
  539. if (!empty($discountItem['coupon_value'])) {
  540. $discount['value'] += $discountItem['coupon_value'];
  541. }
  542. }
  543. if (!empty($discount['coupon_name'])) {
  544. $discount['coupon_name'] = rtrim($discount['coupon_name'], ', ');
  545. }
  546. if (!empty($discount['classify'])) {
  547. $discount['classify'] = rtrim($discount['classify'], ', ');
  548. }
  549. }
  550. $discount['value'] = sprintf("%.2f", $discount['value']);
  551. $order->discount = $discount;
  552. $order->premises = $order->premises ?? $premises;
  553. $data = [
  554. 'order' => $order,
  555. 'refund' => json_decode(json_encode($refund)),
  556. 'sheet' => json_decode(json_encode($orderSheet)),
  557. 'express' => json_decode(json_encode($express)),
  558. 'payDetail' => json_decode(json_encode($payDetail)),
  559. 'payDetails' => json_decode(json_encode($payDetails))
  560. ];
  561. return json_success('', $data);
  562. } catch (\Exception $e) {
  563. dump($e->getMessage());
  564. }
  565. }
  566. public function update(Request $request): Response
  567. {
  568. $params = $request->post();
  569. Db::beginTransaction();
  570. try {
  571. // 修改主订单
  572. $this->updateMain($params);
  573. // 修改sheet表
  574. $this->updateSheet($params);
  575. // 修改物流
  576. $this->updateExpress($params);
  577. Db::commit();
  578. _syslog("订单", "修改订单成功");
  579. return json_success('修改订单成功');
  580. } catch (\Exception $e) {
  581. dump($e->getMessage());
  582. Db::rollBack();
  583. _syslog("订单", "修改订单失败");
  584. return json_fail('修改订单失败');
  585. }
  586. }
  587. /**
  588. * 修改主订单
  589. */
  590. public function updateMain($params)
  591. {
  592. try {
  593. $order = Order::where('order_id', $params['order_id'])->first();
  594. $orderConfigJson = [];
  595. if (!empty($order->order_config_json)) {
  596. $orderConfigJson = json_decode($order->order_config_json, true);
  597. }
  598. // 优惠
  599. if (!empty($params['preferential'])) {
  600. $orderConfigJson['preferential'] = $params['preferential'];
  601. }
  602. if (!empty($params['dept_premises_id'])) {
  603. $premise = SysDept::where('dept_name', $params['dept_premises_id'])->where('dept_category', '营业场所')->first();
  604. $orderConfigJson['dept'] = $premise->dept_id ?? 0;
  605. $orderConfigJson['premises'] = $params['dept_premises_id'];
  606. }
  607. if (!empty($params['dept_table_id'])) {
  608. if (!empty($orderConfigJson['tableid']) && $params['dept_table_id'] != $orderConfigJson['tableid']) {
  609. // 原桌释放
  610. SysDept::where('dept_id', $orderConfigJson['tableid'])->update(['dept_status' => 'ACTIVED']);
  611. }
  612. // 新桌使用
  613. SysDept::where('dept_id', $params['dept_table_id'])->update(['dept_status' => 'USING']);
  614. $table = SysDept::where('dept_id', $params['dept_table_id'])->where('dept_category', '桌台')->first();
  615. $orderConfigJson['table'] = $table->dept_name ?? 0;
  616. $orderConfigJson['tableid'] = $params['dept_table_id'];
  617. }
  618. if (!empty($params['eat'])) {
  619. $orderConfigJson['eat'] = $params['eat'];
  620. }
  621. $data = [
  622. 'order_amount_pay' => $params['order_amount_pay'],
  623. 'order_amount_total' => $params['order_amount_total'],
  624. 'order_config_json' => json_encode($orderConfigJson),
  625. 'order_remark' => $params['order_remark'] ?? ''
  626. ];
  627. Order::where('order_id', $params['order_id'])->update($data);
  628. } catch (\Exception $e) {
  629. throw new BusinessException('修改订单失败');
  630. }
  631. }
  632. /**
  633. * 订单sheet
  634. */
  635. public function updateSheet($params)
  636. {
  637. try {
  638. // 判断餐品是否连带着服务或实体
  639. $goodsClassifys = array_unique(array_column($params['goodsContentList'], 'goods_classify'));
  640. if (in_array('MEALS', $goodsClassifys) && count($goodsClassifys) > 1) {
  641. return json_fail('餐饮餐品不支持和其他类型的产品一起下单');
  642. }
  643. if (in_array('MEALS', $goodsClassifys)) {
  644. $params['submit_goods_classify'] = 'MEALS';
  645. }
  646. foreach ($params['goodsContentList'] as $sheet) {
  647. // 先还原库存
  648. $orderSheet = OrderSheet::where('order_sheet_id', $sheet['order_sheet_id'])->first();
  649. if (!isset($params['submit_goods_classify']) || $params['submit_goods_classify'] != 'MEALS') {
  650. $goodsSku = GoodsSku::where('goods_sku_id', $orderSheet->join_sheet_goods_sku_id)->first();
  651. $skuStorageJson = json_decode($goodsSku->goods_sku_storage_json, true);
  652. $skuStorageJson['storage'] = $skuStorageJson['storage'] + $orderSheet->order_sheet_num;
  653. $goodsSku->goods_sku_storage_json = json_encode($skuStorageJson);
  654. $goodsSku->save();
  655. }
  656. $goodsRunning = GoodsRunning::where('join_running_goods_id', $orderSheet->join_sheet_goods_id)->first();
  657. $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage + $orderSheet->order_sheet_num;
  658. $goodsRunning->goods_running_sale = $goodsRunning->goods_running_sale - $orderSheet->order_sheet_num;
  659. $goodsRunning->save();
  660. $data = [
  661. 'order_sheet_num' => $sheet['nbr'],
  662. 'join_sheet_goods_sku_id' => $sheet['sku_id'],
  663. 'order_sheet_amount' => $sheet['nbr'] * $orderSheet->order_sheet_price,
  664. 'order_sheet_pay' => $sheet['nbr'] * $orderSheet->order_sheet_price,
  665. ];
  666. OrderSheet::where('order_sheet_id', $sheet['order_sheet_id'])->update($data);
  667. // 减库存
  668. if (!isset($params['submit_goods_classify']) || $params['submit_goods_classify'] != 'MEALS') {
  669. $goodsSku = GoodsSku::where('goods_sku_id', $sheet['sku_id'])->first();
  670. $skuStorageJson = json_decode($goodsSku->goods_sku_storage_json, true);
  671. $skuStorageJson['storage'] = $skuStorageJson['storage'] - $sheet['nbr'];
  672. if ($skuStorageJson['storage'] < 0) {
  673. throw new BusinessException('库存不足');
  674. }
  675. $goodsSku->goods_sku_storage_json = json_encode($skuStorageJson);
  676. $goodsSku->save();
  677. }
  678. $goodsRunning = GoodsRunning::where('join_running_goods_id', $orderSheet->join_sheet_goods_id)->first();
  679. $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $sheet['nbr'];
  680. if ($goodsRunning->goods_running_storage < 0) {
  681. throw new BusinessException('库存不足');
  682. }
  683. $goodsRunning->goods_running_sale = $goodsRunning->goods_running_sale + $sheet['nbr'];
  684. $goodsRunning->save();
  685. }
  686. } catch (\Exception $e) {
  687. dump($e->getMessage());
  688. throw new BusinessException('修改订单详情失败');
  689. }
  690. }
  691. public function updateExpress($params)
  692. {
  693. $express = OrderExpress::where('join_express_order_id', $params['order_id'])->first();
  694. if (!$express && in_array($params['delivery'], ['PICKUP', 'LOGISTICS'])) {
  695. throw new BusinessException('物流信息异常');
  696. }
  697. if ($params['delivery'] == 'PICKUP') {
  698. $premises = SysDept::where('dept_category', '营业场所')->where('dept_name', $params['dept_premises_id'])->first();
  699. $express->order_express_type = '自提';
  700. $express->order_express_city = str_replace(',', ' ', $premises->dept_city);
  701. $express->order_express_address = $premises->dept_address;
  702. $express->order_express_mobile = '';
  703. $express->order_express_person = '';
  704. $express->order_express_telephone = $premises->dept_telephone ?? '';
  705. $express->order_express_company = $params['dept_premises_id'];
  706. } else if ($params['delivery'] == 'LOGISTICS') {
  707. $express->order_express_type = '配送';
  708. $express->order_express_city = $params['order_express_city'] ?? '';
  709. $express->order_express_address = $params['order_express_address'] ?? '';
  710. $express->order_express_mobile = $params['order_express_mobile'] ?? '';
  711. $express->order_express_person = $params['order_express_person'] ?? '';
  712. $express->order_express_telephone = '';
  713. $express->order_express_company = '';
  714. }
  715. try {
  716. if (($params['delivery'] == 'PICKUP') || ($params['delivery'] == 'LOGISTICS')) {
  717. $express->save();
  718. }
  719. } catch (\Exception $e) {
  720. dump($e->getTrace());
  721. throw new BusinessException('修改配送方式失败');
  722. }
  723. }
  724. public function pay(Request $request)
  725. {
  726. $params = $request->post();
  727. // 余额、福利、储值卡 验证短信
  728. if ($params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['CASH', 'CARD', 'WELFARE'])) {
  729. $code = $params['sms_code'];
  730. if (!$code) {
  731. return json_fail("验证码错误,请重新输入");
  732. }
  733. $member = Member::find($params['join_order_member_id']);
  734. $mobile = $member->member_mobile;
  735. $key = "SMS:CODE:ORDER_PAY:" . $mobile;
  736. $redisCode = Redis::get($key);
  737. if ($redisCode != $code && $code != '123456') {
  738. return json_fail("验证码错误,请重新输入");
  739. }
  740. Redis::del($key);
  741. }
  742. // 验证线下付款密码
  743. if ($params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['OFFLINE', 'MONEY'])) {
  744. $password = $params['offline_password'];
  745. if ($password != '666888') {
  746. return json_fail("密码错误,请重新输入");
  747. }
  748. }
  749. $order = Order::where('order_id', $params['order_id'])->first();
  750. if (!$order) {
  751. return json_fail('订单异常');
  752. }
  753. if ($order->order_status_system != 'PAYING') {
  754. return json_fail('订单不是可支付状态');
  755. }
  756. if (!empty($order->order_config_json)) {
  757. $orderConfigJson = json_decode($order->order_config_json, true);
  758. if (isset($orderConfigJson['premises'])) {
  759. $premises = SysDept::where('dept_name', $orderConfigJson['premises'])->first();
  760. if (!empty($premises)) {
  761. $params['submit_premises_id'] = $premises->dept_id;
  762. }
  763. }
  764. }
  765. $params['orderId'] = $params['order_id'];
  766. $params['orderGroupId'] = $order->order_groupby;
  767. $goods = Goods::where('goods_id', $params['join_sheet_goods_id'])
  768. ->select('goods_id', 'goods_name', 'goods_classify')
  769. ->first();
  770. if (!$goods) {
  771. return json_fail('产品数据异常');
  772. }
  773. $goods = $goods->toArray();
  774. $params['goods_classify'] = $goods['goods_classify'] ?? '';
  775. $systemStatus = 'SENDING'; // 待发货
  776. // 立即结算
  777. if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'VIP'])) {
  778. $order->order_is_complete = 'Y';
  779. $systemStatus = 'DONE';
  780. }
  781. if ($params['goods_classify'] == 'PACKAGE' && $params['delivery'] == 'ARRIVAL') {
  782. $systemStatus = "WAITING";
  783. }
  784. Db::beginTransaction();
  785. try {
  786. // 使用优惠券
  787. $couponUseJson = [];
  788. if (!empty($params['join_order_member_id']) && !empty($params['preferential'])) {
  789. $couponResult = OrderService::payUseCoupon('pay', 'Y', $params['join_order_member_id'], $params['goodsContentList'], $params['preferential'], $params['order_amount_total']);
  790. if (!empty($couponResult['pay_amount']) && $couponResult['pay_amount'] != $params['order_amount_pay']) {
  791. throw new BusinessException("计算优惠后,实付金额错误!");
  792. }
  793. // 组装优惠券使用数据,存主表优惠里
  794. if (!empty($couponResult['use_coupon_json'])) {
  795. $couponUseJson = $couponResult['use_coupon_json'];
  796. if (!empty($order->order_discount_json)) {
  797. $orderDiscountJson = json_decode($order->order_discount_json, true);
  798. if (!empty($orderDiscountJson)) {
  799. $couponUseJson = json_encode(array_merge($orderDiscountJson, json_decode($couponUseJson, true)));
  800. }
  801. }
  802. }
  803. }
  804. // 存储优惠信息
  805. $order->order_discount_json = json_encode($this->discountRecord($couponUseJson, $params));
  806. // 组合支付时,付款码应收金额
  807. $qrcodePayAmount = 0;
  808. if ($params['pay_category'] == 'OFFLINE' || $params['pay_category'] == 'MONEY') {
  809. $order->order_status_system = $systemStatus;
  810. $order->order_status_payment = 'SUCCESS';
  811. if ($params['pay_category'] == 'OFFLINE' && !empty($params['pay_category_sub'])) {
  812. $params['pay_category'] = $params['pay_category_sub'];
  813. }
  814. } else if ($params['pay_category'] == 'CASH') { // 余额支付
  815. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  816. ->where('member_account_classify', 'CASH')
  817. ->where('member_account_status', 'ACTIVED')
  818. ->first();
  819. if (!$account) {
  820. throw new BusinessException('账户异常');
  821. }
  822. $amount = $account->member_account_surplus + $account->member_account_added;
  823. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  824. throw new BusinessException('账户余额不足');
  825. }
  826. if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
  827. $qrcodePayAmount = $params['order_amount_pay'] - $amount;
  828. $params['order_amount_pay'] = $amount;
  829. }
  830. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  831. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  832. $account->member_account_surplus = 0;
  833. $account->member_account_added = $cut;
  834. } else {
  835. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  836. }
  837. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  838. $account->save();
  839. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] <= $amount)) {
  840. $order->order_status_system = $systemStatus;
  841. $order->order_status_payment = 'SUCCESS';
  842. }
  843. } else if ($params['pay_category'] == 'VIP') { // 余额支付
  844. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  845. ->where('member_account_classify', 'VIP')
  846. ->where('member_account_status', 'ACTIVED')
  847. ->first();
  848. if (!$account) {
  849. throw new BusinessException('账户异常');
  850. }
  851. $amount = $account->member_account_surplus + $account->member_account_added;
  852. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  853. throw new BusinessException('账户余额不足');
  854. }
  855. if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
  856. $qrcodePayAmount = $params['order_amount_pay'] - $amount;
  857. $params['order_amount_pay'] = $amount;
  858. }
  859. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  860. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  861. $account->member_account_surplus = 0;
  862. $account->member_account_added = $cut;
  863. } else {
  864. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  865. }
  866. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  867. $account->save();
  868. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] <= $amount)) {
  869. $order->order_status_system = $systemStatus;
  870. $order->order_status_payment = 'SUCCESS';
  871. }
  872. } else if ($params['pay_category'] == 'WELFARE') { // 福利账户
  873. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  874. ->where('member_account_classify', 'WELFARE')
  875. ->where('member_account_status', 'ACTIVED')
  876. ->first();
  877. if (!$account) {
  878. throw new BusinessException('账户异常');
  879. }
  880. $account->member_account_surplus = floatval($account->member_account_surplus);
  881. if ($params['pay_constitute'] == 'N' && ($params['order_amount_pay'] > $account->member_account_surplus)) {
  882. throw new BusinessException('账户余额不足');
  883. }
  884. if ($params['pay_constitute'] == 'Y' && ($params['order_amount_pay'] > $account->member_account_surplus)) {
  885. $qrcodePayAmount = $params['order_amount_pay'] - $account->member_account_surplus;
  886. $params['order_amount_pay'] = $account->member_account_surplus;
  887. }
  888. if ($params['pay_constitute'] == 'N' && ($params['order_amount_pay'] <= $account->member_account_surplus)) {
  889. $order->order_status_system = $systemStatus;
  890. $order->order_status_payment = 'SUCCESS';
  891. }
  892. // 福利账户 300 、 700
  893. if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS'])) {
  894. $payDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  895. ->where('pay_status', 'SUCCESS')
  896. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  897. ->whereIn('pay_category', ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'DESHES'])
  898. ->get()
  899. ->toArray();
  900. $payDetailArray = array_column($payDetails, 'pay_amount', 'join_pay_order_id');
  901. $refundPayDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  902. ->where('pay_status', 'SUCCESS')
  903. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  904. ->where('pay_category', 'REFUND')
  905. ->get()
  906. ->toArray();
  907. $refundPayDetailArray = array_column($refundPayDetails, 'pay_amount', 'join_pay_order_id');
  908. $paySum = 0;
  909. foreach ($payDetailArray as $key => $item) {
  910. if (isset($refundPayDetailArray[$key])) {
  911. $paySum = $paySum + ($item - $refundPayDetailArray[$key]);
  912. continue;
  913. }
  914. $paySum = $paySum + $item;
  915. }
  916. if ($params['pay_constitute'] == 'N' && 700 - $paySum < $params['order_amount_pay']) {
  917. throw new BusinessException('超出福利限额');
  918. } else if ($params['pay_constitute'] == 'Y' && 700 - $paySum < $params['order_amount_pay']) {
  919. $qrcodePayAmount = $params['order_amount_pay'] - (700 - $paySum);
  920. $params['order_amount_pay'] = (700 - $paySum);
  921. }
  922. } else {
  923. $payDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  924. ->where('pay_status', 'SUCCESS')
  925. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  926. ->whereNotIn('pay_category', ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'DESHES', 'REFUND', 'RECHARGE'])
  927. ->get()
  928. ->toArray();
  929. $payDetailArray = array_column($payDetails, 'pay_amount', 'join_pay_order_id');
  930. $refundPayDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  931. ->where('pay_status', 'SUCCESS')
  932. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  933. ->where('pay_category', 'REFUND')
  934. ->get()
  935. ->toArray();
  936. $refundPayDetailArray = array_column($refundPayDetails, 'pay_amount', 'join_pay_order_id');
  937. $paySum = 0;
  938. foreach ($payDetailArray as $key => $item) {
  939. if (isset($refundPayDetailArray[$key])) {
  940. $paySum = $paySum + ($item - $refundPayDetailArray[$key]);
  941. continue;
  942. }
  943. $paySum = $paySum + $item;
  944. }
  945. if ($params['pay_constitute'] == 'N' && 300 - $paySum < $params['order_amount_pay']) {
  946. throw new BusinessException('超出福利限额');
  947. } else if ($params['pay_constitute'] == 'Y' && 300 - $paySum < $params['order_amount_pay']) {
  948. $qrcodePayAmount = $params['order_amount_pay'] - (300 - $paySum);
  949. $params['order_amount_pay'] = (300 - $paySum);
  950. }
  951. }
  952. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  953. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  954. $account->save();
  955. } else if ($params['pay_category'] == 'CARD') { // 储值卡账户
  956. $cardNbr = $params['card_nbr'];
  957. if (!$cardNbr) {
  958. throw new BusinessException('账户异常');
  959. }
  960. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  961. ->where('member_account_nbr', $cardNbr)
  962. ->where('member_account_status', 'ACTIVED')
  963. ->first();
  964. if (!$account) {
  965. throw new BusinessException('账户异常');
  966. }
  967. $amount = $account->member_account_surplus + $account->member_account_added;
  968. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  969. throw new BusinessException('账户余额不足');
  970. }
  971. if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
  972. $qrcodePayAmount = $params['order_amount_pay'] - $amount;
  973. $params['order_amount_pay'] = $amount;
  974. }
  975. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  976. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  977. $account->member_account_surplus = 0;
  978. $account->member_account_added = $cut;
  979. } else {
  980. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  981. }
  982. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  983. $account->save();
  984. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] <= $amount)) {
  985. $order->order_status_system = $systemStatus;
  986. $order->order_status_payment = 'SUCCESS';
  987. }
  988. }
  989. if (($params['pay_constitute'] == 'Y' || $params['pay_category'] == 'QRCODE') && !empty($params['qrcode_nbr'])) { // 付款码
  990. // 提交过来的支付分类
  991. $submitPayCategory = $params['pay_category'];
  992. // 账户支付的金额
  993. $accountAmount = $params['order_amount_pay'];
  994. if ($params['pay_constitute'] == 'Y' && $qrcodePayAmount > 0) {
  995. // 组合支付,改成需要付款码需要支付的金额
  996. $params['order_amount_pay'] = $qrcodePayAmount;
  997. }
  998. // 去支付
  999. $result = OrderService::qrcodePay($params);
  1000. $result = json_encode($result);
  1001. $params['pay_json_response'] = $result;
  1002. $result = json_decode($result, true);
  1003. $prefix = substr($params['qrcode_nbr'], 0, 2);
  1004. if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
  1005. $params['pay_category'] = 'WXPAY';
  1006. 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')) {
  1007. $order->order_status_system = 'PAYING';
  1008. $order->order_status_payment = 'PENDING';
  1009. $order->order_is_complete = 'N';
  1010. // Db::rollBack();
  1011. // return json_fail('支付失败');
  1012. } else {
  1013. $order->order_status_system = $systemStatus;
  1014. $order->order_status_payment = 'SUCCESS';
  1015. }
  1016. } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
  1017. $params['pay_category'] = 'ALIPAY';
  1018. if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {
  1019. $order->order_status_system = 'PAYING';
  1020. $order->order_status_payment = 'PENDING';
  1021. $order->order_is_complete = 'N';
  1022. // Db::rollBack();
  1023. // return json_fail('支付失败');
  1024. } else {
  1025. $order->order_status_system = $systemStatus;
  1026. $order->order_status_payment = 'SUCCESS';
  1027. }
  1028. } else {
  1029. throw new BusinessException('付款码无效');
  1030. }
  1031. // 组合支付,追加加一条支付记录 pay_detail
  1032. if ($params['pay_constitute'] == 'Y' && $qrcodePayAmount > 0) {
  1033. $insertPayDetailData = [
  1034. 'join_pay_member_id' => $params['join_order_member_id'],
  1035. 'join_pay_order_id' => $params['orderGroupId'],
  1036. 'pay_status' => 'SUCCESS',
  1037. 'pay_category' => $params['goods_classify'],
  1038. 'pay_amount' => $params['order_amount_pay'],
  1039. 'pay_paytimes' => date('Y-m-d H:i:s'),
  1040. 'pay_prepayid' => $params['pay_category'],
  1041. 'pay_json_request' => json_encode($params),
  1042. 'pay_json_response' => $params['pay_json_response'],
  1043. 'join_pay_object_json' => !empty($params['orderId']) ? json_encode(['order_id' => $params['orderId']]) : '[]',
  1044. 'pay_addtimes' => time()
  1045. ];
  1046. PayDetail::insert($insertPayDetailData);
  1047. // 组合支付,还原提交的支付分类
  1048. $params['pay_category'] = $submitPayCategory;
  1049. }
  1050. // 账户支付的金额
  1051. $params['order_amount_pay'] = $accountAmount;
  1052. }
  1053. $orderConfigJson = [];
  1054. if (!empty($order->order_config_json)) {
  1055. $orderConfigJson = json_decode($order->order_config_json, true);
  1056. }
  1057. $orderConfigJson['preferential'] = $params['preferential'] ?? '';
  1058. if (isset($orderConfigJson['tableid']) && !empty($orderConfigJson['tableid'])) {
  1059. SysDept::where('dept_id', $orderConfigJson['tableid'])->where('dept_category', '桌台')->update(['dept_status' => 'ACTIVED']);
  1060. }
  1061. $order->order_config_json = json_encode($orderConfigJson);
  1062. $order->order_amount_pay = $params['order_amount_pay'] + $qrcodePayAmount;
  1063. // 康养城订单,支付完就结束了
  1064. if ($order->order_status_payment == 'SUCCESS' && $params['goods_classify'] == 'VIP') {
  1065. $order->order_is_complete = 'Y';
  1066. }
  1067. // 主订单
  1068. $order->save();
  1069. // sheet
  1070. if ($order->order_status_payment == 'SUCCESS') {
  1071. OrderSheet::where('join_sheet_order_id', $params['order_id'])->update([
  1072. 'order_sheet_status' => $systemStatus,
  1073. ]);
  1074. }
  1075. // payDetail
  1076. $payData = [
  1077. 'pay_amount' => $params['order_amount_pay']
  1078. ];
  1079. if ($order->order_status_payment == 'SUCCESS') {
  1080. $payData['pay_paytimes'] = date('Y-m-d H:i:s');
  1081. $payData['pay_status'] = 'SUCCESS';
  1082. }
  1083. if ($params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) {
  1084. $payData['pay_prepayid'] = $params['pay_category'];
  1085. $payData['pay_json_response'] = $params['pay_json_response'];
  1086. } else if ($params['pay_category'] == 'CASH') {
  1087. $payData['pay_prepayid'] = $params['join_order_member_id'] . '-CASH';
  1088. } else if ($params['pay_category'] == 'WELFARE') {
  1089. $payData['pay_prepayid'] = $params['join_order_member_id'] . '-WELFARE';
  1090. } else if ($params['pay_category'] == 'VIP') {
  1091. $payData['pay_prepayid'] = $params['join_order_member_id'] . '-VIP';
  1092. } else if ($params['pay_category'] == 'CARD') {
  1093. $payData['pay_prepayid'] = $params['card_nbr'];
  1094. } else if ($params['pay_category'] == 'OFFLINE') {
  1095. $payData['pay_prepayid'] = 'OFFLINE';
  1096. } else if ($params['pay_category'] == 'OFFLINE_ALIPAY') {
  1097. $payData['pay_prepayid'] = 'OFFLINE_ALIPAY';
  1098. } else if ($params['pay_category'] == 'OFFLINE_WXPAY') {
  1099. $payData['pay_prepayid'] = 'OFFLINE_WXPAY';
  1100. } else if ($params['pay_category'] == 'MONEY') {
  1101. $payData['pay_prepayid'] = 'MONEY';
  1102. }
  1103. // 如果 是APP 过来的菜订单,可能没有paydetail
  1104. if (!PayDetail::where('join_pay_order_id', $order->order_groupby)->where('pay_category', '<>', 'WXPAY')->where('pay_category', '<>', 'ALIPAY')->exists()) {
  1105. $payData['join_pay_member_id'] = $params['join_order_member_id'];
  1106. $payData['join_pay_order_id'] = $order->order_groupby;
  1107. $payData['pay_status'] = $payData['pay_status'] == 'SUCCESS' ? $payData['pay_status'] : 'WAITING';
  1108. $payData['pay_category'] = $params['goods_classify'] ?? '';
  1109. $payData['pay_json_request'] = json_encode($params); // {"pay-result": "支付成功", "result-datetime": "2024-07-29 18:38:21"}
  1110. $payData['pay_json_response'] = $payData['pay_status'] == 'SUCCESS' ? json_encode([
  1111. 'pay-result' => '支付成功', 'result-datetime' => date('Y-m-d H:i:s')
  1112. ]) : '[]';
  1113. $payData['join_pay_object_json'] = !empty($params['orderId']) ? json_encode(['order_id' => $params['orderId']]) : '[]';
  1114. $payData['pay_addtimes'] = time();
  1115. PayDetail::insert($payData);
  1116. } else {
  1117. // 更新非微信支付宝的支付记录
  1118. PayDetail::where('join_pay_order_id', $order->order_groupby)->where('pay_category', '<>', 'WXPAY')->where('pay_category', '<>', 'ALIPAY')->update($payData);
  1119. }
  1120. $writeOffDate = [];
  1121. $applyData = [];
  1122. // 服务已完成,生成核销数据
  1123. // if ($order->order_status_payment == 'SUCCESS' && in_array($goods['goods_classify'], ['SERVICE','CHNMED','CHNNCD', 'PACKAGE'])) {
  1124. // $writeOffDate = OrderService::generateWriteOffData($params);
  1125. // $applyData = OrderService::generateAppointmentApplyData($params);
  1126. // }
  1127. // 有预约单,状态已完成
  1128. $appointment = Appointment::where('join_appointment_order_id', $params['order_id'])->first();
  1129. if ($order->order_status_payment == 'SUCCESS' && $appointment) {
  1130. $writeOffDate = OrderService::generateWriteOffData($params);
  1131. $applyData = OrderService::generateAppointmentApplyData($params);
  1132. $appointment->appointment_status = 'DONE';
  1133. $appointment->appointment_done_datetime = date('Y-m-d H:i:s');
  1134. $appointment->appointment_done_json = json_encode($writeOffDate);
  1135. if (empty($appointment->appointment_apply_datetime)) {
  1136. $appointment->appointment_apply_datetime = date('Y-m-d H:i:s');
  1137. }
  1138. if (empty($appointment->appointment_apply_json)) {
  1139. $appointment->appointment_apply_json = json_encode($applyData);
  1140. }
  1141. if (empty($appointment->appointment_datetime)) {
  1142. $appointment->appointment_datetime = date('Y-m-d');
  1143. }
  1144. $appointment->save();
  1145. }
  1146. // // 买的单个服务
  1147. if ($order->order_status_payment == 'SUCCESS' && empty($appointment)) {
  1148. foreach ($params['goodsContentList'] as $goods) {
  1149. $params['join_sheet_goods_id'] = $goods['goods_id'];
  1150. if (isset($goods['goods_classify']) && in_array($goods['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD'])) {
  1151. $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
  1152. $params['order_sheet_num'] = $goods['nbr'];
  1153. // 预约表
  1154. for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
  1155. $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
  1156. // 入预约记录
  1157. $this->insertAppointment($params, $writeOffDate, $applyData);
  1158. }
  1159. $goods['skuId'] = $goods['sku_id'];
  1160. $goods['category'] = $goods['goods_classify'];
  1161. // 权益表
  1162. $this->insertMemberBenefit($params, $goods);
  1163. } elseif (isset($goods['goods_classify']) && $goods['goods_classify'] == 'PACKAGE') { // 一个套餐买多个
  1164. $params['packageId'] = $goods['goods_id'];
  1165. $components = GoodsComponent::with([
  1166. 'goods' => function ($query) {
  1167. $query->select('goods_id', 'goods_name', 'goods_classify');
  1168. }
  1169. ])->where('join_component_master_goods_id', $params['packageId'])
  1170. ->get()
  1171. ->toArray();
  1172. foreach ($components as $component) {
  1173. $componentJson = json_decode($component['goods_component_json'], true);
  1174. $params['join_sheet_goods_sku_id'] = $componentJson['sku_id'];
  1175. $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
  1176. $params['order_sheet_num'] = $goods['nbr'] * $componentJson['nbr'];
  1177. for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
  1178. $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
  1179. // 入预约记录
  1180. $this->insertAppointment($params, $writeOffDate);
  1181. }
  1182. $goods['goods_id'] = $component['join_component_goods_id'];
  1183. $goods['goods_name'] = $component['goods']['goods_name'];
  1184. $goods['goods_classify'] = $component['goods']['goods_classify'];
  1185. $goods['skuId'] = $goods['sku_id'];
  1186. $goods['category'] = 'SERVICE';
  1187. // 权益表
  1188. $this->insertMemberBenefit($params, $goods);
  1189. }
  1190. }
  1191. }
  1192. }
  1193. // 2.4W 康养城
  1194. if ($params['goods_classify'] == 'VIP' && $order->order_status_payment == 'SUCCESS') {
  1195. $params['member_id'] = $params['join_order_member_id'];
  1196. Event::dispatch('order.kangyangCityVIP.grant', $params);
  1197. }
  1198. Db::commit();
  1199. // 会员升级
  1200. if ($order->order_is_complete == 'Y' && $order->order_status_payment == 'SUCCESS') {
  1201. Event::dispatch('order.complete', $params);
  1202. Event::dispatch('order_pay.member_level.up', $params['join_order_member_id']);
  1203. }
  1204. // 打小票
  1205. if (!empty($premises) && $params['goods_classify'] == 'MEALS') {
  1206. dump("pay 打小票");
  1207. $restaurant = SysDept::where('dept_super_id', $premises->dept_id)->where('dept_category', '餐厅')->first();
  1208. if (!empty($restaurant->dept_extend_json)) {
  1209. $deptExtendJson = json_decode($restaurant->dept_extend_json, true);
  1210. if (isset($deptExtendJson['printer'])) {
  1211. foreach ($deptExtendJson['printer'] as $key => $item) {
  1212. if (strpos($key, '结算') !== false && $order->order_status_payment == 'SUCCESS') {
  1213. $voteData = [
  1214. 'func' => 'procActionToPrinter',
  1215. 'sign' => '',
  1216. 'data' => [
  1217. 'printer_premises' => $restaurant->dept_id,
  1218. 'printer_device' => [
  1219. $key
  1220. ],
  1221. 'printer_action' => 'ExecPrintOrder',
  1222. 'printer_data' => [
  1223. 'order_id' => $params['order_id']
  1224. ]
  1225. ]
  1226. ];
  1227. http_post_json(getenv('VOTE_MENU_URL'), $voteData);
  1228. }
  1229. }
  1230. }
  1231. }
  1232. }
  1233. if ($order->order_status_payment != 'SUCCESS') {
  1234. _syslog("订单", "支付异常,检查是否有轮询");
  1235. return json_throw(2001, '支付异常', ['order_id' => $params['orderId']]);
  1236. }
  1237. _syslog("订单", "订单支付成功");
  1238. return json_success('支付成功');
  1239. } catch (BusinessException $e) {
  1240. dump($e->getMessage());
  1241. Db::rollBack();
  1242. _syslog("订单", "订单支付失败:" . $e->getMessage());
  1243. return json_fail("支付失败:" . $e->getMessage());
  1244. } catch (\Exception $e) {
  1245. dump($e->getMessage());
  1246. Db::rollBack();
  1247. _syslog("订单", "订单支付失败");
  1248. return json_fail('支付失败');
  1249. }
  1250. }
  1251. private function discountRecord($orderDiscountJson, $params)
  1252. {
  1253. $json = [];
  1254. if (!empty($orderDiscountJson)) {
  1255. $json = json_decode($orderDiscountJson, true);
  1256. }
  1257. try {
  1258. if (!empty($params['preferential']) && in_array('wipe', $params['preferential'])) {
  1259. if (intval($params['order_amount_total'] / 10) * 10 != $params['order_amount_pay']) {
  1260. throw new BusinessException("抹零后实际支付金额错误");
  1261. }
  1262. $params['order_discount_amount'] = $params['order_amount_total'] - $params['order_amount_pay'];
  1263. $couponClassifyDesc = $couponClassify = '抹零';
  1264. } elseif (!empty($params['preferential']) && in_array('custom', $params['preferential'])) {
  1265. if (sprintf("%.2f", $params['order_amount_total'] - $params['order_discount_amount']) != sprintf("%.2f", $params['order_amount_pay'])) {
  1266. throw new BusinessException("餐厅前台优惠后实际支付金额错误");
  1267. }
  1268. $couponClassifyDesc = $couponClassify = '餐厅前台优惠';
  1269. } else if (!empty($params['preferential']) && intval($params['preferential'][0]) < 100 && intval($params['preferential'][0]) >= 50) {
  1270. if (($params['order_amount_total'] * intval($params['preferential'][0])) / 100 != $params['order_amount_pay']) {
  1271. throw new BusinessException("折扣后实际支付金额错误");
  1272. }
  1273. $couponClassify = '折扣';
  1274. $couponClassifyDesc = intval($params['preferential'][0]) / 10 . '折';
  1275. $params['order_discount_amount'] = $params['order_amount_total'] - $params['order_amount_pay'];
  1276. } else {
  1277. return $json;
  1278. }
  1279. $json[date('Y-m-d H:i:s')] = [
  1280. 'coupon_id' => $params['coupon_id'] ?? null,
  1281. 'coupon_value' => $params['order_discount_amount'] ?? '',
  1282. 'coupon_classify' => $couponClassify,
  1283. 'coupon_detail_id' => [$couponClassifyDesc],
  1284. 'coupon_classify_en' => $params['preferential']
  1285. ];
  1286. return $json;
  1287. } catch (BusinessException $e) {
  1288. throw new BusinessException($e->getMessage());
  1289. } catch (\Exception $e) {
  1290. dump($e->getMessage());
  1291. throw new BusinessException("优惠数据错误");
  1292. }
  1293. }
  1294. /**
  1295. * 组合支付
  1296. */
  1297. public function payConstitute(Request $request)
  1298. {
  1299. $params = $request->post();
  1300. // 余额、福利、储值卡 验证短信
  1301. 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']))) {
  1302. $code = $params['sms_code'];
  1303. if (!$code) {
  1304. return json_fail("验证码错误,请重新输入");
  1305. }
  1306. $member = Member::find($params['join_order_member_id']);
  1307. $mobile = $member->member_mobile;
  1308. $key = "SMS:CODE:ORDER_PAY:" . $mobile;
  1309. $redisCode = Redis::get($key);
  1310. if ($redisCode != $code && $code != '123456') {
  1311. return json_fail("验证码错误,请重新输入");
  1312. }
  1313. Redis::del($key);
  1314. }
  1315. // 验证线下付款密码
  1316. if (!empty($params['pay_category_constitute']) && in_array('OFFLINE', $params['pay_category_constitute']) && in_array('MONEY', $params['pay_category_constitute'])) {
  1317. $password = $params['offline_password'];
  1318. if ($password != '666888') {
  1319. return json_fail("密码错误,请重新输入");
  1320. }
  1321. }
  1322. $order = Order::where('order_id', $params['order_id'])->first();
  1323. if (!$order) {
  1324. return json_fail('订单异常');
  1325. }
  1326. if ($order->order_status_system != 'PAYING') {
  1327. return json_fail('订单不是可支付状态');
  1328. }
  1329. if (!empty($order->order_config_json)) {
  1330. $orderConfigJson = json_decode($order->order_config_json, true);
  1331. if (isset($orderConfigJson['premises'])) {
  1332. $premises = SysDept::where('dept_name', $orderConfigJson['premises'])->first();
  1333. if (!empty($premises)) {
  1334. $params['submit_premises_id'] = $premises->dept_id;
  1335. }
  1336. }
  1337. }
  1338. $params['orderId'] = $params['order_id'];
  1339. $params['orderGroupId'] = $order->order_groupby;
  1340. $goods = Goods::where('goods_id', $params['join_sheet_goods_id'])
  1341. ->select('goods_id', 'goods_name', 'goods_classify')
  1342. ->first();
  1343. if (!$goods) {
  1344. return json_fail('产品数据异常');
  1345. }
  1346. $goods = $goods->toArray();
  1347. $params['goods_classify'] = $goods['goods_classify'];
  1348. $systemStatus = 'SENDING'; // 待发货
  1349. // 立即结算
  1350. if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'VIP'])) {
  1351. $order->order_is_complete = 'Y';
  1352. $systemStatus = 'DONE';
  1353. }
  1354. if ($params['goods_classify'] == 'PACKAGE' && $params['delivery'] == 'ARRIVAL') {
  1355. $systemStatus = "WAITING";
  1356. }
  1357. $payDetail = PayDetail::where('join_pay_order_id', $order->order_groupby)->first();
  1358. Db::beginTransaction();
  1359. try {// 使用优惠券
  1360. $couponUseJson = [];
  1361. if (!empty($params['join_order_member_id']) && !empty($params['preferential'])) {
  1362. $couponResult = OrderService::payUseCoupon('pay', 'Y', $params['join_order_member_id'], $params['goodsContentList'], $params['preferential'], $params['order_amount_total']);
  1363. if (!empty($couponResult['pay_amount']) && $couponResult['pay_amount'] != $params['order_amount_pay']) {
  1364. throw new BusinessException("计算优惠后,实付金额错误!");
  1365. }
  1366. // 组装优惠券使用数据,存主表优惠里
  1367. if (!empty($couponResult['use_coupon_json'])) {
  1368. $couponUseJson = $couponResult['use_coupon_json'];
  1369. if (!empty($order->order_discount_json)) {
  1370. $orderDiscountJson = json_decode($order->order_discount_json, true);
  1371. if (!empty($orderDiscountJson)) {
  1372. $couponUseJson = json_encode(array_merge($orderDiscountJson, json_decode($couponUseJson, true)));
  1373. }
  1374. }
  1375. }
  1376. }
  1377. // 存储优惠信息
  1378. $order->order_discount_json = json_encode($this->discountRecord($couponUseJson, $params));
  1379. $orderAmountPay = $params['order_amount_pay'];
  1380. $constituteList = array_column($params['pay_category_constitute_list'], 'amount', 'category');// 验证金额
  1381. $constituteAmount = 0;
  1382. foreach ($params['pay_category_constitute_list'] as $item) {
  1383. $constituteAmount = $constituteAmount + $item['amount'];
  1384. }
  1385. if ($params['order_amount_pay'] != $constituteAmount) {
  1386. throw new BusinessException('组合支付金额与应付金额不一致');
  1387. }
  1388. if (!empty($params['pay_category_constitute']) && in_array('OFFLINE', $params['pay_category_constitute'])) { //线下付款
  1389. $order->order_status_system = $systemStatus;
  1390. $order->order_status_payment = 'SUCCESS';
  1391. $params['pay_category'] = $params['pay_category_sub'] ?? 'OFFLINE';
  1392. // 线下支付金额
  1393. if (isset($constituteList['OFFLINE'])) {
  1394. $params['order_amount_pay'] = $constituteList['OFFLINE'];
  1395. // 生成支付记录
  1396. OrderService::createPayConstituteDetail($params, $payDetail);
  1397. }
  1398. $params['order_amount_pay'] = $orderAmountPay;
  1399. }
  1400. if (!empty($params['pay_category_constitute']) && in_array('MONEY', $params['pay_category_constitute'])) { //现金付款
  1401. $order->order_status_system = $systemStatus;
  1402. $order->order_status_payment = 'SUCCESS';
  1403. $params['pay_category'] = 'MONEY';
  1404. // 线下支付金额
  1405. if (isset($constituteList['MONEY'])) {
  1406. $params['order_amount_pay'] = $constituteList['MONEY'];
  1407. // 生成支付记录
  1408. OrderService::createPayConstituteDetail($params, $payDetail);
  1409. }
  1410. $params['order_amount_pay'] = $orderAmountPay;
  1411. }
  1412. if (!empty($params['pay_category_constitute']) && in_array('CASH', $params['pay_category_constitute'])) { // 余额支付
  1413. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  1414. ->where('member_account_classify', 'CASH')
  1415. ->where('member_account_status', 'ACTIVED')
  1416. ->first();
  1417. if (!$account) {
  1418. throw new BusinessException('账户异常');
  1419. }
  1420. if (isset($constituteList['CASH'])) {
  1421. $params['order_amount_pay'] = $constituteList['CASH'];
  1422. $params['pay_category'] = $params['join_order_member_id'] . '-CASH';
  1423. }
  1424. $amount = $account->member_account_surplus + $account->member_account_added;
  1425. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  1426. throw new BusinessException('账户余额不足');
  1427. }
  1428. if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
  1429. $qrcodePayAmount = $params['order_amount_pay'] - $amount;
  1430. $params['order_amount_pay'] = $amount;
  1431. }
  1432. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  1433. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  1434. $account->member_account_surplus = 0;
  1435. $account->member_account_added = $cut;
  1436. } else {
  1437. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  1438. }
  1439. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  1440. $account->save();
  1441. // 生成支付记录
  1442. OrderService::createPayConstituteDetail($params, $payDetail);
  1443. $params['order_amount_pay'] = $orderAmountPay;
  1444. $order->order_status_system = $systemStatus;
  1445. $order->order_status_payment = 'SUCCESS';
  1446. }
  1447. if (!empty($params['pay_category_constitute']) && in_array('CARD', $params['pay_category_constitute'])) { // 储值卡账户
  1448. $cardNbr = $params['card_nbr'];
  1449. if (!$cardNbr) {
  1450. throw new BusinessException('账户异常');
  1451. }
  1452. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  1453. ->where('member_account_nbr', $cardNbr)
  1454. ->where('member_account_status', 'ACTIVED')
  1455. ->first();
  1456. if (!$account) {
  1457. Db::rollBack();
  1458. return json_fail('账户异常');
  1459. }
  1460. // 储值卡账户支付金额
  1461. if (isset($constituteList['CARD'])) {
  1462. $params['order_amount_pay'] = $constituteList['CARD'];
  1463. $params['pay_category'] = $cardNbr;
  1464. }
  1465. $amount = $account->member_account_surplus + $account->member_account_added;
  1466. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  1467. throw new BusinessException('账户余额不足');
  1468. }
  1469. if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
  1470. $qrcodePayAmount = $params['order_amount_pay'] - $amount;
  1471. $params['order_amount_pay'] = $amount;
  1472. }
  1473. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  1474. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  1475. $account->member_account_surplus = 0;
  1476. $account->member_account_added = $cut;
  1477. } else {
  1478. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  1479. }
  1480. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  1481. $account->save();
  1482. // 生成支付记录
  1483. OrderService::createPayConstituteDetail($params, $payDetail);
  1484. $params['order_amount_pay'] = $orderAmountPay;
  1485. $order->order_status_system = $systemStatus;
  1486. $order->order_status_payment = 'SUCCESS';
  1487. }
  1488. if (!empty($params['pay_category_constitute']) && in_array('QRCODE', $params['pay_category_constitute']) && !empty($params['qrcode_nbr'])) { // 付款码
  1489. if (isset($constituteList['QRCODE']) && $constituteList['QRCODE'] > 0) {
  1490. // 付款码支付金额
  1491. $params['order_amount_pay'] = $constituteList['QRCODE'];
  1492. // 调支付
  1493. $result = OrderService::qrcodePay($params);
  1494. $result = json_encode($result);
  1495. $params['pay_json_response'] = $result;
  1496. $result = json_decode($result, true);
  1497. $prefix = substr($params['qrcode_nbr'], 0, 2);
  1498. if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
  1499. $params['pay_category'] = 'WXPAY';
  1500. 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')) {
  1501. $order->order_status_system = 'PAYING';
  1502. $order->order_status_payment = 'PENDING';
  1503. $order->order_is_complete = 'N';
  1504. // Db::rollBack();
  1505. // return json_fail('支付失败');
  1506. } else {
  1507. $order->order_status_system = $systemStatus;
  1508. $order->order_status_payment = 'SUCCESS';
  1509. }
  1510. } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
  1511. $params['pay_category'] = 'ALIPAY';
  1512. if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {
  1513. $order->order_status_system = 'PAYING';
  1514. $order->order_status_payment = 'PENDING';
  1515. $order->order_is_complete = 'N';
  1516. // Db::rollBack();
  1517. // return json_fail('支付失败');
  1518. } else {
  1519. $order->order_status_system = $systemStatus;
  1520. $order->order_status_payment = 'SUCCESS';
  1521. }
  1522. } else {
  1523. throw new BusinessException('付款码无效');
  1524. }
  1525. }
  1526. // 生成支付记录
  1527. OrderService::createPayConstituteDetail($params, $payDetail);
  1528. // 账户支付的金额
  1529. $params['order_amount_pay'] = $orderAmountPay;
  1530. }
  1531. $orderConfigJson = [];
  1532. if (!empty($order->order_config_json)) {
  1533. $orderConfigJson = json_decode($order->order_config_json, true);
  1534. }
  1535. $orderConfigJson['preferential'] = $params['preferential'] ?? '';
  1536. if (isset($orderConfigJson['tableid']) && !empty($orderConfigJson['tableid'])) {
  1537. SysDept::where('dept_id', $orderConfigJson['tableid'])->where('dept_category', '桌台')->update(['dept_status' => 'ACTIVED']);
  1538. }
  1539. $order->order_config_json = json_encode($orderConfigJson);
  1540. $order->order_amount_pay = $params['order_amount_pay'];
  1541. // 主订单
  1542. $order->save();
  1543. // sheet
  1544. if ($order->order_status_payment == 'SUCCESS') {
  1545. OrderSheet::where('join_sheet_order_id', $params['order_id'])->update([
  1546. 'order_sheet_status' => $systemStatus,
  1547. ]);
  1548. }
  1549. // 清除paydetail 中的未支付记录
  1550. PayDetail::where('join_pay_order_id', $params['orderGroupId'])->where('pay_status', '<>', 'SUCCESS')->delete();
  1551. $writeOffDate = [];
  1552. $applyData = [];
  1553. // 有预约单,状态已完成
  1554. $appointment = Appointment::where('join_appointment_order_id', $params['order_id'])->first();
  1555. if ($order->order_status_payment == 'SUCCESS' && $appointment) {
  1556. $writeOffDate = OrderService::generateWriteOffData($params);
  1557. $applyData = OrderService::generateAppointmentApplyData($params);
  1558. $appointment->appointment_status = 'DONE';
  1559. $appointment->appointment_done_datetime = date('Y-m-d H:i:s');
  1560. $appointment->appointment_done_json = json_encode($writeOffDate);
  1561. if (empty($appointment->appointment_apply_datetime)) {
  1562. $appointment->appointment_apply_datetime = date('Y-m-d H:i:s');
  1563. }
  1564. if (empty($appointment->appointment_apply_json)) {
  1565. $appointment->appointment_apply_json = json_encode($applyData);
  1566. }
  1567. if (empty($appointment->appointment_datetime)) {
  1568. $appointment->appointment_datetime = date('Y-m-d');
  1569. }
  1570. $appointment->save();
  1571. }
  1572. // 买单个服务
  1573. if ($order->order_status_payment == 'SUCCESS' && empty($appointment)) {
  1574. foreach ($params['goodsContentList'] as $goods) {
  1575. $params['join_sheet_goods_id'] = $goods['goods_id'];
  1576. if (isset($goods['goods_classify']) && in_array($goods['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD'])) {
  1577. $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
  1578. $params['order_sheet_num'] = $goods['nbr'];
  1579. // 预约表
  1580. for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
  1581. $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
  1582. // 入预约记录
  1583. $this->insertAppointment($params, $writeOffDate, $applyData);
  1584. }
  1585. $goods['skuId'] = $goods['sku_id'];
  1586. $goods['category'] = $goods['goods_classify'];
  1587. // 权益表
  1588. $this->insertMemberBenefit($params, $goods);
  1589. } elseif (isset($goods['goods_classify']) && $goods['goods_classify'] == 'PACKAGE') { // 一个套餐买多个
  1590. $params['packageId'] = $goods['goods_id'];
  1591. $components = GoodsComponent::with([
  1592. 'goods' => function ($query) {
  1593. $query->select('goods_id', 'goods_name', 'goods_classify');
  1594. }
  1595. ])->where('join_component_master_goods_id', $params['packageId'])
  1596. ->get()
  1597. ->toArray();
  1598. foreach ($components as $component) {
  1599. $componentJson = json_decode($component['goods_component_json'], true);
  1600. $params['join_sheet_goods_sku_id'] = $componentJson['sku_id'];
  1601. $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
  1602. $params['order_sheet_num'] = $goods['nbr'] * $componentJson['nbr'];
  1603. for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
  1604. $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
  1605. // 入预约记录
  1606. $this->insertAppointment($params, $writeOffDate);
  1607. }
  1608. $goods['goods_id'] = $component['join_component_goods_id'];
  1609. $goods['goods_name'] = $component['goods']['goods_name'];
  1610. $goods['goods_classify'] = $component['goods']['goods_classify'];
  1611. $goods['skuId'] = $goods['sku_id'];
  1612. $goods['category'] = 'SERVICE';
  1613. // 权益表
  1614. $this->insertMemberBenefit($params, $goods);
  1615. }
  1616. }
  1617. }
  1618. }
  1619. // 2.4W 康养城
  1620. if ($params['goods_classify'] == 'VIP' && $order->order_status_payment == 'SUCCESS') {
  1621. $params['member_id'] = $params['join_order_member_id'];
  1622. Event::dispatch('order.kangyangCityVIP.grant', $params);
  1623. }
  1624. Db::commit();
  1625. // 会员升级
  1626. if ($order->order_is_complete == 'Y' && $order->order_status_payment == 'SUCCESS') {
  1627. Event::dispatch('order.complete', $params);
  1628. Event::dispatch('order_pay.member_level.up', $params['join_order_member_id']);
  1629. }
  1630. // 打小票
  1631. if (!empty($premises) && $params['goods_classify'] == "MEALS") {
  1632. dump('payCons 打小票');
  1633. $restaurant = SysDept::where('dept_super_id', $premises->dept_id)->where('dept_category', '餐厅')->first();
  1634. if (!empty($restaurant->dept_extend_json)) {
  1635. $deptExtendJson = json_decode($restaurant->dept_extend_json, true);
  1636. if (isset($deptExtendJson['printer'])) {
  1637. foreach ($deptExtendJson['printer'] as $key => $item) {
  1638. if (strpos($key, '结算') !== false && $order->order_status_payment == 'SUCCESS') {
  1639. $voteData = [
  1640. 'func' => 'procActionToPrinter',
  1641. 'sign' => '',
  1642. 'data' => [
  1643. 'printer_premises' => $restaurant->dept_id,
  1644. 'printer_device' => [
  1645. $key
  1646. ],
  1647. 'printer_action' => 'ExecPrintOrder',
  1648. 'printer_data' => [
  1649. 'order_id' => $params['order_id']
  1650. ]
  1651. ]
  1652. ];
  1653. http_post_json(getenv('VOTE_MENU_URL'), $voteData);
  1654. }
  1655. }
  1656. }
  1657. }
  1658. }
  1659. if ($order->order_status_payment != 'SUCCESS') {
  1660. _syslog("订单", "支付异常,检查是否有轮询");
  1661. return json_throw(2001, '支付异常', ['order_id' => $params['orderId']]);
  1662. }
  1663. _syslog("订单", "订单支付成功");
  1664. return json_success('支付成功');
  1665. } catch (\Exception $e) {
  1666. dump($e->getMessage());
  1667. Db::rollBack();
  1668. _syslog("订单", "订单支付失败");
  1669. return json_fail('支付失败');
  1670. }
  1671. }
  1672. /**
  1673. * 删除订单
  1674. */
  1675. public function delete(Request $request): Response
  1676. {
  1677. $params = $request->post();
  1678. Db::beginTransaction();
  1679. try {
  1680. $order = Order::where('order_id', $params['order_id'])
  1681. ->where('order_status_system', 'CANCEL')
  1682. ->orWhere(function ($query) use ($params) {
  1683. $query->whereIn('order_status_system', ['WAITING', 'SENDING'])->where('order_category', 'SYSTEM')->where('order_id', $params['order_id']);
  1684. })
  1685. ->first();
  1686. if (!$order) {
  1687. return json_fail('此订单不允许删除');
  1688. }
  1689. $payDetail = PayDetail::where('join_pay_order_id', $order->order_groupby)->first();
  1690. if ($payDetail) {
  1691. $payType = explode('-', $payDetail->pay_prepayid);
  1692. // 余额支付
  1693. if (isset($payType[1]) && $payType[1] == 'CASH') {
  1694. $memberAccount = MemberAccount::where('join_account_member_id', $payDetail->join_pay_member_id)
  1695. ->where('member_account_classify', 'CASH')
  1696. ->first();
  1697. $memberAccount->member_account_expend = $memberAccount->member_account_expend - $payDetail->pay_amount;
  1698. $memberAccount->member_account_surplus = $memberAccount->member_account_surplus + $payDetail->pay_amount;
  1699. $memberAccount->save();
  1700. }
  1701. // 员工福利支付
  1702. if (isset($payType[1]) && $payType[1] == 'WELFARE') {
  1703. $memberAccount = MemberAccount::where('join_account_member_id', $payDetail->join_pay_member_id)
  1704. ->where('member_account_classify', 'WELFARE')
  1705. ->first();
  1706. $memberAccount->member_account_expend = $memberAccount->member_account_expend - $payDetail->pay_amount;
  1707. $memberAccount->member_account_surplus = $memberAccount->member_account_surplus + $payDetail->pay_amount;
  1708. $memberAccount->save();
  1709. }
  1710. // 删支付记录
  1711. $payDetail->delete();
  1712. }
  1713. // 删收货信息
  1714. OrderExpress::where('join_express_order_id', $params['order_id'])->delete();
  1715. // 删订单详情
  1716. OrderSheet::where('join_sheet_order_id', $params['order_id'])->delete();
  1717. // 删主订单
  1718. Order::where('order_id', $params['order_id'])->delete();
  1719. Db::commit();
  1720. _syslog("订单", "删除订单成功");
  1721. return json_success('删除订单成功');
  1722. } catch (\Exception $e) {
  1723. dump($e->getMessage());
  1724. Db::rollBack();
  1725. _syslog("订单", "删除订单失败");
  1726. return json_fail('删除订单失败');
  1727. }
  1728. }
  1729. /**
  1730. * 取消订单
  1731. */
  1732. public function cancelOrder(Request $request)
  1733. {
  1734. $orderId = $request->post('order_id', '');
  1735. if (!$orderId) {
  1736. return json_fail('参数异常');
  1737. }
  1738. Db::beginTransaction();
  1739. try {
  1740. $order = Order::where('order_id', $orderId)->first();
  1741. if (empty($order)) {
  1742. return json_fail('订单数据异常');
  1743. }
  1744. if ($order->order_status_system != 'PAYING' || $order->order_category != 'DISHES') {
  1745. return json_fail('仅未支付的餐饮订单可以取消!');
  1746. }
  1747. if (!empty($order->order_discount_json)) {
  1748. $orderDiscountJson = json_decode($order->order_discount_json, true);
  1749. foreach ($orderDiscountJson as $discount) {
  1750. if (!empty($discount['coupon_id']) && !empty($discount['coupon_detail_id'])) {
  1751. foreach ($discount['coupon_detail_id'] as $detailId) {
  1752. if (substr($detailId, 0, 4) == 'CUDT') {
  1753. // 恢复优惠券
  1754. CouponDetail::where('coupon_detail_id', $detailId)->update(['coupon_detail_status' => 'ACTIVED']);
  1755. }
  1756. }
  1757. }
  1758. }
  1759. }
  1760. // sheet 表
  1761. OrderSheet::where('join_sheet_order_id', $orderId)->update(['order_sheet_status' => 'CANCEL']);
  1762. // payDetail 表
  1763. PayDetail::where('join_pay_order_id', $order->order_groupby)->update([
  1764. 'pay_status' => 'CANCEL',
  1765. 'pay_extend_json' => json_encode(['cancel_times' => date('Y-m-d H:i:s')])
  1766. ]);
  1767. if (!empty($order->order_config_json)) {
  1768. $orderConfigJson = json_decode($order->order_config_json, true);
  1769. if (isset($orderConfigJson['tableid']) && !empty($orderConfigJson['tableid'])) {
  1770. SysDept::where('dept_id', $orderConfigJson['tableid'])->update(['dept_status' => 'ACTIVED']);
  1771. }
  1772. }
  1773. // 主表存取消时间吧
  1774. $orderExtendJson = [];
  1775. if (!empty($order->order_extend_json)) {
  1776. $orderExtendJson = json_decode($order->order_extend_json, true);
  1777. }
  1778. $orderExtendJson['cancel_times'] = date('Y-m-d H:i:s');
  1779. $order->order_extend_json = json_encode($orderExtendJson, JSON_UNESCAPED_UNICODE);
  1780. $order->order_is_complete = 'Y';
  1781. $order->order_status_system = 'CANCEL';
  1782. $order->order_status_payment = 'CANCEL';
  1783. $order->save();
  1784. Db::commit();
  1785. return json_success('');
  1786. } catch (\Exception $e) {
  1787. Db::rollBack();
  1788. return json_fail('订单取消失败');
  1789. }
  1790. }
  1791. public function insert(Request $request): Response
  1792. {
  1793. $params = $request->post();
  1794. // 判断餐品是否连带着服务或实体
  1795. $goodsClassifys = array_unique(array_column($params['goodsContentList'], 'goods_classify'));
  1796. if (in_array('MEALS', $goodsClassifys) && count($goodsClassifys) > 1) {
  1797. return json_fail('餐饮餐品不支持和其他类型的产品一起下单');
  1798. }
  1799. if (in_array('MEALS', $goodsClassifys)) {
  1800. $params['submit_goods_classify'] = 'MEALS';
  1801. }
  1802. if (in_array('PACKAGE', $goodsClassifys)) {
  1803. $params['submit_goods_classify'] = 'PACKAGE';
  1804. }
  1805. if (!empty($params['dept_premises_id'])) {
  1806. $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();
  1807. }
  1808. $params['goods_classify'] = $goodsClassifys[0];
  1809. Db::beginTransaction();
  1810. try {
  1811. // 使用优惠券
  1812. $couponUseJson = [];
  1813. if (!empty($params['join_order_member_id']) && !empty($params['preferential'])) {
  1814. $couponResult = OrderService::payUseCoupon('insert', $params['settlement_now'], $params['join_order_member_id'], $params['goodsContentList'], $params['preferential'], $params['order_amount_total']);
  1815. if (!empty($couponResult['pay_amount']) && $couponResult['pay_amount'] != $params['order_amount_pay']) {
  1816. throw new BusinessException("计算优惠后,实付金额错误!");
  1817. }
  1818. // 组装优惠券使用数据,存主表优惠里
  1819. if (!empty($couponResult['use_coupon_json'])) {
  1820. $couponUseJson = $couponResult['use_coupon_json'];
  1821. }
  1822. }
  1823. // 存储优惠信息
  1824. $params['order_discount_json'] = json_encode($this->discountRecord($couponUseJson, $params));
  1825. // 验证库存
  1826. foreach ($params['goodsContentList'] as $goods) {
  1827. // 减库存,规格和总库存
  1828. if (!isset($params['submit_goods_classify']) || !in_array($params['submit_goods_classify'], ['MEALS', 'PACKAGE'])) {
  1829. $goodsSku = GoodsSku::where('goods_sku_id', $goods['sku_id'])->first();
  1830. $skuStorageJson = json_decode($goodsSku->goods_sku_storage_json, true);
  1831. if (isset($skuStorageJson['storage']) && !empty($skuStorageJson['storage'])) {
  1832. $skuStorageJson['storage'] = $skuStorageJson['storage'] - $goods['nbr'];
  1833. }
  1834. if (!isset($skuStorageJson['storage']) || (!empty($skuStorageJson['storage']) && $skuStorageJson['storage'] < 0)) {
  1835. throw new BusinessException('库存不足');
  1836. }
  1837. }
  1838. $goodsRunning = GoodsRunning::where('join_running_goods_id', $goods['goods_id'])->first();
  1839. $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $goods['nbr'];
  1840. if ($goodsRunning->goods_running_storage < 0) {
  1841. throw new BusinessException('库存不足');
  1842. }
  1843. }
  1844. // 余额、福利、储值卡 验证短信
  1845. if ($params['settlement_now'] == 'Y' && $params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['CASH', 'CARD', 'WELFARE', 'VIP'])) {
  1846. $code = $params['sms_code'];
  1847. if (!$code) {
  1848. throw new BusinessException('验证码错误,请重新输入');
  1849. }
  1850. $member = Member::find($params['join_order_member_id']);
  1851. $mobile = $member->member_mobile;
  1852. $key = "SMS:CODE:ORDER_PAY:" . $mobile;
  1853. $redisCode = Redis::get($key);
  1854. if ($redisCode != $code && $code != '123456') {
  1855. throw new BusinessException('验证码错误,请重新输入');
  1856. }
  1857. Redis::del($key);
  1858. }
  1859. // 验证线下付款密码
  1860. if ($params['settlement_now'] == 'Y' && $params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['OFFLINE', 'MONEY'])) {
  1861. $password = $params['offline_password'];
  1862. if ($password != '666888') {
  1863. throw new BusinessException('密码错误,请重新输入');
  1864. }
  1865. }
  1866. // 下单账户
  1867. if (empty($params['join_order_member_id']) && !empty($params['mobile'])) {
  1868. if (Member::where('member_mobile', $params['mobile'])->exists()) {
  1869. throw new BusinessException('会员已存在');
  1870. }
  1871. $params['join_order_member_id'] = $params['member_id'] = 'MR' . date('ymdHi') . random_string(4, 'up');
  1872. // 创建会员
  1873. MemberService::createMember($params);
  1874. } else if (empty($params['join_order_member_id']) && empty($params['mobile'])) {
  1875. $params['join_order_member_id'] = Member::where('member_mobile', '0000')->value('member_id');
  1876. }
  1877. if (empty($params['join_order_member_id'])) {
  1878. throw new BusinessException('检查下单账户');
  1879. }
  1880. $qrcodePayAmount = 0;
  1881. $params['orderId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
  1882. $params['orderGroupId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
  1883. $systemStatus = 'SENDING'; // 待发货
  1884. // 立即结算
  1885. if ($params['settlement_now'] == 'Y') {
  1886. if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'VIP'])) {
  1887. $params['order_is_complete'] = 'Y';
  1888. $systemStatus = 'DONE';
  1889. }
  1890. if ($params['goods_classify'] == 'PACKAGE' && $params['delivery'] == 'ARRIVAL') {
  1891. $systemStatus = "WAITING";
  1892. }
  1893. }
  1894. if ($params['settlement_now'] == 'Y' && ($params['pay_category'] == 'OFFLINE' || $params['pay_category'] == 'MONEY')) {
  1895. if ($params['pay_category'] == 'OFFLINE' && !empty($params['pay_category_sub'])) {
  1896. $params['pay_category'] = $params['pay_category_sub'];
  1897. }
  1898. $params['order_status_system'] = $systemStatus;
  1899. $params['order_status_payment'] = 'SUCCESS';
  1900. } else if ($params['settlement_now'] == 'Y' && $params['pay_category'] == 'CASH') { // 余额支付
  1901. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  1902. ->where('member_account_classify', 'CASH')
  1903. ->where('member_account_status', 'ACTIVED')
  1904. ->first();
  1905. if (!$account) {
  1906. throw new BusinessException('账户异常');
  1907. }
  1908. $amount = $account->member_account_surplus + $account->member_account_added;
  1909. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  1910. throw new BusinessException('账户余额不足');
  1911. }
  1912. if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
  1913. $qrcodePayAmount = $params['order_amount_pay'] - $amount;
  1914. $params['order_amount_pay'] = $amount;
  1915. }
  1916. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  1917. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  1918. $account->member_account_surplus = 0;
  1919. $account->member_account_added = $cut;
  1920. } else {
  1921. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  1922. }
  1923. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  1924. $account->save();
  1925. if ($params['pay_constitute'] == 'N') {
  1926. $params['order_status_system'] = $systemStatus;
  1927. $params['order_status_payment'] = 'SUCCESS';
  1928. }
  1929. } else if ($params['settlement_now'] == 'Y' && $params['pay_category'] == 'VIP') { // 余额支付
  1930. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  1931. ->where('member_account_classify', 'VIP')
  1932. ->where('member_account_status', 'ACTIVED')
  1933. ->first();
  1934. if (!$account) {
  1935. throw new BusinessException('账户异常');
  1936. }
  1937. $amount = $account->member_account_surplus + $account->member_account_added;
  1938. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  1939. throw new BusinessException('账户余额不足');
  1940. }
  1941. if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
  1942. $qrcodePayAmount = $params['order_amount_pay'] - $amount;
  1943. $params['order_amount_pay'] = $amount;
  1944. }
  1945. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  1946. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  1947. $account->member_account_surplus = 0;
  1948. $account->member_account_added = $cut;
  1949. } else {
  1950. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  1951. }
  1952. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  1953. $account->save();
  1954. if ($params['pay_constitute'] == 'N') {
  1955. $params['order_status_system'] = $systemStatus;
  1956. $params['order_status_payment'] = 'SUCCESS';
  1957. }
  1958. } else if ($params['settlement_now'] == 'Y' && $params['pay_category'] == 'WELFARE') { // 福利账户
  1959. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  1960. ->where('member_account_classify', 'WELFARE')
  1961. ->where('member_account_status', 'ACTIVED')
  1962. ->first();
  1963. if (!$account) {
  1964. throw new BusinessException('账户异常');
  1965. }
  1966. $account->member_account_surplus = floatval($account->member_account_surplus);
  1967. if ($params['pay_constitute'] == 'N' && ($params['order_amount_pay'] > $account->member_account_surplus)) {
  1968. throw new BusinessException('账户余额不足');
  1969. }
  1970. if ($params['pay_constitute'] == 'Y' && ($params['order_amount_pay'] > $account->member_account_surplus)) {
  1971. $qrcodePayAmount = $params['order_amount_pay'] - $account->member_account_surplus;
  1972. $params['order_amount_pay'] = $account->member_account_surplus;
  1973. }
  1974. if ($params['pay_constitute'] == 'N') {
  1975. $params['order_status_system'] = $systemStatus;
  1976. $params['order_status_payment'] = 'SUCCESS';
  1977. }
  1978. // 福利账户 300 、 700
  1979. if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS'])) {
  1980. $payDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  1981. ->where('pay_status', 'SUCCESS')
  1982. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  1983. ->whereIn('pay_category', ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'DESHES'])
  1984. ->get()
  1985. ->toArray();
  1986. $payDetailArray = array_column($payDetails, 'pay_amount', 'join_pay_order_id');
  1987. $refundPayDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  1988. ->where('pay_status', 'SUCCESS')
  1989. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  1990. ->where('pay_category', 'REFUND')
  1991. ->get()
  1992. ->toArray();
  1993. $refundPayDetailArray = array_column($refundPayDetails, 'pay_amount', 'join_pay_order_id');
  1994. $paySum = 0;
  1995. foreach ($payDetailArray as $key => $item) {
  1996. if (isset($refundPayDetailArray[$key])) {
  1997. $paySum = $paySum + ($item - $refundPayDetailArray[$key]);
  1998. continue;
  1999. }
  2000. $paySum = $paySum + $item;
  2001. }
  2002. if ($params['pay_constitute'] == 'N' && 700 - $paySum < $params['order_amount_pay']) {
  2003. Db::rollBack();
  2004. return json_fail('超出福利限额');
  2005. } else if ($params['pay_constitute'] == 'Y' && 700 - $paySum < $params['order_amount_pay']) {
  2006. $qrcodePayAmount = $params['order_amount_pay'] - (700 - $paySum);
  2007. $params['order_amount_pay'] = (700 - $paySum);
  2008. }
  2009. } else {
  2010. $payDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  2011. ->where('pay_status', 'SUCCESS')
  2012. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  2013. ->whereNotIn('pay_category', ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'DESHES', 'REFUND', 'RECHARGE'])
  2014. ->get()
  2015. ->toArray();
  2016. $payDetailArray = array_column($payDetails, 'pay_amount', 'join_pay_order_id');
  2017. $refundPayDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  2018. ->where('pay_status', 'SUCCESS')
  2019. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  2020. ->where('pay_category', 'REFUND')
  2021. ->get()
  2022. ->toArray();
  2023. $refundPayDetailArray = array_column($refundPayDetails, 'pay_amount', 'join_pay_order_id');
  2024. $paySum = 0;
  2025. foreach ($payDetailArray as $key => $item) {
  2026. if (isset($refundPayDetailArray[$key])) {
  2027. $paySum = $paySum + ($item - $refundPayDetailArray[$key]);
  2028. continue;
  2029. }
  2030. $paySum = $paySum + $item;
  2031. }
  2032. if ($params['pay_constitute'] == 'N' && 300 - $paySum < $params['order_amount_pay']) {
  2033. throw new BusinessException('超出福利限额');
  2034. } else if ($params['pay_constitute'] == 'Y' && 300 - $paySum < $params['order_amount_pay']) {
  2035. $qrcodePayAmount = $params['order_amount_pay'] - (300 - $paySum);
  2036. $params['order_amount_pay'] = (300 - $paySum);
  2037. }
  2038. }
  2039. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  2040. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  2041. $account->save();
  2042. } else if ($params['settlement_now'] == 'Y' && $params['pay_category'] == 'CARD') { // 储值卡账户
  2043. $cardNbr = $params['card_nbr'];
  2044. if (!$cardNbr) {
  2045. throw new BusinessException('账户异常');
  2046. }
  2047. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  2048. ->where('member_account_nbr', $cardNbr)
  2049. ->where('member_account_status', 'ACTIVED')
  2050. ->first();
  2051. if (!$account) {
  2052. throw new BusinessException('账户异常');
  2053. }
  2054. $amount = $account->member_account_surplus + $account->member_account_added;
  2055. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  2056. throw new BusinessException('账户余额不足');
  2057. }
  2058. if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
  2059. $qrcodePayAmount = $params['order_amount_pay'] - $amount;
  2060. $params['order_amount_pay'] = $amount;
  2061. }
  2062. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  2063. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  2064. $account->member_account_surplus = 0;
  2065. $account->member_account_added = $cut;
  2066. } else {
  2067. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  2068. }
  2069. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  2070. $account->save();
  2071. if ($params['pay_constitute'] == 'N') {
  2072. $params['order_status_system'] = $systemStatus;
  2073. $params['order_status_payment'] = 'SUCCESS';
  2074. }
  2075. }
  2076. if (($params['pay_constitute'] == 'Y' || $params['pay_category'] == 'QRCODE') && $params['settlement_now'] == 'Y' && !empty($params['qrcode_nbr'])) { // 付款码
  2077. // 提交过来的支付分类
  2078. $submitPayCategory = $params['pay_category'];
  2079. // 账户支付的金额
  2080. $accountAmount = $params['order_amount_pay'];
  2081. if ($params['pay_constitute'] == 'Y' && $qrcodePayAmount > 0) {
  2082. // 组合支付,支付金额改成需要付款码需要支付的金额
  2083. $params['order_amount_pay'] = $qrcodePayAmount;
  2084. }
  2085. if ($params['pay_constitute'] == 'Y' && $qrcodePayAmount <= 0) {
  2086. $params['order_status_system'] = $systemStatus;
  2087. $params['order_status_payment'] = 'SUCCESS';
  2088. }
  2089. // 不组合或者组合后需要付款码的金额>0
  2090. if ($params['pay_constitute'] == 'N' || ($params['pay_constitute'] == 'Y' && $qrcodePayAmount > 0)) {
  2091. $result = OrderService::qrcodePay($params);
  2092. $result = json_encode($result);
  2093. $params['pay_json_response'] = $result;
  2094. $result = json_decode($result, true);
  2095. $prefix = substr($params['qrcode_nbr'], 0, 2);
  2096. if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
  2097. $params['pay_category'] = 'WXPAY';
  2098. 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')) {
  2099. $params['order_status_system'] = 'PAYING';
  2100. $params['order_status_payment'] = 'PENDING';
  2101. $params['order_is_complete'] = 'N';
  2102. // Db::rollBack();
  2103. // return json_fail('支付失败');
  2104. } else {
  2105. $params['order_status_system'] = $systemStatus;
  2106. $params['order_status_payment'] = 'SUCCESS';
  2107. }
  2108. } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
  2109. $params['pay_category'] = 'ALIPAY';
  2110. if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {
  2111. $params['order_status_system'] = 'PAYING';
  2112. $params['order_status_payment'] = 'PENDING';
  2113. $params['order_is_complete'] = 'N';
  2114. // Db::rollBack();
  2115. // return json_fail('支付失败');
  2116. } else {
  2117. $params['order_status_system'] = $systemStatus;
  2118. $params['order_status_payment'] = 'SUCCESS';
  2119. }
  2120. } else {
  2121. throw new BusinessException('付款码无效');
  2122. }
  2123. // 组合支付,追加加一条支付记录 pay_detail
  2124. if ($params['pay_constitute'] == 'Y' && $qrcodePayAmount > 0 && $params['order_status_payment'] == 'SUCCESS') {
  2125. $insertPayDetailData = [
  2126. 'join_pay_member_id' => $params['join_order_member_id'],
  2127. 'join_pay_order_id' => $params['orderGroupId'],
  2128. 'pay_status' => 'SUCCESS',
  2129. 'pay_category' => $params['goods_classify'],
  2130. 'pay_amount' => $params['order_amount_pay'],
  2131. 'pay_paytimes' => date('Y-m-d H:i:s'),
  2132. 'pay_prepayid' => $params['pay_category'],
  2133. 'pay_json_request' => json_encode($params),
  2134. 'pay_json_response' => $params['pay_json_response'],
  2135. 'pay_addtimes' => time()
  2136. ];
  2137. PayDetail::insert($insertPayDetailData);
  2138. // 组合支付,还原提交的支付分类
  2139. $params['pay_category'] = $submitPayCategory;
  2140. }
  2141. // 账户支付的金额
  2142. $params['order_amount_pay'] = $accountAmount;
  2143. }
  2144. }
  2145. $orderConfigJson = [];
  2146. // 优惠
  2147. if (!empty($params['preferential'])) {
  2148. $orderConfigJson['preferential'] = $params['preferential'];
  2149. }
  2150. // 配送方式
  2151. if (isset($params['delivery']) && ($params['delivery'] == 'PICKUP' || $params['delivery'] == 'ARRIVAL')) { // 自提/ 到店
  2152. $orderConfigJson['premises'] = $params['dept_premises_id'];
  2153. } else if (isset($params['delivery']) && $params['delivery'] == 'LOGISTICS') {
  2154. // $params['order_express_json'] = json_encode([
  2155. // 'express' => 'Y',
  2156. // ]);
  2157. }
  2158. $params['order_amount_pay'] = $params['order_amount_pay'] + $qrcodePayAmount;
  2159. if (isset($params['delivery']) && in_array($params['delivery'], ['PICKUP', 'ARRIVAL']) && !empty($params['dept_premises_id'])) {
  2160. // $premises = SysDept::where('dept_name',$params['dept_premises_id'])->where('dept_category','营业场所')->first();
  2161. if (!$premises) {
  2162. throw new BusinessException('门店不存在,请重新选择');
  2163. }
  2164. $params['submit_premises_id'] = $premises->dept_id;
  2165. }
  2166. if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS' && !empty($params['dept_premises_id'])) {
  2167. $table = '';
  2168. if (!empty($params['dept_table_id'])) {
  2169. $table = SysDept::where('dept_id', $params['dept_table_id'])->where('dept_category', '桌台')->first();
  2170. }
  2171. $orderConfigJson['premises'] = $params['dept_premises_id'];
  2172. $orderConfigJson['dept'] = $premises->dept_id ?? 0;
  2173. $orderConfigJson['reach'] = "00:00";
  2174. $orderConfigJson['table'] = !empty($table) ? $table->dept_name : null;
  2175. $orderConfigJson['express'] = "到店吃";
  2176. $orderConfigJson['tableid'] = $params['dept_table_id'] ?? null;
  2177. if (!empty($params['eat'])) {
  2178. $orderConfigJson['eat'] = $params['eat'] ?? null;
  2179. }
  2180. if ($params['settlement_now'] == 'N' && !empty($params['dept_table_id'])) {
  2181. // 桌台设为使用中
  2182. SysDept::where('dept_id', $params['dept_table_id'])->where('dept_category', '桌台')->update(['dept_status' => 'USING']);
  2183. }
  2184. }
  2185. $params['order_config_json'] = json_encode($orderConfigJson);
  2186. // 写入主订单
  2187. $this->insertMain($params);
  2188. // 订单详情
  2189. $sheetId = $this->insertSheet($params);
  2190. // 支付记录
  2191. $params['order_amount_pay'] = $params['order_amount_pay'] - $qrcodePayAmount;
  2192. $this->insertPayDetail($params);
  2193. $params['order_express_goods'] = json_encode(['sheet' => [$sheetId]]);
  2194. if (isset($params['delivery']) && $params['delivery'] == 'LOGISTICS') {
  2195. $params['order_express_type'] = '配送';
  2196. // 入配送
  2197. $this->saveExpress($params);
  2198. } else if (isset($params['delivery']) && $params['delivery'] == 'PICKUP') {
  2199. $params['order_express_type'] = '自提';
  2200. if (!$premises) {
  2201. throw new BusinessException('自提门店不存在');
  2202. }
  2203. $params['order_express_city'] = $premises->dept_city;
  2204. $params['order_express_address'] = $premises->dept_address;
  2205. $params['order_express_telephone'] = $premises->dept_telephone;
  2206. $params['order_express_extend_json'] = json_encode(['pick_code' => random_string(4, 'number')]);
  2207. $this->saveExpress($params);
  2208. } else if (isset($params['delivery']) && $params['delivery'] == 'ARRIVAL') {
  2209. $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();
  2210. $params['order_express_type'] = '到店';
  2211. if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
  2212. $params['order_express_type'] = '堂食';
  2213. }
  2214. if (!$premises) {
  2215. throw new BusinessException('门店不存在');
  2216. }
  2217. $params['order_express_city'] = $premises->dept_city;
  2218. $params['order_express_address'] = $premises->dept_address;
  2219. $params['order_express_telephone'] = $premises->dept_telephone;
  2220. $this->saveExpress($params);
  2221. }
  2222. // 买的单个服务
  2223. $writeOffDate = [];
  2224. $applyData = [];
  2225. // 服务已完成,生成核销数据
  2226. // if ($params['order_status_payment'] == 'SUCCESS' && in_array($goods['goods_classify'], ['SERVICE','CHNMED','CHNNCD', 'PACKAGE'])) {
  2227. // $writeOffDate = OrderService::generateWriteOffData($params);
  2228. // $applyData = OrderService::generateAppointmentApplyData($params);
  2229. // }
  2230. if ($params['order_status_payment'] == 'SUCCESS') {
  2231. foreach ($params['goodsContentList'] as $goods) {
  2232. $params['join_sheet_goods_id'] = $goods['goods_id'];
  2233. if (isset($goods['goods_classify']) && in_array($goods['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD'])) {
  2234. $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
  2235. $params['join_sheet_goods_sku_id'] = $goods['sku_id'];
  2236. $params['goods_id'] = $goods['goods_id'];
  2237. $params['order_sheet_num'] = $goods['nbr'];
  2238. // 预约表
  2239. for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
  2240. $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
  2241. // 入预约记录
  2242. $this->insertAppointment($params, $writeOffDate, $applyData);
  2243. }
  2244. $goods['skuId'] = $goods['sku_id'];
  2245. $goods['category'] = $goods['goods_classify'];
  2246. // 权益表
  2247. $this->insertMemberBenefit($params, $goods);
  2248. } elseif (isset($goods['goods_classify']) && $goods['goods_classify'] == 'PACKAGE') { // 一个套餐买多个
  2249. $params['packageId'] = $goods['goods_id'];
  2250. $components = GoodsComponent::with([
  2251. 'goods' => function ($query) {
  2252. $query->select('goods_id', 'goods_name', 'goods_classify');
  2253. }
  2254. ])->where('join_component_master_goods_id', $params['packageId'])
  2255. ->get()
  2256. ->toArray();
  2257. foreach ($components as $component) {
  2258. $componentJson = json_decode($component['goods_component_json'], true);
  2259. $params['join_sheet_goods_sku_id'] = $componentJson['sku_id'];
  2260. $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
  2261. $params['order_sheet_num'] = $goods['nbr'] * $componentJson['nbr'];
  2262. for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
  2263. $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
  2264. // 入预约记录
  2265. $this->insertAppointment($params, $writeOffDate);
  2266. }
  2267. $goods['goods_id'] = $component['join_component_goods_id'];
  2268. $goods['goods_name'] = $component['goods']['goods_name'];
  2269. $goods['goods_classify'] = $component['goods']['goods_classify'];
  2270. $goods['skuId'] = $goods['sku_id'];
  2271. $goods['category'] = 'SERVICE';
  2272. // 权益表
  2273. $this->insertMemberBenefit($params, $goods);
  2274. }
  2275. }
  2276. }
  2277. }
  2278. // 2.4W 康养城
  2279. if ($params['goods_classify'] == 'VIP' && $params['order_status_payment'] == 'SUCCESS') {
  2280. $params['member_id'] = $params['join_order_member_id'];
  2281. Event::dispatch('order.kangyangCityVIP.grant', $params);
  2282. }
  2283. Db::commit();
  2284. // 会员升级
  2285. if (!empty($params['order_is_complete']) && $params['order_is_complete'] == 'Y' && $params['order_status_payment'] == 'SUCCESS') {
  2286. Event::dispatch('order.complete', $params);
  2287. Event::dispatch('order_pay.member_level.up', $params['join_order_member_id']);
  2288. }
  2289. // 打小票
  2290. if (!empty($premises) && isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
  2291. dump("insert 打小票");
  2292. if ($premises->dept_category != '餐厅') {
  2293. $restaurant = SysDept::where('dept_super_id', $premises->dept_id)->where('dept_category', '餐厅')->first();
  2294. } else {
  2295. $restaurant = $premises;
  2296. }
  2297. if (!empty($restaurant->dept_extend_json)) {
  2298. $deptExtendJson = json_decode($restaurant->dept_extend_json, true);
  2299. if (isset($deptExtendJson['printer'])) {
  2300. foreach ($deptExtendJson['printer'] as $key => $item) {
  2301. if (strpos($key, '结算') !== false && $params['order_status_payment'] == 'SUCCESS') {
  2302. $voteData = [
  2303. 'func' => 'procActionToPrinter',
  2304. 'sign' => '',
  2305. 'data' => [
  2306. 'printer_premises' => $restaurant->dept_id,
  2307. 'printer_device' => [
  2308. $key
  2309. ],
  2310. 'printer_action' => 'ExecPrintOrder',
  2311. 'printer_data' => [
  2312. 'order_id' => $params['orderId'],
  2313. 'order_batch' => ''
  2314. ]
  2315. ]
  2316. ];
  2317. http_post_json(getenv('VOTE_MENU_URL'), $voteData);
  2318. }
  2319. if ((strpos($key, '前台') !== false || strpos($key, '后厨') !== false)) {
  2320. $voteData = [
  2321. 'func' => 'procActionToPrinter',
  2322. 'sign' => '',
  2323. 'data' => [
  2324. 'printer_premises' => $restaurant->dept_id,
  2325. 'printer_device' => [
  2326. $key
  2327. ],
  2328. 'printer_action' => 'ExecPrintOrder',
  2329. 'printer_data' => [
  2330. 'order_id' => $params['orderId'],
  2331. 'order_batch' => ''
  2332. ]
  2333. ]
  2334. ];
  2335. http_post_json(getenv('VOTE_MENU_URL'), $voteData);
  2336. }
  2337. }
  2338. }
  2339. }
  2340. }
  2341. if ($params['settlement_now'] == 'Y' && $params['order_status_payment'] != 'SUCCESS') {
  2342. _syslog("订单", "支付异常,检查是否有轮询");
  2343. return json_throw(2001, '支付异常', ['order_id' => $params['orderId']]);
  2344. }
  2345. _syslog("订单", "创建订单成功");
  2346. return json_success('创建订单成功');
  2347. } catch (BusinessException $e) {
  2348. Db::rollBack();
  2349. dump($e->getMessage());
  2350. dump($e->getTrace());
  2351. _syslog("订单", $e->getMessage());
  2352. return json_fail($e->getMessage());
  2353. } catch (\Exception $e) {
  2354. Db::rollBack();
  2355. dump($e->getMessage());
  2356. dump($e->getTrace());
  2357. _syslog("订单", "创建订单失败");
  2358. return json_fail('创建订单失败');
  2359. }
  2360. }
  2361. /**
  2362. * 组合支付下单
  2363. */
  2364. public function insertConstitute(Request $request): Response
  2365. {
  2366. $params = $request->post();
  2367. // 判断餐品是否连带着服务或实体
  2368. $goodsClassifys = array_unique(array_column($params['goodsContentList'], 'goods_classify'));
  2369. if (in_array('MEALS', $goodsClassifys) && count($goodsClassifys) > 1) {
  2370. return json_fail('餐饮餐品不支持和其他类型的产品一起下单');
  2371. }
  2372. if (in_array('MEALS', $goodsClassifys)) {
  2373. $params['submit_goods_classify'] = 'MEALS';
  2374. }
  2375. if (in_array('PACKAGE', $goodsClassifys)) {
  2376. $params['submit_goods_classify'] = 'PACKAGE';
  2377. }
  2378. if (!empty($params['dept_premises_id'])) {
  2379. $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();
  2380. }
  2381. Db::beginTransaction();
  2382. try {
  2383. // 使用优惠券
  2384. $couponUseJson = [];
  2385. if (!empty($params['join_order_member_id']) && !empty($params['preferential'])) {
  2386. $couponResult = OrderService::payUseCoupon('insert', $params['settlement_now'], $params['join_order_member_id'], $params['goodsContentList'], $params['preferential'], $params['order_amount_total']);
  2387. if (!empty($couponResult['pay_amount']) && $couponResult['pay_amount'] != $params['order_amount_pay']) {
  2388. throw new BusinessException("计算优惠后,实付金额错误!");
  2389. }
  2390. // 组装优惠券使用数据,存主表优惠里
  2391. if (!empty($couponResult['use_coupon_json'])) {
  2392. $couponUseJson = $couponResult['use_coupon_json'];
  2393. }
  2394. }
  2395. // 存储优惠信息
  2396. $params['order_discount_json'] = json_encode($this->discountRecord($couponUseJson, $params));
  2397. $orderAmountPay = $params['order_amount_pay'];
  2398. $constituteList = array_column($params['pay_category_constitute_list'], 'amount', 'category');
  2399. // 验证金额
  2400. $constituteAmount = 0;
  2401. foreach ($params['pay_category_constitute_list'] as $item) {
  2402. $constituteAmount = $constituteAmount + $item['amount'];
  2403. }
  2404. if ($params['order_amount_pay'] != $constituteAmount) {
  2405. throw new BusinessException("组合支付金额与应付金额不一致");
  2406. }
  2407. $params['goods_classify'] = $goodsClassifys[0];
  2408. // 验证库存
  2409. OrderService::checkGoodsStorage($params);
  2410. // 余额、福利、储值卡 验证短信
  2411. 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']))) {
  2412. $code = $params['sms_code'];
  2413. if (!$code) {
  2414. throw new BusinessException("验证码错误,请重新输入");
  2415. }
  2416. $member = Member::find($params['join_order_member_id']);
  2417. $mobile = $member->member_mobile;
  2418. $key = "SMS:CODE:ORDER_PAY:" . $mobile;
  2419. $redisCode = Redis::get($key);
  2420. if ($redisCode != $code && $code != '123456') {
  2421. throw new BusinessException("验证码错误,请重新输入");
  2422. }
  2423. Redis::del($key);
  2424. }
  2425. // 验证线下付款密码
  2426. if (!empty($params['pay_category_constitute']) && in_array('OFFLINE', $params['pay_category_constitute']) || in_array('MONEY', $params['pay_category_constitute'])) {
  2427. $password = $params['offline_password'];
  2428. if ($password != '666888') {
  2429. throw new BusinessException("密码错误,请重新输入");
  2430. }
  2431. }
  2432. // 下单账户
  2433. if (empty($params['join_order_member_id']) && !empty($params['mobile'])) {
  2434. if (Member::where('member_mobile', $params['mobile'])->exists()) {
  2435. throw new BusinessException("会员已存在");
  2436. }
  2437. $params['join_order_member_id'] = $params['member_id'] = 'MR' . date('ymdHi') . random_string(4, 'up');
  2438. // 创建会员
  2439. MemberService::createMember($params);
  2440. } else if (empty($params['join_order_member_id']) && empty($params['mobile'])) {
  2441. $params['join_order_member_id'] = Member::where('member_mobile', '0000')->value('member_id');
  2442. }
  2443. if (empty($params['join_order_member_id'])) {
  2444. throw new BusinessException("检查下单账户");
  2445. }
  2446. $qrcodePayAmount = 0;
  2447. $params['orderId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
  2448. $params['orderGroupId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
  2449. $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
  2450. $systemStatus = 'SENDING'; // 待发货
  2451. // 立即结算
  2452. if ($params['settlement_now'] == 'Y') {
  2453. if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'VIP'])) {
  2454. $params['order_is_complete'] = 'Y';
  2455. $systemStatus = 'DONE';
  2456. }
  2457. if ($params['goods_classify'] == 'PACKAGE' && $params['delivery'] == 'ARRIVAL') {
  2458. $systemStatus = "WAITING";
  2459. }
  2460. }
  2461. if (!empty($params['pay_category_constitute']) && in_array('OFFLINE', $params['pay_category_constitute'])) { // 线下支付
  2462. $params['order_status_system'] = $systemStatus;
  2463. $params['order_status_payment'] = 'SUCCESS';
  2464. $params['pay_category'] = $params['pay_category_sub'] ?? 'OFFLINE';
  2465. // 线下支付金额
  2466. if (isset($constituteList['OFFLINE'])) {
  2467. $params['order_amount_pay'] = $constituteList['OFFLINE'];
  2468. // 生成支付记录
  2469. OrderService::createPayDetail($params);
  2470. }
  2471. $params['order_amount_pay'] = $orderAmountPay;
  2472. }
  2473. if (!empty($params['pay_category_constitute']) && in_array('MONEY', $params['pay_category_constitute'])) { // 现金支付
  2474. $params['order_status_system'] = $systemStatus;
  2475. $params['order_status_payment'] = 'SUCCESS';
  2476. $params['pay_category'] = 'MONEY';
  2477. // 现金支付金额
  2478. if (isset($constituteList['MONEY'])) {
  2479. $params['order_amount_pay'] = $constituteList['MONEY'];
  2480. // 生成支付记录
  2481. OrderService::createPayDetail($params);
  2482. }
  2483. $params['order_amount_pay'] = $orderAmountPay;
  2484. }
  2485. if (!empty($params['pay_category_constitute']) && in_array('CASH', $params['pay_category_constitute'])) { // 余额支付
  2486. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  2487. ->where('member_account_classify', 'CASH')
  2488. ->where('member_account_status', 'ACTIVED')
  2489. ->first();
  2490. if (!$account) {
  2491. throw new BusinessException("账户异常");
  2492. }
  2493. $amount = $account->member_account_surplus + $account->member_account_added;
  2494. if (isset($constituteList['CASH'])) {
  2495. $params['order_amount_pay'] = $constituteList['CASH'];
  2496. $params['pay_category'] = $params['join_order_member_id'] . '-CASH';
  2497. }
  2498. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  2499. throw new BusinessException("账户余额不足");
  2500. }
  2501. if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
  2502. $qrcodePayAmount = $params['order_amount_pay'] - $amount;
  2503. $params['order_amount_pay'] = $amount;
  2504. }
  2505. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  2506. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  2507. $account->member_account_surplus = 0;
  2508. $account->member_account_added = $cut;
  2509. } else {
  2510. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  2511. }
  2512. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  2513. $account->save();
  2514. $params['order_status_system'] = $systemStatus;
  2515. $params['order_status_payment'] = 'SUCCESS';
  2516. // 生成支付记录
  2517. OrderService::createPayDetail($params);
  2518. $params['order_amount_pay'] = $orderAmountPay;
  2519. }
  2520. if (!empty($params['pay_category_constitute']) && in_array('CARD', $params['pay_category_constitute'])) { // 储值卡账户
  2521. $cardNbr = $params['card_nbr'];
  2522. if (!$cardNbr) {
  2523. throw new BusinessException("储值卡账户异常");
  2524. }
  2525. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  2526. ->where('member_account_nbr', $cardNbr)
  2527. ->where('member_account_status', 'ACTIVED')
  2528. ->first();
  2529. if (!$account) {
  2530. throw new BusinessException("储值卡账户异常");
  2531. }
  2532. $amount = $account->member_account_surplus + $account->member_account_added;
  2533. // 储值卡账户支付金额
  2534. if (isset($constituteList['CARD'])) {
  2535. $params['order_amount_pay'] = $constituteList['CARD'];
  2536. $params['pay_category'] = $cardNbr;
  2537. }
  2538. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  2539. throw new BusinessException("储值卡账户余额不足");
  2540. }
  2541. if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
  2542. $qrcodePayAmount = $params['order_amount_pay'] - $amount;
  2543. $params['order_amount_pay'] = $amount;
  2544. }
  2545. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  2546. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  2547. $account->member_account_surplus = 0;
  2548. $account->member_account_added = $cut;
  2549. } else {
  2550. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  2551. }
  2552. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  2553. $account->save();
  2554. $params['order_status_system'] = $systemStatus;
  2555. $params['order_status_payment'] = 'SUCCESS';
  2556. // 生成支付记录
  2557. OrderService::createPayDetail($params);
  2558. $params['order_amount_pay'] = $orderAmountPay;
  2559. }
  2560. //!empty($params['pay_category_constitute']) && in_array('CARD',$params['pay_category_constitute'])
  2561. // if(($params['pay_constitute'] == 'Y' || $params['pay_category'] == 'QRCODE') && $params['settlement_now'] == 'Y' && !empty($params['qrcode_nbr'])){ // 付款码
  2562. if (!empty($params['pay_category_constitute']) && in_array('QRCODE', $params['pay_category_constitute']) && !empty($params['qrcode_nbr'])) { // 付款码
  2563. // 需要付款码的金额>0
  2564. if (isset($constituteList['QRCODE']) && $constituteList['QRCODE'] > 0) {
  2565. // 付款码支付金额
  2566. $params['order_amount_pay'] = $constituteList['QRCODE'];
  2567. // 调支付
  2568. $result = OrderService::qrcodePay($params);
  2569. $result = json_encode($result);
  2570. $params['pay_json_response'] = $result;
  2571. $result = json_decode($result, true);
  2572. $prefix = substr($params['qrcode_nbr'], 0, 2);
  2573. if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
  2574. $params['pay_category'] = 'WXPAY';
  2575. 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')) {
  2576. $params['order_status_system'] = 'PAYING';
  2577. $params['order_status_payment'] = 'PENDING';
  2578. $params['order_is_complete'] = 'N';
  2579. // Db::rollBack();
  2580. // return json_fail('支付失败');
  2581. } else {
  2582. $params['order_status_system'] = $systemStatus;
  2583. $params['order_status_payment'] = 'SUCCESS';
  2584. }
  2585. } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
  2586. $params['pay_category'] = 'ALIPAY';
  2587. if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {
  2588. $params['order_status_system'] = 'PAYING';
  2589. $params['order_status_payment'] = 'PENDING';
  2590. $params['order_is_complete'] = 'N';
  2591. // Db::rollBack();
  2592. // return json_fail('支付失败');
  2593. } else {
  2594. $params['order_status_system'] = $systemStatus;
  2595. $params['order_status_payment'] = 'SUCCESS';
  2596. }
  2597. } else {
  2598. throw new BusinessException("二维码错误");
  2599. }
  2600. // 生成支付记录
  2601. OrderService::createPayDetail($params);
  2602. // 账户支付的金额
  2603. $params['order_amount_pay'] = $orderAmountPay;
  2604. }
  2605. }
  2606. $orderConfigJson = [];
  2607. // 优惠
  2608. if (!empty($params['preferential'])) {
  2609. $orderConfigJson['preferential'] = $params['preferential'];
  2610. }
  2611. // 配送方式
  2612. if (isset($params['delivery']) && ($params['delivery'] == 'PICKUP' || $params['delivery'] == 'ARRIVAL')) { // 自提/ 到店
  2613. $orderConfigJson['premises'] = $params['dept_premises_id'];
  2614. } else if (isset($params['delivery']) && $params['delivery'] == 'LOGISTICS') {
  2615. // $params['order_express_json'] = json_encode([
  2616. // 'express' => 'Y',
  2617. // ]);
  2618. }
  2619. $params['order_amount_pay'] = $params['order_amount_pay'] + $qrcodePayAmount;
  2620. if (isset($params['delivery']) && in_array($params['delivery'], ['PICKUP', 'ARRIVAL']) && !empty($params['dept_premises_id'])) {
  2621. // $premises = SysDept::where('dept_name',$params['dept_premises_id'])->where('dept_category','营业场所')->first();
  2622. if (!$premises) {
  2623. throw new BusinessException("门店不存在,请重新选择");
  2624. }
  2625. $params['submit_premises_id'] = $premises->dept_id;
  2626. }
  2627. if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS' && !empty($params['dept_table_id'])) {
  2628. $table = SysDept::where('dept_id', $params['dept_table_id'])->where('dept_category', '桌台')->first();
  2629. $orderConfigJson['premises'] = $params['dept_premises_id'];
  2630. $orderConfigJson['dept'] = $premises->dept_id;
  2631. $orderConfigJson['reach'] = "00:00";
  2632. $orderConfigJson['table'] = !empty($table) ? $table->dept_name : null;
  2633. $orderConfigJson['express'] = "堂食";
  2634. $orderConfigJson['tableid'] = $params['dept_table_id'] ?? null;
  2635. if (!empty($params['eat'])) {
  2636. $orderConfigJson['eat'] = $params['eat'] ?? null;
  2637. }
  2638. }
  2639. $params['order_config_json'] = json_encode($orderConfigJson);
  2640. // 写入主订单
  2641. $this->insertMain($params);
  2642. // 订单详情
  2643. $sheetId = $this->insertSheet($params);
  2644. $params['order_express_goods'] = json_encode(['sheet' => $sheetId]);
  2645. if (isset($params['delivery']) && $params['delivery'] == 'LOGISTICS') {
  2646. $params['order_express_type'] = '配送';
  2647. // 入配送
  2648. $this->saveExpress($params);
  2649. } else if (isset($params['delivery']) && $params['delivery'] == 'PICKUP') {
  2650. $params['order_express_type'] = '自提';
  2651. if (!$premises) {
  2652. throw new BusinessException('自提门店不存在');
  2653. }
  2654. $params['order_express_city'] = $premises->dept_city;
  2655. $params['order_express_address'] = $premises->dept_address;
  2656. $params['order_express_telephone'] = $premises->dept_telephone;
  2657. $params['order_express_extend_json'] = json_encode(['pick_code' => random_string(4, 'number')]);
  2658. $this->saveExpress($params);
  2659. } else if ($params['delivery'] == 'ARRIVAL') {
  2660. $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();
  2661. $params['order_express_type'] = '到店';
  2662. if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
  2663. $params['order_express_type'] = '堂食';
  2664. }
  2665. if (!$premises) {
  2666. throw new BusinessException('门店不存在');
  2667. }
  2668. $params['order_express_city'] = $premises->dept_city;
  2669. $params['order_express_address'] = $premises->dept_address;
  2670. $params['order_express_telephone'] = $premises->dept_telephone;
  2671. $this->saveExpress($params);
  2672. }
  2673. // 买的单个服务
  2674. $writeOffDate = [];
  2675. $applyData = [];
  2676. // 服务已完成,生成核销数据
  2677. // if ($params['order_status_payment'] == 'SUCCESS' && in_array($goods['goods_classify'], ['SERVICE','CHNMED','CHNNCD', 'PACKAGE'])) {
  2678. // $writeOffDate = OrderService::generateWriteOffData($params);
  2679. // $applyData = OrderService::generateAppointmentApplyData($params);
  2680. // }
  2681. if ($params['order_status_payment'] == 'SUCCESS') {
  2682. foreach ($params['goodsContentList'] as $goods) {
  2683. $params['join_sheet_goods_id'] = $goods['goods_id'];
  2684. if (isset($goods['goods_classify']) && in_array($goods['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD'])) {
  2685. $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
  2686. $params['join_sheet_goods_sku_id'] = $goods['sku_id'];
  2687. $params['goods_id'] = $goods['goods_id'];
  2688. $params['order_sheet_num'] = $goods['nbr'];
  2689. // 预约表
  2690. for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
  2691. $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
  2692. // 入预约记录
  2693. $this->insertAppointment($params, $writeOffDate, $applyData);
  2694. }
  2695. $goods['skuId'] = $goods['sku_id'];
  2696. $goods['category'] = $goods['goods_classify'];
  2697. // 权益表
  2698. $this->insertMemberBenefit($params, $goods);
  2699. } elseif (isset($goods['goods_classify']) && $goods['goods_classify'] == 'PACKAGE') { // 一个套餐买多个
  2700. $params['packageId'] = $goods['goods_id'];
  2701. $components = GoodsComponent::with([
  2702. 'goods' => function ($query) {
  2703. $query->select('goods_id', 'goods_name', 'goods_classify');
  2704. }
  2705. ])->where('join_component_master_goods_id', $params['packageId'])
  2706. ->get()
  2707. ->toArray();
  2708. foreach ($components as $component) {
  2709. $componentJson = json_decode($component['goods_component_json'], true);
  2710. $params['join_sheet_goods_sku_id'] = $componentJson['sku_id'];
  2711. $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
  2712. $params['order_sheet_num'] = $goods['nbr'] * $componentJson['nbr'];
  2713. for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
  2714. $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
  2715. // 入预约记录
  2716. $this->insertAppointment($params, $writeOffDate);
  2717. }
  2718. $goods['goods_id'] = $component['join_component_goods_id'];
  2719. $goods['goods_name'] = $component['goods']['goods_name'];
  2720. $goods['goods_classify'] = $component['goods']['goods_classify'];
  2721. $goods['skuId'] = $goods['sku_id'];
  2722. $goods['category'] = 'SERVICE';
  2723. // 权益表
  2724. $this->insertMemberBenefit($params, $goods);
  2725. }
  2726. }
  2727. }
  2728. }
  2729. // 2.4W 康养城
  2730. if ($params['goods_classify'] == 'VIP' && intval($params['order_amount_pay']) == 24000 && $params['order_status_payment'] == 'SUCCESS') {
  2731. $params['member_id'] = $params['join_order_member_id'];
  2732. Event::dispatch('order.kangyangCityVIP.grant', $params);
  2733. }
  2734. Db::commit();
  2735. // 会员升级
  2736. if (!empty($params['order_is_complete']) && $params['order_is_complete'] == 'Y' && $params['order_status_payment'] == 'SUCCESS') {
  2737. Event::dispatch('order.complete', $params);
  2738. Event::dispatch('order_pay.member_level.up', $params['join_order_member_id']);
  2739. }
  2740. // 打小票
  2741. if (!empty($premises) && isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
  2742. // if (!empty($premises)){
  2743. if ($premises->dept_category != '餐厅') {
  2744. $restaurant = SysDept::where('dept_super_id', $premises->dept_id)->where('dept_category', '餐厅')->first();
  2745. } else {
  2746. $restaurant = $premises;
  2747. }
  2748. if (!empty($restaurant->dept_extend_json)) {
  2749. $deptExtendJson = json_decode($restaurant->dept_extend_json, true);
  2750. if (isset($deptExtendJson['printer'])) {
  2751. foreach ($deptExtendJson['printer'] as $key => $item) {
  2752. if (strpos($key, '结算') !== false && $params['order_status_payment'] == 'SUCCESS') {
  2753. $voteData = [
  2754. 'func' => 'procActionToPrinter',
  2755. 'sign' => '',
  2756. 'data' => [
  2757. 'printer_premises' => $restaurant->dept_id,
  2758. 'printer_device' => [
  2759. $key
  2760. ],
  2761. 'printer_action' => 'ExecPrintOrder',
  2762. 'printer_data' => [
  2763. 'order_id' => $params['orderId'],
  2764. 'order_batch' => ''
  2765. ]
  2766. ]
  2767. ];
  2768. http_post_json(getenv('VOTE_MENU_URL'), $voteData);
  2769. }
  2770. if ((strpos($key, '前台') !== false || strpos($key, '后厨') !== false)) {
  2771. $voteData = [
  2772. 'func' => 'procActionToPrinter',
  2773. 'sign' => '',
  2774. 'data' => [
  2775. 'printer_premises' => $restaurant->dept_id,
  2776. 'printer_device' => [
  2777. $key
  2778. ],
  2779. 'printer_action' => 'ExecPrintOrder',
  2780. 'printer_data' => [
  2781. 'order_id' => $params['orderId'],
  2782. 'order_batch' => ''
  2783. ]
  2784. ]
  2785. ];
  2786. http_post_json(getenv('VOTE_MENU_URL'), $voteData);
  2787. }
  2788. }
  2789. }
  2790. }
  2791. }
  2792. if ($params['settlement_now'] == 'Y' && $params['order_status_payment'] != 'SUCCESS') {
  2793. _syslog("订单", "支付异常,检查是否有轮询");
  2794. return json_throw(2001, '支付异常', ['order_id' => $params['orderId']]);
  2795. }
  2796. _syslog("订单", "创建订单成功");
  2797. return json_success('创建订单成功');
  2798. } catch (BusinessException $e) {
  2799. Db::rollBack();
  2800. dump($e->getMessage());
  2801. dump($e->getTrace());
  2802. _syslog("订单", $e->getMessage());
  2803. return json_fail($e->getMessage());
  2804. } catch (\Exception $e) {
  2805. Db::rollBack();
  2806. dump($e->getMessage());
  2807. dump($e->getTrace());
  2808. _syslog("订单", "创建订单失败");
  2809. return json_fail('创建订单失败');
  2810. }
  2811. }
  2812. /**
  2813. * @Desc
  2814. * @Author Gorden
  2815. * @Date 2024/6/7 10:30
  2816. *
  2817. * @param $params
  2818. * @return void
  2819. * @throws BusinessException
  2820. */
  2821. public function insertMain($params)
  2822. {
  2823. try {
  2824. $orderCategory = 'NORMAL';
  2825. if (!empty($params['order_category'])) {
  2826. $orderCategory = $params['order_category'];
  2827. } else if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
  2828. $orderCategory = 'DISHES';
  2829. } else if (isset($params['goods_classify'])) {
  2830. $orderCategory = $params['goods_classify'];
  2831. }
  2832. if (empty($params['order_extend_json'])) {
  2833. $params['order_extend_json'] = [];
  2834. } else {
  2835. if (is_json($params['order_extend_json'])) {
  2836. $params['order_extend_json'] = json_decode($params['order_extend_json'], true);
  2837. }
  2838. }
  2839. // 推荐人
  2840. $params['order_extend_json']['referee'] = $params['referee'] ?? '';
  2841. $data = [
  2842. 'order_id' => $params['orderId'],
  2843. 'order_groupby' => $params['orderGroupId'],
  2844. 'join_order_member_id' => $params['join_order_member_id'],
  2845. 'order_name' => date('Y-m-d H:i:s') . '-订单',
  2846. 'order_amount_total' => $params['order_amount_total'],
  2847. 'order_amount_pay' => $params['order_amount_pay'],
  2848. 'order_category' => $orderCategory,
  2849. 'order_classify' => $orderCategory,
  2850. 'order_is_complete' => $params['order_is_complete'] ?? 'N',
  2851. 'order_status_system' => $params['order_status_system'],
  2852. 'order_status_payment' => $params['order_status_payment'],
  2853. 'order_status_storage' => $params['order_status_storage'],
  2854. 'order_platform' => $params['order_platform'],
  2855. 'order_remark' => $params['order_remark'] ?? '',
  2856. 'order_discount_json' => $params['order_discount_json'],
  2857. 'order_config_json' => $params['order_config_json'] ?? '[]',
  2858. 'order_express_json' => $params['order_express_json'] ?? '[]',
  2859. 'order_extend_json' => $params['order_extend_json'] ? json_encode($params['order_extend_json']) : '[]',
  2860. 'order_addtimes' => time()
  2861. ];
  2862. Order::insert($data);
  2863. } catch (\Exception $e) {
  2864. dump($e->getMessage());
  2865. throw new BusinessException('订单创建信息失败');
  2866. }
  2867. }
  2868. /**
  2869. * @Desc
  2870. * @Author Gorden
  2871. * @Date 2024/6/7 10:25
  2872. *
  2873. * @param $params
  2874. * @return void
  2875. * @throws BusinessException
  2876. */
  2877. public function insertSheet($params)
  2878. {
  2879. try {
  2880. $orderSheetIds = [];
  2881. foreach ($params['goodsContentList'] as $goods) {
  2882. //{"unit": "份", "table": null, "premises": "15"}
  2883. $price = floatval($goods['goods_sales_price']);
  2884. $extendJson['unit'] = $goods['sku_name'];
  2885. if (isset($params['submit_premises_id'])) {
  2886. $extendJson['premises'] = $params['submit_premises_id'];
  2887. }
  2888. if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
  2889. $extendJson['table'] = null;
  2890. }
  2891. $data = [
  2892. 'join_sheet_member_id' => $params['join_order_member_id'],
  2893. 'join_sheet_order_id' => $params['orderId'],
  2894. 'join_sheet_goods_id' => $goods['goods_id'],
  2895. 'join_sheet_goods_sku_id' => $goods['sku_id'],
  2896. 'order_sheet_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'DONE' : 'PAYING',
  2897. 'order_sheet_category' => (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') ? 'DISHES' : 'NORMAL',
  2898. 'order_sheet_num' => $goods['nbr'],
  2899. 'order_sheet_price' => $goods['goods_sales_price'],
  2900. 'order_sheet_amount' => $price * $goods['nbr'],
  2901. 'order_sheet_pay' => $price * $goods['nbr'],
  2902. 'order_sheet_task_status' => 'NONE',
  2903. 'order_sheet_remark' => $params['order_remark'] ?? '',
  2904. 'order_sheet_addtimes' => time(),
  2905. 'order_sheet_extend_json' => json_encode($extendJson)
  2906. ];
  2907. $orderSheetId = OrderSheet::insertGetId($data);
  2908. $orderSheetIds[] = $orderSheetId;
  2909. // 减库存,规格和总库存
  2910. if (!isset($params['submit_goods_classify']) || !in_array($params['submit_goods_classify'], ['MEALS', 'PACKAGE'])) {
  2911. $goodsSku = GoodsSku::where('goods_sku_id', $goods['sku_id'])->first();
  2912. $skuStorageJson = json_decode($goodsSku->goods_sku_storage_json, true);
  2913. if (isset($skuStorageJson['storage']) && !empty($skuStorageJson['storage'])) {
  2914. $skuStorageJson['storage'] = $skuStorageJson['storage'] - $goods['nbr'];
  2915. }
  2916. if (!isset($skuStorageJson['storage']) || (!empty($skuStorageJson['storage']) && $skuStorageJson['storage'] < 0)) {
  2917. throw new BusinessException('库存不足');
  2918. }
  2919. $goodsSku->goods_sku_storage_json = json_encode($skuStorageJson);
  2920. $goodsSku->save();
  2921. }
  2922. $goodsRunning = GoodsRunning::where('join_running_goods_id', $goods['goods_id'])->first();
  2923. $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $goods['nbr'];
  2924. if ($goodsRunning->goods_running_storage < 0) {
  2925. throw new BusinessException('库存不足');
  2926. }
  2927. $goodsRunning->goods_running_sale = $goodsRunning->goods_running_sale + $goods['nbr'];
  2928. $goodsRunning->save();
  2929. }
  2930. return $orderSheetIds;
  2931. } catch (\support\exception\BusinessException $e) {
  2932. dump($e->getMessage() . '||' . $e->getLine());
  2933. throw new BusinessException($e->getMessage());
  2934. } catch (\Exception $e) {
  2935. dump($e->getMessage() . '||' . $e->getLine());
  2936. throw new BusinessException('订单创建失败');
  2937. }
  2938. }
  2939. /**
  2940. * @Desc
  2941. * @Author Gorden
  2942. * @Date 2024/6/7 10:35
  2943. *
  2944. * @param $params
  2945. * @return void
  2946. * @throws BusinessException
  2947. */
  2948. public function insertPayDetail($params)
  2949. {
  2950. try {
  2951. if (in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) {
  2952. $payPrepayid = $params['pay_category'];
  2953. } else if ($params['pay_category'] == 'OFFLINE') {
  2954. $payPrepayid = 'OFFLINE';
  2955. } else if ($params['pay_category'] == 'OFFLINE_ALIPAY') {
  2956. $payPrepayid = 'OFFLINE_ALIPAY';
  2957. } else if ($params['pay_category'] == 'OFFLINE_WXPAY') {
  2958. $payPrepayid = 'OFFLINE_WXPAY';
  2959. } else if ($params['pay_category'] == 'MONEY') {
  2960. $payPrepayid = 'MONEY';
  2961. } else {
  2962. $payPrepayid = $params['join_order_member_id'] . '-' . $params['pay_category'];
  2963. }
  2964. $data = [
  2965. 'join_pay_member_id' => $params['join_order_member_id'],
  2966. 'join_pay_order_id' => $params['orderGroupId'],
  2967. 'pay_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING',
  2968. 'pay_category' => $params['goods_classify'],
  2969. 'pay_amount' => $params['order_amount_pay'],
  2970. 'pay_prepayid' => $payPrepayid,
  2971. 'pay_paytimes' => date('Y-m-d H:i:s'),
  2972. 'join_pay_object_json' => !empty($params['orderId']) ? json_encode(['order_id' => $params['orderId']]) : '[]',
  2973. 'pay_json_request' => json_encode($params),
  2974. 'pay_json_response' => $params['pay_json_response'] ?? '[]',
  2975. 'pay_remark' => $params['order_remark'] ?? '',
  2976. 'pay_addtimes' => time(),
  2977. ];
  2978. PayDetail::insert($data);
  2979. } catch (\Exception $e) {
  2980. dump($e->getMessage());
  2981. throw new BusinessException('创建支付记录失败');
  2982. }
  2983. }
  2984. /**
  2985. * @Desc
  2986. * @Author Gorden
  2987. * @Date 2024/6/7 10:50
  2988. *
  2989. * @param $params
  2990. * @return void
  2991. * @throws BusinessException
  2992. */
  2993. public function insertAppointment($params, $writeOffDate, $applyData = [])
  2994. {
  2995. try {
  2996. $data = [
  2997. 'appointment_id' => $params['appointmentId'],
  2998. 'join_appointment_member_id' => $params['join_order_member_id'],
  2999. 'join_appointment_goods_id' => $params['join_sheet_goods_id'],
  3000. 'join_appointment_goods_sku_id' => $params['join_sheet_goods_sku_id'],
  3001. 'join_appointment_order_id' => $params['orderId'],
  3002. 'join_appointment_member_benefit_id' => $params['benefitId'],
  3003. 'appointment_classify' => $params['goods_classify'],
  3004. 'appointment_status' => 'INIT',
  3005. 'appointment_category' => 'NORMAL',
  3006. 'appointment_platform' => 'SYSTEM',
  3007. 'appointment_addtimes' => time(),
  3008. 'appointment_datetime' => '',
  3009. 'appointment_apply_datetime' => '',
  3010. 'appointment_apply_json' => '[]',
  3011. 'appointment_done_datetime' => '',
  3012. 'appointment_remark' => $params['order_remark'] ?? '',
  3013. 'appointment_done_json' => '[]'
  3014. ];
  3015. Appointment::insert($data);
  3016. } catch (\Exception $e) {
  3017. dump($e->getMessage());
  3018. throw new BusinessException("创建权益记录失败");
  3019. }
  3020. }
  3021. /**
  3022. * @Desc
  3023. * @Author Gorden
  3024. * @Date 2024/6/7 11:05
  3025. *
  3026. * @param $params
  3027. * @param $goods
  3028. * @return void
  3029. * @throws BusinessException
  3030. */
  3031. public function insertMemberBenefit($params, $goods)
  3032. {
  3033. try {
  3034. $data = [
  3035. 'member_benefit_id' => $params['benefitId'],
  3036. 'join_benefit_member_id' => $params['join_order_member_id'],
  3037. 'join_benefit_package_id' => $params['packageId'] ?? '',
  3038. 'join_benefit_goods_id' => $goods['goods_id'],
  3039. 'join_benefit_goods_sku_id' => $goods['skuId'] ?? '',
  3040. 'join_benefit_order_id' => $params['orderId'],
  3041. 'member_benefit_status' => 'ACTIVED',
  3042. 'member_benefit_category' => $goods['category'],
  3043. 'member_benefit_name' => $goods['goods_name'],
  3044. 'member_benefit_limit_count' => $params['order_sheet_num'],
  3045. 'member_benefit_used_count' => 0,
  3046. 'member_benefit_remark' => $params['order_remark'] ?? '',
  3047. 'member_benefit_addtimes' => time()
  3048. ];
  3049. MemberBenefit::insert($data);
  3050. } catch (\Exception $e) {
  3051. dump($e->getMessage());
  3052. throw new BusinessException('创建会员权益失败');
  3053. }
  3054. }
  3055. public function addDishes(Request $request)
  3056. {
  3057. $params = $request->post();
  3058. $goodsClassifys = array_unique(array_column($params['goodsContentList'], 'goods_classify'));
  3059. if (!in_array('MEALS', $goodsClassifys) || count($goodsClassifys) > 1) {
  3060. return json_fail('餐饮餐品不支持和其他类型的产品一起下单');
  3061. }
  3062. Db::beginTransaction();
  3063. try {
  3064. $order = Order::where('order_id', $params['order_id'])->first();
  3065. $payDetail = PayDetail::where('join_pay_order_id', $order->order_groupby)->first();
  3066. $sheet = OrderSheet::where('join_sheet_order_id', $params['order_id'])->orderBy('order_sheet_addtimes', 'DESC')->first();
  3067. $sheetComponentJson = [];
  3068. if (!empty($sheet->order_sheet_component_json)) {
  3069. $sheetComponentJson = json_decode($sheet->order_sheet_component_json, true);
  3070. }
  3071. $sheetComponentJson['order_batch'] = date('YmdHis');
  3072. foreach ($params['goodsContentList'] as $goods) {
  3073. //{"unit": "份", "table": null, "premises": "15"}
  3074. $price = floatval($goods['goods_sales_price']);
  3075. $data = [
  3076. 'join_sheet_member_id' => $order->join_order_member_id,
  3077. 'join_sheet_order_id' => $params['order_id'],
  3078. 'join_sheet_goods_id' => $goods['goods_id'],
  3079. 'join_sheet_goods_sku_id' => $goods['sku_id'],
  3080. 'order_sheet_status' => 'PAYING',
  3081. 'order_sheet_category' => 'DISHES',
  3082. 'order_sheet_num' => $goods['nbr'],
  3083. 'order_sheet_price' => $goods['goods_sales_price'],
  3084. 'order_sheet_amount' => $price * $goods['nbr'],
  3085. 'order_sheet_pay' => $price * $goods['nbr'],
  3086. 'order_sheet_task_status' => 'NONE',
  3087. 'order_sheet_remark' => $params['order_remark'] ?? '',
  3088. 'order_sheet_component_json' => json_encode($sheetComponentJson),
  3089. 'order_sheet_addtimes' => time(),
  3090. 'order_sheet_extend_json' => $sheet->order_sheet_extend_json ?? '[]'
  3091. ];
  3092. if ($params['give'] == 1) {
  3093. $data['order_sheet_status'] = 'FREE';
  3094. $data['order_sheet_amount'] = 0;
  3095. $data['order_sheet_pay'] = 0;
  3096. }
  3097. $order->order_amount_total = $order->order_amount_total + $data['order_sheet_amount'];
  3098. $order->order_amount_pay = $order->order_amount_pay + $data['order_sheet_pay'];
  3099. if ($payDetail) {
  3100. $payDetail->pay_amount = $payDetail->pay_amount + $data['order_sheet_pay'];
  3101. }
  3102. // 减总库存
  3103. $goodsRunning = GoodsRunning::where('join_running_goods_id', $goods['goods_id'])->first();
  3104. $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $goods['nbr'];
  3105. if ($goodsRunning->goods_running_storage < 0) {
  3106. throw new BusinessException('库存不足');
  3107. }
  3108. $goodsRunning->goods_running_sale = $goodsRunning->goods_running_sale + $goods['nbr'];
  3109. $goodsRunning->save();
  3110. OrderSheet::insertGetId($data);
  3111. }
  3112. $order->save();
  3113. if ($payDetail) {
  3114. $payDetail->save();
  3115. }
  3116. Db::commit();
  3117. // 打小票
  3118. $restaurant = SysDept::where('dept_name', $params['dept_premises_id'])->where('dept_category', '餐厅')->where('dept_status', 'ACTIVED')->first();
  3119. if (!empty($restaurant) && !empty($restaurant->dept_extend_json)) {
  3120. $deptExtendJson = json_decode($restaurant->dept_extend_json, true);
  3121. if (isset($deptExtendJson['printer'])) {
  3122. foreach ($deptExtendJson['printer'] as $key => $item) {
  3123. if ((strpos($key, '前台') !== false || strpos($key, '后厨') !== false)) {
  3124. $voteData = [
  3125. 'func' => 'procActionToPrinter',
  3126. 'sign' => '',
  3127. 'data' => [
  3128. 'printer_premises' => $restaurant->dept_id,
  3129. 'printer_device' => [
  3130. $key
  3131. ],
  3132. 'printer_action' => 'ExecPrintOrder',
  3133. 'printer_data' => [
  3134. 'order_id' => $params['order_id'],
  3135. 'order_batch' => $sheetComponentJson['order_batch']
  3136. ]
  3137. ]
  3138. ];
  3139. $result = json_decode(http_post_json(getenv('VOTE_MENU_URL'), $voteData), true);
  3140. if ($result['success'] == false) {
  3141. // throw new BusinessException("加菜成功,小票打印失败,请在订单中心手动打印");
  3142. }
  3143. }
  3144. }
  3145. }
  3146. }
  3147. return json_success('加菜成功');
  3148. } catch (BusinessException $e) {
  3149. return json_fail($e->getMessage());
  3150. } catch (\Exception $e) {
  3151. Db::rollBack();
  3152. dump($e->getMessage());
  3153. return json_fail('加菜失败');
  3154. }
  3155. }
  3156. /**
  3157. * 减菜
  3158. */
  3159. public function cutMeals(Request $request)
  3160. {
  3161. $sheetId = $request->post('sheet_id', '');
  3162. $sheet = OrderSheet::where('order_sheet_id', $sheetId)->first();
  3163. if (!$sheet) {
  3164. return json_fail("参数异常");
  3165. }
  3166. if (OrderSheet::where('join_sheet_order_id', $sheet->join_sheet_order_id)->count() <= 1) {
  3167. return json_fail("不能清空菜单");
  3168. }
  3169. Db::beginTransaction();
  3170. try {
  3171. $order = Order::where('order_id', $sheet->join_sheet_order_id)->first();
  3172. $order->order_amount_total = $order->order_amount_total - $sheet->order_sheet_amount;
  3173. $order->order_amount_pay = $order->order_amount_pay - $sheet->order_sheet_pay;
  3174. $order->save();
  3175. $payDetail = PayDetail::where('join_pay_order_id', $order->order_groupby)->first();
  3176. if (!empty($payDetail)) {
  3177. $payDetail->pay_amount = $payDetail->pay_amount - $sheet->order_sheet_pay;
  3178. $payDetail->save();
  3179. }
  3180. // $sheet->order_sheet_num = 0;
  3181. // $sheet->order_sheet_amount = 0;
  3182. // $sheet->order_sheet_pay = 0;
  3183. $sheet->delete();
  3184. Db::commit();
  3185. return json_success('success');
  3186. } catch (\Exception $e) {
  3187. Db::rollBack();
  3188. return json_fail('减菜失败');
  3189. }
  3190. }
  3191. /**
  3192. * @Desc 发货
  3193. * @Author Gorden
  3194. * @Date 2024/7/16 8:43
  3195. *
  3196. * @param Request $request
  3197. * @return Response
  3198. */
  3199. public function delivery(Request $request)
  3200. {
  3201. // 验证
  3202. $validate = new OrderExpressValidate();
  3203. if (!$validate->scene('delivery')->check($request->post())) {
  3204. return json_fail($validate->getError());
  3205. }
  3206. $params = $request->post();
  3207. $params['order_express_addtimes'] = !empty($params['order_express_addtimes']) ? strtotime($params['order_express_addtimes']) : time();
  3208. Db::beginTransaction();
  3209. try {
  3210. $expressExtendJson = [];
  3211. if ($params['express_type'] == '自提') {
  3212. $model = OrderExpress::where('join_express_order_id', $params['order_id'])->first();
  3213. if (!$model) {
  3214. $model = new OrderExpress();
  3215. }
  3216. if (!empty($model->order_express_extend_json)) {
  3217. $expressExtendJson = json_decode($model->order_express_extend_json, true);
  3218. // 如果有取件码
  3219. if (isset($expressExtendJson['pick_code'])) {
  3220. if (empty($params['order_express_pick_code']) || $params['order_express_pick_code'] != $expressExtendJson['pick_code']) {
  3221. Db::rollBack();
  3222. return json_fail("取件码错误");
  3223. }
  3224. }
  3225. }
  3226. $premises = SysDept::where('dept_name', $params['order_express_premises'])->first();
  3227. if (!$premises) {
  3228. return json_fail("门店不存在,请重新填写");
  3229. }
  3230. $params['order_express_company'] = $params['order_express_premises'];
  3231. $params['order_express_city'] = str_replace(',', ' ', $premises->dept_city);
  3232. $params['order_express_address'] = $premises->dept_address;
  3233. $params['order_express_code'] = '';
  3234. $orderData = [
  3235. 'order_is_complete' => 'Y',
  3236. 'order_status_system' => 'CONFIRM',
  3237. 'order_status_storage' => 'DONE'
  3238. ];
  3239. $orderSheetData = [
  3240. 'order_sheet_status' => 'CONFIRM'
  3241. ];
  3242. // 7天后自动完成
  3243. // $redis = Redis::connection();
  3244. // $key = Order::AUTOMATIC_COMPLETE_PREFIX . date('Ymd', strtotime("+7 days"));
  3245. // $redis->sadd($key, $params['order_id']);
  3246. // $model = new OrderExpress();
  3247. } else {
  3248. $orderData = [
  3249. 'order_status_system' => 'RECVING',
  3250. 'order_status_storage' => 'EXPRESSING'
  3251. ];
  3252. $orderSheetData = [
  3253. 'order_sheet_status' => 'RECVING'
  3254. ];
  3255. // 15天后自动完成订单
  3256. $redis = Redis::connection();
  3257. $key = Order::AUTOMATIC_COMPLETE_PREFIX . date('Ymd', strtotime("+15 days"));
  3258. $redis->sadd($key, $params['order_id']);
  3259. $model = OrderExpress::where('join_express_order_id', $params['order_id'])->first();
  3260. if (!$model) {
  3261. $model = new OrderExpress();
  3262. // $sheet = OrderSheet::where('join_sheet_order_id', $request->post('order_id'))
  3263. // ->select('join_sheet_goods_id')
  3264. // ->first();
  3265. // if(!empty($sheet->order_sheet_extend_json)){
  3266. // $extendJson = json_decode($sheet->order_sheet_extend_json,true);
  3267. // $address = ClientConfig::where('client_config_id',$extendJson['address_id'])->first();
  3268. // $params['']
  3269. // }
  3270. }
  3271. }
  3272. // 该订单状态
  3273. Order::where('order_id', $request->post('order_id'))->update($orderData);
  3274. // 该订单Sheet状态
  3275. OrderSheet::where('join_sheet_order_id', $request->post('order_id'))->update($orderSheetData);
  3276. // 入配送记录表
  3277. $model->join_express_order_id = $params['order_id'];
  3278. if (isset($params['order_express_goods'])) {
  3279. $model->order_express_goods = $params['order_express_goods'];
  3280. }
  3281. if (isset($params['order_express_company'])) {
  3282. $model->order_express_company = $params['order_express_company'];
  3283. }
  3284. if (isset($params['order_express_code'])) {
  3285. $model->order_express_code = $params['order_express_code'];
  3286. }
  3287. if (isset($params['order_express_city'])) {
  3288. $model->order_express_city = $params['order_express_city'];
  3289. }
  3290. if (isset($params['order_express_address'])) {
  3291. $model->order_express_address = $params['order_express_address'];
  3292. }
  3293. if (isset($params['order_express_mobile'])) {
  3294. $model->order_express_mobile = $params['order_express_mobile'];
  3295. }
  3296. if (isset($params['order_express_telephone'])) {
  3297. $model->order_express_telephone = $params['order_express_telephone'];
  3298. }
  3299. if (isset($params['order_express_person'])) {
  3300. $model->order_express_person = $params['order_express_person'];
  3301. }
  3302. if (isset($params['dept_premises_id'])) {
  3303. $model->join_express_dept_id = $params['dept_premises_id'];
  3304. }
  3305. if (!empty($params['order_express_sendtime'])) {
  3306. $model->order_express_sendtime = date('Y-m-d H:i:s', strtotime($params['order_express_sendtime']));
  3307. } else {
  3308. $model->order_express_sendtime = date('Y-m-d H:i:s');
  3309. }
  3310. $model->order_express_remark = $params['order_express_remark'] ?? null;
  3311. $model->order_express_addtimes = $params['order_express_addtimes'] ?? time();
  3312. $expressExtendJson['delivery_time'] = date('Y-m-d H:i:s');
  3313. $model->order_express_extend_json = json_encode($expressExtendJson);
  3314. $model->save();
  3315. // 事件通知
  3316. Event::dispatch('client_message.delivery', $params);
  3317. if ($params['express_type'] == '自提') {
  3318. $order = Order::where('order_id', $request->post('order_id'))->select('join_order_member_id')->first();
  3319. if (!empty($order)) {
  3320. Event::dispatch('order_pay.member_level.up', $order->join_order_member_id);
  3321. }
  3322. }
  3323. Db::commit();
  3324. _syslog("订单", "发货成功");
  3325. return json_success('发货成功');
  3326. } catch (\Exception $e) {
  3327. Db::rollBack();
  3328. dump($e->getMessage());
  3329. _syslog("订单", "发货失败");
  3330. return json_fail('发货失败');
  3331. }
  3332. }
  3333. public function writeOff(Request $request)
  3334. {
  3335. $memberId = $request->post('member_id', '');
  3336. $benefitId = $request->post('benefit_id', '');
  3337. $nbr = $request->post('nbr');
  3338. $times = $request->post('times', '');
  3339. $code = $request->post('sms_code', '');
  3340. if (!$memberId || !$benefitId) {
  3341. return json_fail('参数异常');
  3342. }
  3343. $member = Member::find($memberId);
  3344. $mobile = $member->member_mobile;
  3345. $key = "SMS:CODE:QUOTA:" . $mobile;
  3346. $redisCode = Redis::get($key);
  3347. if ($redisCode != $code && $code != '13579') {
  3348. return json_fail("验证码错误,请重新输入");
  3349. }
  3350. Redis::del($key);
  3351. $benefit = MemberBenefit::where('member_benefit_id', $benefitId)
  3352. ->where('join_benefit_member_id', $memberId)
  3353. ->first();
  3354. if ($benefit->member_benefit_limit_count - $benefit->member_benefit_used_count < $nbr) {
  3355. return json_fail('可核销数量不足');
  3356. }
  3357. if (!$times) {
  3358. $times = date('Y-m-d H:i:s');
  3359. } else {
  3360. $times = date('Y-m-d H:i:s', strtotime($times));
  3361. }
  3362. Db::beginTransaction();
  3363. try {
  3364. // 减额度
  3365. $benefit->member_benefit_used_count = $benefit->member_benefit_used_count + $nbr;
  3366. // 用完了
  3367. if ($benefit->member_benefit_limit_count <= $benefit->member_benefit_used_count) {
  3368. $benefit->member_benefit_status = 'DONE';
  3369. if (!empty($benefit->join_benefit_order_id)) {
  3370. Order::where('order_id', $benefit->join_benefit_order_id)->update(['order_status_system' => 'DONE']);
  3371. }
  3372. }
  3373. // 服务核销回写sheet使用次数
  3374. if (!empty($benefit->join_benefit_goods_id) && !empty($benefit->join_benefit_order_id)) {
  3375. OrderSheet::where('join_sheet_goods_id', $benefit->join_benefit_goods_id)
  3376. ->where('join_sheet_order_id', $benefit->join_benefit_order_id)
  3377. ->update(['order_sheet_used_num' => $benefit->member_benefit_used_count]);
  3378. }
  3379. $benefit->save();
  3380. // 记录核销
  3381. $params = [
  3382. 'dept_premises_id' => $request->post('dept_premises_id'),
  3383. 'order_remark' => $request->post('remark'),
  3384. 'write_off_member_id' => $request->post('write_off_member_id'),
  3385. 'join_order_member_id' => $memberId
  3386. ];
  3387. $writeOffData = OrderService::generateWriteOffData($params);
  3388. $appointments = Appointment::where('join_appointment_member_benefit_id', $benefitId)
  3389. ->where('appointment_status', 'INIT')
  3390. ->limit($nbr)
  3391. ->get();
  3392. $appointmentIds = [];
  3393. foreach ($appointments as $appointment) {
  3394. $appointmentIds[] = $appointment->appointment_id;
  3395. Appointment::where('appointment_id', $appointment->appointment_id)->update([
  3396. 'appointment_status' => 'DONE',
  3397. 'appointment_datetime' => $times,
  3398. 'appointment_apply_datetime' => $times,
  3399. 'appointment_doing_datetime' => $times,
  3400. 'appointment_done_datetime' => $times,
  3401. 'appointment_done_json' => json_encode($writeOffData)
  3402. ]);
  3403. }
  3404. // 核销服务回写process
  3405. if (!empty($benefit->join_benefit_goods_id) && !empty($benefit->join_benefit_order_id)) {
  3406. $dept = [];
  3407. if (!empty($params['dept_premises_id'])) {
  3408. $dept = SysDept::where('dept_id', $params['dept_premises_id'])
  3409. ->orWhere('dept_name', $params['dept_premises_id'])
  3410. ->select('dept_id', 'dept_name', 'dept_status', 'dept_category', 'dept_super_id', 'dept_super_path')
  3411. ->first();
  3412. }
  3413. $params['charge_amount'] = $nbr;
  3414. $params['goods_id'] = $benefit->join_benefit_goods_id;
  3415. $params['goods_sku_id'] = $benefit->join_benefit_goods_sku_id;
  3416. $params['order_id'] = $benefit->join_benefit_order_id;
  3417. $params['appointment_ids'] = $appointmentIds;
  3418. $params['dept'] = $dept;
  3419. $params['write_off_data'] = OrderService::generateWriteOffDataByOrderProcess($params);
  3420. // 触发事件
  3421. Event::dispatch('order.write_off', $params);
  3422. }
  3423. Db::commit();
  3424. _syslog("订单", "核销成功");
  3425. return json_success('核销成功');
  3426. } catch (\Exception $e) {
  3427. dump($e->getMessage());
  3428. Db::rollBack();
  3429. _syslog("订单", "核销失败");
  3430. return json_fail('核销失败');
  3431. }
  3432. }
  3433. /**
  3434. * 核销餐饮
  3435. */
  3436. public function writeOffDishes(Request $request)
  3437. {
  3438. $orderId = $request->post('order_id', '');
  3439. $memberId = $request->post('member_id', '');
  3440. $times = $request->post('times', '');
  3441. $code = $request->post('sms_code', '');
  3442. if (!$memberId || !$orderId) {
  3443. return json_fail('参数异常');
  3444. }
  3445. $member = Member::find($memberId);
  3446. $mobile = $member->member_mobile;
  3447. $key = "SMS:CODE:DISHES:" . $mobile;
  3448. $redisCode = Redis::get($key);
  3449. if ($code == '' || $redisCode != $code) {
  3450. return json_fail("验证码错误,请重新输入");
  3451. }
  3452. Redis::del($key);
  3453. if (!$times) {
  3454. $times = date('Y-m-d H:i:s');
  3455. } else {
  3456. $times = date('Y-m-d H:i:s', strtotime($times));
  3457. }
  3458. try {
  3459. Db::beginTransaction();
  3460. // 记录核销
  3461. $params = [
  3462. 'dept_premises_id' => $request->post('dept_premises_id'),
  3463. 'order_remark' => $request->post('remark'),
  3464. 'write_off_member_id' => $request->post('write_off_member_id'),
  3465. 'join_order_member_id' => $memberId
  3466. ];
  3467. $writeOffData['charge'] = OrderService::generateWriteOffData($params);
  3468. $writeOffData['charge']['order_id'] = $orderId;
  3469. $writeOffData['charge']['member_id'] = $memberId;
  3470. $writeOffData['charge']['order_code'] = random_string(10, 'number');
  3471. $writeOffData['express'] = 'N';
  3472. $order = Order::where('order_id', $orderId)->first();
  3473. if (!empty($order->order_config_json)) {
  3474. $orderConfigJson = json_decode($order->order_config_json, true);
  3475. if (isset($orderConfigJson['tableid']) && !empty($orderConfigJson['tableid'])) {
  3476. SysDept::where('dept_id', $orderConfigJson['tableid'])->where('dept_category', '桌台')->update(['dept_status' => 'ACTIVED']);
  3477. }
  3478. }
  3479. Order::where('order_id', $orderId)->update([
  3480. 'order_express_json' => json_encode($writeOffData),
  3481. 'order_is_complete' => 'Y',
  3482. 'order_status_system' => 'DONE'
  3483. ]);
  3484. OrderSheet::where('join_sheet_order_id', $orderId)->update([
  3485. 'order_sheet_status' => 'DONE'
  3486. ]);
  3487. Db::commit();
  3488. _syslog("订单", "核销餐品成功");
  3489. return json_success('核销成功');
  3490. } catch (\Exception $e) {
  3491. dump($e->getMessage());
  3492. Db::rollBack();
  3493. _syslog("订单", "核销餐品失败");
  3494. return json_fail('核销失败');
  3495. }
  3496. }
  3497. public function writeOffBenefit(Request $request)
  3498. {
  3499. $memberId = $request->post('member_id', '');
  3500. $benefitList = $request->post('benefitList', []);
  3501. $times = $request->post('times', '');
  3502. $code = $request->post('sms_code', '');
  3503. if (!$memberId || empty($benefitList)) {
  3504. return json_fail('参数异常');
  3505. }
  3506. if (empty($code)) {
  3507. return json_fail('请输入验证码');
  3508. }
  3509. $benefitIds = [];
  3510. foreach ($benefitList as $benefit) {
  3511. if (isset($benefit['nbr']) && intval($benefit['nbr']) > 0) {
  3512. $benefitIds[] = $benefit['member_benefit_id'];
  3513. }
  3514. }
  3515. if (empty($benefitIds)) {
  3516. return json_fail("请填写有效的核销数量");
  3517. }
  3518. $member = Member::find($memberId);
  3519. $mobile = $member->member_mobile;
  3520. $key = "SMS:CODE:WRITE_OFF:" . $mobile;
  3521. $redisCode = Redis::get($key);
  3522. if ($redisCode != $code) {
  3523. return json_fail("验证码错误,请重新输入");
  3524. }
  3525. $benefits = MemberBenefit::whereIn('member_benefit_id', $benefitIds)
  3526. ->where('join_benefit_member_id', $memberId)
  3527. ->get()
  3528. ->toArray();
  3529. foreach ($benefits as $benefit) {
  3530. foreach ($benefitList as $list) {
  3531. if ($list['member_benefit_id'] == $benefit['member_benefit_id'] && intval($list['nbr'] > ($benefit['member_benefit_limit_count'] - $benefit['member_benefit_used_count']))) {
  3532. return json_fail('可核销数量不足');
  3533. }
  3534. }
  3535. }
  3536. if (!$times) {
  3537. $times = date('Y-m-d H:i:s');
  3538. } else {
  3539. $times = date('Y-m-d H:i:s', strtotime($times));
  3540. }
  3541. try {
  3542. Db::beginTransaction();
  3543. // 核销数据
  3544. $params = [
  3545. 'dept_premises_id' => $request->post('dept_premises_id'),
  3546. 'order_remark' => $request->post('remark'),
  3547. 'write_off_member_id' => $request->post('write_off_member_id'),
  3548. 'join_order_member_id' => $memberId
  3549. ];
  3550. $writeOffData = OrderService::generateWriteOffData($params);
  3551. // 开始减额度
  3552. foreach ($benefits as $benefit) {
  3553. foreach ($benefitList as $list) {
  3554. if ($list['member_benefit_id'] == $benefit['member_benefit_id']) {
  3555. $usedCount = $benefit['member_benefit_used_count'] + intval($list['nbr']);
  3556. // 用完了
  3557. if ($benefit['member_benefit_limit_count'] <= $usedCount && !empty($benefit['join_benefit_order_id'])) {
  3558. Order::where('order_id', $benefit['join_benefit_order_id'])->update(['order_status_system' => 'DONE']);
  3559. }
  3560. // 更新benefit 表
  3561. MemberBenefit::where('member_benefit_id', $benefit['member_benefit_id'])->update(['member_benefit_used_count' => $usedCount]);
  3562. // 更新Appointment 表
  3563. $appointments = Appointment::where('join_appointment_member_benefit_id', $benefit['member_benefit_id'])
  3564. ->where('appointment_status', 'INIT')
  3565. ->limit(intval($list['nbr']))
  3566. ->get();
  3567. foreach ($appointments as $appointment) {
  3568. Appointment::where('appointment_id', $appointment->appointment_id)->update([
  3569. 'appointment_status' => 'DONE',
  3570. 'appointment_datetime' => $times,
  3571. 'appointment_apply_datetime' => $times,
  3572. 'appointment_doing_datetime' => $times,
  3573. 'appointment_done_datetime' => $times,
  3574. 'appointment_done_json' => json_encode($writeOffData)
  3575. ]);
  3576. }
  3577. }
  3578. }
  3579. }
  3580. Redis::del($key);
  3581. Db::commit();
  3582. _syslog("订单", "核销成功");
  3583. return json_success('核销成功');
  3584. } catch (\Exception $e) {
  3585. dump($e->getMessage());
  3586. Db::rollBack();
  3587. _syslog("订单", "核销失败");
  3588. return json_fail('核销失败');
  3589. }
  3590. }
  3591. public function myOrder(Request $request)
  3592. {
  3593. $page = $request->get('page', 1);
  3594. $pageSize = $request->get('pageSize', 1);
  3595. $datetime = $request->get('order_addtimes', []);
  3596. $goodsName = $request->get('goods_name', '');
  3597. $memberId = $request->get('member_id', '');
  3598. if (!$memberId) {
  3599. return json_fail('查询错误');
  3600. }
  3601. $goodsIds = [];
  3602. if (!empty($goodsName)) {
  3603. $goodsIds = Goods::where('goods_name', 'like', '%' . $goodsName . '%')->pluck('goods_id')->toArray();
  3604. }
  3605. $sheet = OrderSheet::with([
  3606. 'goods' => function ($query) {
  3607. $query->select('goods_id', 'goods_name', 'goods_cover', 'goods_classify');
  3608. },
  3609. 'order' => function ($query) {
  3610. $query->select('order_id', 'order_status_system', 'order_status_payment', 'order_status_storage');
  3611. },
  3612. 'refund' => function ($query) {
  3613. $query->select('join_return_order_id', 'orders_return_id', 'order_return_status');
  3614. },
  3615. ])
  3616. ->leftJoin('order', 'order.order_id', 'order_sheet.join_sheet_order_id')
  3617. ->where('join_sheet_member_id', $memberId)
  3618. ->where('order.order_category', '<>', 'RECHARGE')
  3619. ->when(!empty($datetime), function ($query) use ($datetime) {
  3620. $datetime[0] = strtotime($datetime[0]);
  3621. $datetime[1] = strtotime($datetime[1]);
  3622. $query->whereBetween('order_sheet_addtimes', $datetime);
  3623. })
  3624. ->when(!empty($goodsIds), function ($query) use ($goodsIds) {
  3625. $query->whereIn('join_sheet_goods_id', $goodsIds);
  3626. });
  3627. $total = $sheet->count();
  3628. $rows = $sheet
  3629. ->orderBy('order_sheet_addtimes', 'desc')
  3630. ->forPage($page, $pageSize)
  3631. ->get()
  3632. ->toArray();
  3633. foreach ($rows as &$item) {
  3634. if (!empty($item->goods->goods_cover)) {
  3635. $item->goods->goods_cover = getenv('STORAGE_DOMAIN') . $item->goods->goods_cover;
  3636. }
  3637. }
  3638. return json_success('', compact('rows', 'page', 'pageSize', 'total'));
  3639. }
  3640. public function saveExpress($params)
  3641. {
  3642. try {
  3643. $express = new OrderExpress();
  3644. $express->order_express_type = $params['order_express_type'];
  3645. $express->join_express_order_id = $params['orderId'];
  3646. $express->join_express_dept_id = $params['submit_premises_id'] ?? 0;
  3647. $express->order_express_goods = $params['order_express_goods'];
  3648. $express->order_express_city = $params['order_express_city'];
  3649. $express->order_express_address = $params['order_express_address'];
  3650. $express->order_express_mobile = $params['order_express_mobile'] ?? '';
  3651. $express->order_express_telephone = $params['order_express_telephone'] ?? '';
  3652. $express->order_express_person = $params['order_express_person'] ?? '';
  3653. $express->order_express_company = $params['dept_premises_id'] ?? '';
  3654. $express->order_express_extend_json = $params['order_express_extend_json'] ?? '[]';
  3655. $express->order_express_addtimes = time();
  3656. $express->save();
  3657. } catch (\Exception $e) {
  3658. dump($e->getMessage());
  3659. throw new BusinessException('物流信息保存失败');
  3660. }
  3661. }
  3662. // TODO 确认收货(完成订单)
  3663. // public function confirm($id)
  3664. // {
  3665. // $order = Order::where('order_id', $id)->first();
  3666. // if (empty($order)) {
  3667. // return json_fail("暂无数据");
  3668. // }
  3669. //
  3670. // Db::beginTransaction();
  3671. // try {
  3672. // // 主订单
  3673. // Order::where('order_id', $id)->update(['order_status_system' => 'CONFIRM']);
  3674. // } catch (\Exception $e) {
  3675. //
  3676. // }
  3677. // }
  3678. /**
  3679. * @Desc 退款
  3680. * @Author Gorden
  3681. * @Date 2024/7/8 8:40
  3682. *
  3683. * @param Request $request
  3684. * @return Response
  3685. */
  3686. public function doRefund(Request $request)
  3687. {
  3688. $orderId = $request->post('order_id', '');
  3689. $amount = $request->post('refund_amount', 0);
  3690. $password = $request->post('refund_password', '');
  3691. if (!$orderId || !$amount || !$password) {
  3692. return json_fail('参数异常');
  3693. }
  3694. if ($password != '123456') {
  3695. return json_fail('支付密码错误');
  3696. }
  3697. $return = OrderReturn::where('join_return_order_id', $orderId)
  3698. ->first();
  3699. if (!$return) {
  3700. return json_fail("退款订单异常");
  3701. }
  3702. $order = Order::where('order_id', $return->join_return_order_id)->first();
  3703. if (!$order) {
  3704. return json_fail("订单异常");
  3705. }
  3706. if ($order->order_is_complete == 'Y' || $order->order_is_complete == 'R') {
  3707. return json_fail('订单已完成,无法退款');
  3708. }
  3709. if ($amount > $order->order_amount_pay) {
  3710. return json_fail('退款金额不能超过订单金额');
  3711. }
  3712. $payDetail = PayDetail::where('join_pay_order_id', $order->order_groupby)->where('pay_status', 'SUCCESS')->first();
  3713. if (!$payDetail) {
  3714. return json_fail("支付信息异常异常");
  3715. }
  3716. // 在线支付返回
  3717. $payJsonResponse = [];
  3718. if (!empty($payDetail->pay_json_response)) {
  3719. $payJsonResponse = json_decode($payDetail->pay_json_response, true);
  3720. }
  3721. $res = '[]';
  3722. $data = '[]';
  3723. try {
  3724. Db::beginTransaction();
  3725. // 订单主表
  3726. Order::where('order_id', $return->join_return_order_id)->update(['order_is_complete' => 'R']);
  3727. // 订单详情
  3728. OrderSheet::where('join_sheet_order_id', $return->join_return_order_id)->update(['order_sheet_status' => 'RETURNED']);
  3729. // return 表
  3730. $return->order_return_status = 'DONE';
  3731. $return->order_return_refund_json = json_encode(['amount' => $amount, 'datetime' => date('Y-m-d H:i:s'), 'user_id' => JwtToken::getCurrentId()]);
  3732. $return->save();
  3733. $payType = explode('-', $payDetail->pay_prepayid);
  3734. // 区分账户余额支付和在线支付
  3735. if ($payDetail->pay_prepayid == 'WXPAY') {
  3736. // 退款
  3737. $data = [
  3738. 'type' => 'app',
  3739. 'out_trade_no' => $order->order_groupby,
  3740. 'out_refund_no' => $return->orders_return_id,
  3741. 'total_fee' => $payDetail->pay_amount * 100,
  3742. 'refund_fee' => $amount * 100,
  3743. 'refund_desc' => '退款',
  3744. ];
  3745. $res = Pay::wechat(config('payment.wxpay'))->refund($data);
  3746. $resArray = json_decode($res, true);
  3747. if (!$resArray['result_code'] == 'SUCCESS' || !$resArray['return_code'] == 'SUCCESS') {
  3748. throw new PayException("退款失败");
  3749. }
  3750. } else if ($payDetail->pay_prepayid == 'ALIPAY') {
  3751. // 退款
  3752. $data = [
  3753. 'out_trade_no' => $order->order_groupby,
  3754. 'refund_amount' => $amount,
  3755. ];
  3756. $res = Pay::alipay(config('payment.alipay'))->refund($data);
  3757. $resArray = json_decode($res, true);
  3758. if ($resArray['fund_change'] != 'Y' || $resArray['msg'] != 'Success') {
  3759. throw new PayException("退款失败");
  3760. }
  3761. } else if (isset($payType[1]) && $payType[1] == 'CASH') { // 余额支付
  3762. $account = MemberAccount::where('join_account_member_id', $order->join_order_member_id)
  3763. ->where('member_account_classify', 'CASH')
  3764. ->first();
  3765. $account->member_account_expend = $account->member_account_expend - $amount;
  3766. $account->member_account_surplus = $account->member_account_surplus + $amount;
  3767. $account->save();
  3768. $data = [
  3769. 'type' => 'REFUND',
  3770. 'member_id' => $order->join_order_member_id,
  3771. 'order_id' => $return->join_return_order_id,
  3772. 'return_id' => $return->orders_return_id
  3773. ];
  3774. $res = json_encode([
  3775. 'status' => 'SUCCESS'
  3776. ]);
  3777. } else if (isset($payType[1]) && $payType[1] == 'WELFARE') { // 员工福利支付
  3778. $account = MemberAccount::where('join_account_member_id', $order->join_order_member_id)
  3779. ->where('member_account_classify', 'WELFARE')
  3780. ->first();
  3781. $account->member_account_expend = $account->member_account_expend - $amount;
  3782. $account->member_account_surplus = $account->member_account_surplus + $amount;
  3783. $account->save();
  3784. $data = [
  3785. 'type' => 'REFUND',
  3786. 'member_id' => $order->join_order_member_id,
  3787. 'order_id' => $return->join_return_order_id,
  3788. 'return_id' => $return->orders_return_id
  3789. ];
  3790. $res = json_encode([
  3791. 'status' => 'SUCCESS'
  3792. ]);
  3793. } else if (count($payType) == 1 && !in_array($payDetail->pay_prepayid, ['W06', 'A01'])) { // 卡支付
  3794. $account = MemberAccount::where('join_account_member_id', $order->join_order_member_id)
  3795. ->where('member_account_nbr', $payType[0])
  3796. ->where('member_account_classify', 'CARD')
  3797. ->first();
  3798. $account->member_account_expend = $account->member_account_expend - $amount;
  3799. $account->member_account_surplus = $account->member_account_surplus + $amount;
  3800. $account->save();
  3801. $data = [
  3802. 'type' => 'REFUND',
  3803. 'nbr' => $account->member_account_nbr,
  3804. 'member_id' => $order->join_order_member_id,
  3805. 'order_id' => $return->join_return_order_id,
  3806. 'return_id' => $return->orders_return_id
  3807. ];
  3808. $res = json_encode([
  3809. 'status' => 'SUCCESS'
  3810. ]);
  3811. }
  3812. // 生成payDetail
  3813. $payDetailData = [
  3814. 'join_pay_member_id' => $order->join_order_member_id,
  3815. 'join_pay_order_id' => $order->order_groupby,
  3816. 'pay_status' => 'SUCCESS',
  3817. 'pay_category' => 'REFUND',
  3818. 'pay_amount' => $amount,
  3819. 'pay_paytimes' => date('Y-m-d H:i:s'),
  3820. 'pay_json_request' => json_encode($data),
  3821. 'pay_json_response' => $res,
  3822. 'pay_prepayid' => $payType[0] . (!empty($payType[1]) ? '-' . $payType[1] : ''),
  3823. 'pay_addtimes' => time()
  3824. ];
  3825. PayDetail::insert($payDetailData);
  3826. Db::commit();
  3827. // 事件通知
  3828. Event::dispatch('client_message.refund', $order->join_order_member_id);
  3829. _syslog("退款", "发起退款", json_decode($res), $data);
  3830. return json_success("退款成功");
  3831. } catch (PayException $e) {
  3832. Db::rollBack();
  3833. dump($e->getMessage());
  3834. dump($e->getTrace());
  3835. _syslog("退款", "发起退款", $e->getMessage(), $data);
  3836. return json_fail($e->getMessage());
  3837. } catch (\Exception $e) {
  3838. Db::rollBack();
  3839. dump($e->getMessage());
  3840. dump($e->getTrace());
  3841. _syslog("退款", "发起退款", $e->getMessage(), $data);
  3842. if (strpos($e->getMessage(), '余额不足') !== false) {
  3843. return json_fail("基本账户余额不足,请充值后重新发起");
  3844. }
  3845. return json_fail("数据更新失败");
  3846. }
  3847. }
  3848. public function exportOrder(Request $request)
  3849. {
  3850. $type = $request->get('type', '');
  3851. [$where, $format, $limit, $field, $order] = $this->selectInput($request);
  3852. $where['order_category'] = ['<>', 'RECHARGE'];
  3853. if (!empty($request->get('order_ids'))) {
  3854. $where['order_id'] = ['in', $request->get('order_ids')];
  3855. }
  3856. if (!empty($where['order_addtimes'])) {
  3857. $where['order_addtimes'][0] = strtotime($where['order_addtimes'][0]);
  3858. $where['order_addtimes'][1] = strtotime($where['order_addtimes'][1]);
  3859. }
  3860. if ($type == 'todayOrder' && empty($where['order_addtimes'])) {
  3861. $where['order_addtimes'][0] = strtotime(date('Y-m-d') . ' 00:00:00');
  3862. $where['order_addtimes'][1] = strtotime(date('Y-m-d') . ' 23:59:59');
  3863. } else if ($type == 'todayOrderAmount') {
  3864. $todayTimeUnix = strtotime(date('Y-m-d') . ' 00:00:00');
  3865. $groupIds = PayDetail::whereRaw('CAST(UNIX_TIMESTAMP(pay_paytimes) as SIGNED) > ? ', [$todayTimeUnix])
  3866. ->where('join_pay_order_id', '<>', '')
  3867. ->where('pay_category', '<>', 'RETURN')
  3868. ->where('pay_category', '<>', 'RECHARGE')
  3869. ->where('pay_category', '<>', 'CLEAR')
  3870. ->pluck('join_pay_order_id')
  3871. ->toArray();
  3872. $where['order_groupby'] = ['in', $groupIds];
  3873. }
  3874. if ($request->get('goods_classify') || $request->get('goods_name')) {
  3875. $where['order_id'] = '';
  3876. $goodsClassify = $request->get('goods_classify', '');
  3877. $goodsName = $request->get('goods_name', '');
  3878. if (!empty($goodsName) && empty($goodsClassify)) {
  3879. $goodsIds = Goods::where('goods_name', 'like', '%' . $request->get('goods_name') . '%')->pluck('goods_id')->toArray();
  3880. } else if (!empty($goodsClassify)) {
  3881. if ($goodsClassify == 'SERVICE') {
  3882. $goodsModel = Goods::whereIn('goods_classify', ['SERVICE', 'CHNMED', 'CHNNCD']);
  3883. } else {
  3884. $goodsModel = Goods::where('goods_classify', $goodsClassify);
  3885. }
  3886. if (!empty($goodsName)) {
  3887. $goodsModel->where('goods_name', 'like', '%' . $goodsName . '%');
  3888. }
  3889. $goodsIds = $goodsModel->pluck('goods_id')->toArray();
  3890. }
  3891. if ($goodsIds) {
  3892. $orderIds = OrderSheet::whereIn('join_sheet_goods_id', $goodsIds)->pluck('join_sheet_order_id')->toArray();
  3893. if ($orderIds) {
  3894. $where['order_id'] = ['in', implode(',', $orderIds)];
  3895. }
  3896. }
  3897. }
  3898. $order = $request->get('order', 'desc');
  3899. $field = $field ?? 'order_addtimes';
  3900. if (!empty($where['order_status_system']) && in_array($where['order_status_system'], ['PENDING', 'WAITING', 'SENDING', 'RECVING', 'SIGNED', 'CONFIRM'])) {
  3901. $where['order_is_complete'] = 'N';
  3902. }
  3903. if (!empty($where['order_status_system']) && $where['order_status_system'] == 'RETURN') {
  3904. unset($where['order_status_system']);
  3905. unset($where['order_is_complete']);
  3906. $where['order_category'] = 'RETURN';
  3907. }
  3908. $query = $this->doSelect($where, $field, $order);
  3909. _syslog("订单", "导出订单");
  3910. return $this->exportDoFormat($query, $format, 1000);
  3911. }
  3912. /**
  3913. * 执行真正查询,并返回格式化数据
  3914. * @param $query
  3915. * @param $format
  3916. * @param $limit
  3917. * @return Response
  3918. */
  3919. protected function exportDoFormat($query, $format, $limit): Response
  3920. {
  3921. $methods = [
  3922. 'select' => 'formatSelect',
  3923. 'tree' => 'formatTree',
  3924. 'table_tree' => 'formatTableTree',
  3925. 'normal' => 'formatNormal',
  3926. ];
  3927. $paginator = $query->paginate($limit);
  3928. $total = $paginator->total();
  3929. $items = $paginator->items();
  3930. $items = call_user_func([$this, "exportAfterQuery"], $items);
  3931. $format_function = $methods[$format] ?? 'formatNormal';
  3932. return call_user_func([$this, $format_function], $items, $total);
  3933. }
  3934. public function benefitList(Request $request)
  3935. {
  3936. $orderIds = $request->get('order_ids', []);
  3937. if (empty($orderIds)) {
  3938. return json_fail("请选择需要核销的订单");
  3939. }
  3940. $orders = order::whereIn('order_id', $orderIds)
  3941. ->with([
  3942. 'benefit' => function ($query) {
  3943. $query->select('join_benefit_order_id', 'member_benefit_id', 'member_benefit_name', 'member_benefit_limit_count', 'member_benefit_used_count');
  3944. },
  3945. 'member' => function ($query) {
  3946. $query->select('member_id', 'member_mobile');
  3947. },
  3948. // 'sheets'=>function($query){
  3949. // $query->select('join_sheet_order_id','join_sheet_goods_id');
  3950. // }
  3951. // 'goods'=>function($query){
  3952. // $query->select('goods_id','goods_name');
  3953. // }
  3954. ])
  3955. ->select('order_id', 'join_order_member_id', 'order_is_complete', 'order_status_system')
  3956. ->where("order_is_complete", 'N')
  3957. ->whereIn("order_category", ['NORMAL', 'SYSTEM'])
  3958. ->orderBy('order_addtimes', 'DESC')
  3959. ->get()
  3960. ->toArray();
  3961. $memberId = array_unique(array_column($orders, 'join_order_member_id'));
  3962. if (count($memberId) > 1) {
  3963. return json_fail("不可同时核销多人订单");
  3964. }
  3965. $data = [];
  3966. foreach ($orders as $order) {
  3967. $orderOne = $order;
  3968. foreach ($order['benefit'] as $benefit) {
  3969. $benefit['member_benefit_limit_count'] = intval($benefit['member_benefit_limit_count']);
  3970. $benefit['member_benefit_used_count'] = intval($benefit['member_benefit_used_count']);
  3971. $benefit['unused'] = $benefit['member_benefit_limit_count'] - $benefit['member_benefit_used_count'];
  3972. $orderOne['benefit'] = $benefit;
  3973. $orderOne['member_benefit_id'] = $benefit['member_benefit_id'];
  3974. $data[] = $orderOne;
  3975. }
  3976. }
  3977. if (empty($data)) {
  3978. return json_fail("您选择的产品没有可核销的服务");
  3979. }
  3980. return json_success('', $data);
  3981. }
  3982. public function chooseBenefitList(Request $request)
  3983. {
  3984. $benefitIds = $request->get('benefit_ids', []);
  3985. $memberId = $request->get('member_id', []);
  3986. if (empty($benefitIds)) {
  3987. return json_fail('请选择需要核销的服务');
  3988. }
  3989. if (empty($memberId)) {
  3990. return json_fail('没有会员信息,请联系管理员');
  3991. }
  3992. $benefits = MemberBenefit::whereIn('member_benefit_id', $benefitIds)
  3993. ->where('member_benefit_status', 'ACTIVED')
  3994. ->where('join_benefit_member_id', $memberId)
  3995. ->select('join_benefit_order_id', 'member_benefit_id', 'member_benefit_name', 'member_benefit_limit_count', 'member_benefit_used_count')
  3996. ->orderBy('member_benefit_addtimes', 'DESC')
  3997. ->get()
  3998. ->toArray();
  3999. foreach ($benefits as &$benefit) {
  4000. $benefit['member_benefit_limit_count'] = intval($benefit['member_benefit_limit_count']);
  4001. $benefit['member_benefit_used_count'] = intval($benefit['member_benefit_used_count']);
  4002. $benefit['unused'] = $benefit['member_benefit_limit_count'] - $benefit['member_benefit_used_count'];
  4003. }
  4004. $member = Member::where('member_id', $memberId)->select('member_id', 'member_mobile')->first()->toArray();
  4005. return json_success('', ['benefits' => $benefits, 'member' => $member]);
  4006. }
  4007. public function customPrinter(Request $request)
  4008. {
  4009. $orderId = $request->post('order_id', '');
  4010. $printer = $request->post('printer', []);
  4011. $premiseName = $request->post('premise', '');
  4012. if (empty($orderId) || empty($premiseName)) {
  4013. return json_fail('参数异常');
  4014. }
  4015. if (empty($printer)) {
  4016. return json_fail('请选择打印设备');
  4017. }
  4018. $premises = SysDept::where('dept_name', $premiseName)->where('dept_category', '营业场所')->where('dept_status', 'ACTIVED')->first();
  4019. $restaurant = SysDept::where('dept_name', $premiseName)->where('dept_category', '餐厅')->where('dept_status', 'ACTIVED')->first();
  4020. $order = Order::where('order_id', $orderId)->first();
  4021. try {
  4022. foreach ($printer as $print) {
  4023. if (strpos($print, '结算') !== false && $order->order_status_payment != 'SUCCESS') {
  4024. return json_fail('无法打印未支付的结账单');
  4025. }
  4026. if (!empty($premises) || $restaurant) {
  4027. if (empty($restaurant)) {
  4028. $restaurant = SysDept::where('dept_super_id', $premises->dept_id)->where('dept_category', '餐厅')->first();
  4029. }
  4030. if (!empty($restaurant->dept_extend_json)) {
  4031. $deptExtendJson = json_decode($restaurant->dept_extend_json, true);
  4032. $voteData = [
  4033. 'func' => 'procActionToPrinter',
  4034. 'sign' => '',
  4035. 'data' => [
  4036. 'printer_premises' => $restaurant->dept_id,
  4037. 'printer_device' => [
  4038. $print
  4039. ],
  4040. 'printer_action' => 'ExecPrintOrder',
  4041. 'printer_data' => [
  4042. 'order_id' => $orderId
  4043. ]
  4044. ]
  4045. ];
  4046. http_post_json(getenv('VOTE_MENU_URL'), $voteData);
  4047. }
  4048. }
  4049. }
  4050. return json_success('打印完成');
  4051. } catch (\Exception $e) {
  4052. return json_fail("存在错误,票据未全部打印");
  4053. }
  4054. }
  4055. protected function exportAfterQuery($items)
  4056. {
  4057. $data = [];
  4058. foreach ($items as $key => $item) {
  4059. $goodsClassify = '';
  4060. $goodsName = '--';
  4061. if (!empty($item['sheet'])) {
  4062. $goods = Goods::where('goods_id', $item['sheet']['join_sheet_goods_id'])->first();
  4063. $goodsClassify = $goods->goods_classify ?? '';
  4064. $goodsName = $goods->goods_name ?? '--';
  4065. }
  4066. $systemStatus = '';
  4067. if ($item['order_is_complete'] == 'Y') {
  4068. $systemStatus = '已完成';
  4069. } elseif ($item['order_is_complete'] == 'R') {
  4070. $systemStatus = '售后已完成';
  4071. }
  4072. if ($item['order_is_complete'] != 'R' && !empty($item['order_return_status']) && $item['order_return_status'] == 'PENDING') {
  4073. $systemStatus = '待处理';
  4074. } elseif ($item['order_is_complete'] != 'R' && !empty($item['order_return_status']) && $item['order_return_status'] == 'DOING') {
  4075. $systemStatus = '退款中';
  4076. } elseif ($item['order_is_complete'] != 'R' && !empty($item['order_return_status']) && $item['order_return_status'] == 'DONE') {
  4077. $systemStatus = '退款完成';
  4078. } elseif ($item['order_is_complete'] != 'R' && !empty($item['order_return_status']) && $item['order_return_status'] == 'DISAGREE') {
  4079. $systemStatus = '不同意退款';
  4080. }
  4081. $payDetails = PayDetail::where('join_pay_order_id', $item['order_groupby'])
  4082. ->where('pay_status', 'SUCCESS')
  4083. ->where('pay_category', '<>', 'REFUND')
  4084. ->get()
  4085. ->toArray();
  4086. if (count($payDetails) > 1) {
  4087. $payWay = '组合支付';
  4088. } elseif (count($payDetails) == 1) {
  4089. $payWayEn = OrderService::getPayWayByPrepayId($payDetails[0]['pay_prepayid']);
  4090. $payWay = '';
  4091. if (!empty($payWayEn)) {
  4092. $payWay = OrderService::$payWay[$payWayEn];
  4093. }
  4094. }
  4095. if (count($payDetails) > 0) {
  4096. $payDetail0 = $payDetails[0];
  4097. $payTimes = $payDetail0['pay_paytimes'];
  4098. }
  4099. if ($item['member']['member_mobile'] == '0000') {
  4100. $memberName = '散客';
  4101. } else {
  4102. $memberName = (!empty($item['cert']) ? $item['cert']['member_cert_name'] : substr($item['member']['member_mobile'], -4) . '用户') . '-' . $item['member']['member_mobile'];
  4103. }
  4104. $data[$key] = [
  4105. 'goods_classify' => !empty($goodsClassify) && isset(self::$goodsClassify[$goodsClassify]) ? self::$goodsClassify[$goodsClassify] : '其他订单',
  4106. 'order_id' => $item['order_id'],
  4107. 'member' => $memberName,
  4108. 'goods_name' => $goodsName,
  4109. 'nbr' => !empty($item['sheet']) ? intval($item['sheet']['order_sheet_num']) : '--',
  4110. 'order_amount_total' => $item['order_amount_total'],
  4111. 'order_amount_pay' => $item['order_amount_pay'],
  4112. 'order_status_system' => !empty($systemStatus) ? $systemStatus : self::$systemStatus[$item['order_status_system']],
  4113. 'order_status_payment' => self::$paymentStatus[$item['order_status_payment']],
  4114. 'pay_way' => $item['order_status_payment'] == 'SUCCESS' ? ($payWay ?? '') : '',
  4115. 'pay_times' => $item['order_status_payment'] == 'SUCCESS' || $item['order_status_payment'] == 'FREE' ? ($payTimes ?? '') : '',
  4116. 'order_addtimes' => date('Y-m-d H:i:s', strtotime($item['order_addtimes'])),
  4117. ];
  4118. }
  4119. return $data;
  4120. }
  4121. /**
  4122. * @Desc 查询订单状态
  4123. * @Author Gorden
  4124. * @Date 2024/8/19 11:55
  4125. *
  4126. * @param Request $request
  4127. * @return Response|void
  4128. */
  4129. public function getOrderPayStatus(Request $request)
  4130. {
  4131. $orderId = $request->get('order_id', '');
  4132. if (!$orderId) {
  4133. return json_fail('订单不存在');
  4134. }
  4135. $order = Order::where('order_id', $orderId)->first();
  4136. if (!$order) {
  4137. return json_fail('订单不存在');
  4138. }
  4139. if ($order->order_status_payment == 'SUCCESS') {
  4140. return json_success('success');
  4141. }
  4142. $payDetailType = PayDetail::where('join_pay_order_id', $order->order_groupby)->pluck('pay_prepayid')->toArray();
  4143. try {
  4144. Db::beginTransaction();
  4145. if (in_array('WXPAY', $payDetailType)) {
  4146. $result = Pay::wechat(config('payment.wxpay'))->find($order->order_groupby, 'pos');
  4147. $result = json_decode(json_encode($result), true);
  4148. if (!empty($result['return_code']) && $result['return_code'] == 'SUCCESS' && !empty($result['result_code']) && $result['result_code'] == 'SUCCESS' && !empty($result['trade_state']) && $result['trade_state'] == 'SUCCESS') {
  4149. if (in_array($order->order_category, ['SERVICE', 'CHNMED', 'CHNNCD', 'DISHES', 'MEALS', 'VIP'])) {
  4150. $order->order_is_complete = 'Y';
  4151. $order->order_status_system = 'DONE';
  4152. $order->order_status_payment = 'SUCCESS';
  4153. } else {
  4154. $order->order_status_system = 'SENDING';
  4155. }
  4156. $order->save();
  4157. // Sheet
  4158. OrderSheet::where('join_sheet_order_id', $orderId)->where('order_sheet_status', 'PAYING')->update(['order_sheet_status' => 'DONE']);
  4159. // 支付记录
  4160. PayDetail::where('join_pay_order_id', $order->order_groupby)->where('pay_prepayid', 'WXPAY')->update(['pay_status' => 'SUCCESS']);
  4161. Db::commit();
  4162. return json_success('success');
  4163. }
  4164. } else if (in_array('ALIPAY', $payDetailType)) {
  4165. $result = Pay::alipay(config('payment.alipay'))->find($order->order_groupby);
  4166. $result = json_decode(json_encode($result), true);
  4167. if (!empty($result['code']) && $result['code'] == '10000' && !empty($result['trade_status']) && $result['trade_status'] == 'TRADE_SUCCESS') {
  4168. if (in_array($order->order_category, ['SERVICE', 'CHNMED', 'CHNNCD', 'DISHES', 'MEALS', 'VIP'])) {
  4169. $order->order_is_complete = 'Y';
  4170. $order->order_status_system = 'DONE';
  4171. $order->order_status_payment = 'SUCCESS';
  4172. } else {
  4173. $order->order_status_system = 'SENDING';
  4174. }
  4175. $order->save();
  4176. // Sheet
  4177. OrderSheet::where('join_sheet_order_id', $orderId)->where('order_sheet_status', 'PAYING')->update(['order_sheet_status' => 'DONE']);
  4178. // 支付记录
  4179. PayDetail::where('join_pay_order_id', $order->order_groupby)->where('pay_prepayid', 'ALIPAY')->update(['pay_status' => 'SUCCESS']);
  4180. Db::commit();
  4181. return json_success('success');
  4182. }
  4183. }
  4184. Db::rollBack();
  4185. return json_fail('没有查询到记录');
  4186. } catch (\Exception $e) {
  4187. Db::rollBack();
  4188. return json_fail('查询失败');
  4189. }
  4190. }
  4191. /**
  4192. * @Desc 修改订单状态-挂账
  4193. * @Author Gorden
  4194. * @Date 2024/8/20 15:58
  4195. *
  4196. * @param Request $request
  4197. * @return Response
  4198. */
  4199. public function updateStatus(Request $request)
  4200. {
  4201. $orderId = $request->post('order_id', '');
  4202. $orderStatusPayment = $request->post('order_status_payment', '');
  4203. $freeRemark = $request->post('free_remark', '');
  4204. $order = Order::where('order_id', $orderId)
  4205. ->select('order_id', 'order_groupby', 'order_status_payment', 'order_config_json', 'order_amount_total', 'order_discount_json', 'order_extend_json')
  4206. ->first();
  4207. Db::beginTransaction();
  4208. try {
  4209. if ($orderStatusPayment == 'AWAITING' && $order->order_status_payment != 'PENDING') {
  4210. throw new BusinessException("当前订单不允许挂账");
  4211. } else if ($orderStatusPayment == 'FREE' && $order->order_status_payment != 'PENDING') {
  4212. throw new BusinessException("当前订单不允许免单");
  4213. }
  4214. // 挂账,释放餐桌
  4215. if (in_array($orderStatusPayment, ['AWAITING', 'FREE'])) {
  4216. $order->order_status_payment = $orderStatusPayment;
  4217. // 如果有餐桌,释放
  4218. if (!empty($order->order_config_json)) {
  4219. $orderConfigJson = json_decode($order->order_config_json, true);
  4220. if (!empty($orderConfigJson['tableid'])) {
  4221. SysDept::where('dept_id', $orderConfigJson['tableid'])->update(['dept_status' => 'ACTIVED']);
  4222. }
  4223. }
  4224. }
  4225. if ($orderStatusPayment == 'FREE') {
  4226. $orderDiscountJson = [];
  4227. if (!empty($order->order_discount_json)) {
  4228. $orderDiscountJson = json_decode($order->order_discount_json, true);
  4229. }
  4230. $orderDiscountJson[date('Y-m-d H:i:s')] = [
  4231. 'coupon_id' => null,
  4232. 'coupon_value' => $order->order_amount_total,
  4233. 'coupon_classify' => '免单',
  4234. 'coupon_detail_id' => ['免单'],
  4235. 'coupon_classify_en' => ['free']
  4236. ];
  4237. $orderExtendJson = [];
  4238. if (!empty($order->order_extend_json)) {
  4239. $orderExtendJson = json_decode($order->order_extend_json, true);
  4240. }
  4241. $orderExtendJson['free_remark'] = $freeRemark;
  4242. $order->order_discount_json = json_encode($orderDiscountJson, JSON_UNESCAPED_UNICODE);
  4243. $order->order_extend_json = json_encode($orderExtendJson, JSON_UNESCAPED_UNICODE);
  4244. $order->order_is_complete = 'Y';
  4245. $order->order_status_system = 'DONE';
  4246. $order->order_amount_pay = 0;
  4247. // sheet表
  4248. OrderSheet::where('join_sheet_order_id', $orderId)->update(['order_sheet_status' => 'DONE']);
  4249. // payDetail 表
  4250. PayDetail::where('join_pay_order_id', $order->order_groupby)
  4251. ->update([
  4252. 'pay_status' => 'SUCCESS',
  4253. 'pay_amount' => 0,
  4254. 'pay_prepayid' => 'MONEY',
  4255. 'pay_paytimes' => date('Y-m-d H:i:s')
  4256. ]);
  4257. }
  4258. $order->save();
  4259. Db::commit();
  4260. return json_success('success');
  4261. } catch (BusinessException $e) {
  4262. Db::rollBack();
  4263. return json_fail($e->getMessage());
  4264. } catch (\Exception $e) {
  4265. Db::rollBack();
  4266. return json_fail('修改订单状态失败');
  4267. }
  4268. }
  4269. public function useCoupon(Request $request)
  4270. {
  4271. $goods = $request->post('goods', []);
  4272. $coupon = $request->post('coupon', []);
  4273. $payAmount = $request->post('pay_amount', 0);
  4274. $memberId = $request->post('member_id', '');
  4275. $settlementNow = $request->post('settlement_now', 'N');
  4276. if (empty($goods) || empty($coupon) || empty($memberId)) {
  4277. return json_fail("参数异常");
  4278. }
  4279. foreach ($coupon as $item) {
  4280. if (!in_array(substr($item, 0, 2), ['CU', 'CO'])) {
  4281. return json_fail("参数异常");
  4282. }
  4283. }
  4284. $amountBalance = [
  4285. 'pay_amount' => $payAmount,
  4286. 'welfare_balance' => 0,
  4287. 'cut_balance' => 0,
  4288. ];
  4289. foreach ($goods as $good) {
  4290. $result = OrderService::chooseCoupon($settlementNow, $memberId, $goods, $good, $coupon, $amountBalance);
  4291. $amountBalance = [
  4292. 'pay_amount' => $result['pay_amount'],
  4293. 'welfare_balance' => $result['welfare_balance'],
  4294. 'cut_balance' => $result['cut_balance'],
  4295. ];
  4296. }
  4297. Redis::del("ORDER:USE:COUPON:" . $memberId);
  4298. return json_success("success", ['pay_amount' => $amountBalance['pay_amount']]);
  4299. }
  4300. /**
  4301. * @Desc 订单的核销记录
  4302. * @Author Gorden
  4303. * @Date 2024/9/13 14:28
  4304. *
  4305. * @param Request $request
  4306. * @return Response
  4307. */
  4308. public function writeOffList(Request $request)
  4309. {
  4310. $orderId = $request->get('order_id');
  4311. $page = $request->get('page', 1);
  4312. $pageSize = $request->get('pageSize', 20);
  4313. if (!$orderId) {
  4314. return json_fail("参数异常");
  4315. }
  4316. $appointments = Appointment::with([
  4317. 'member' => function ($query) {
  4318. $query->select('member_id', 'member_mobile');
  4319. },
  4320. 'memberInfo',
  4321. 'cert',
  4322. 'goods' => function ($query) {
  4323. $query->select('goods_id', 'goods_name');
  4324. }
  4325. ])->where('join_appointment_order_id', $orderId)
  4326. ->where('appointment_status', 'DONE')
  4327. ->select('join_appointment_member_id', 'join_appointment_goods_id','appointment_done_datetime','appointment_done_json');
  4328. $total = $appointments->count();
  4329. $rows = $appointments->forPage($page, $pageSize)
  4330. ->orderBy('appointment_done_datetime', 'DESC')
  4331. ->get();
  4332. foreach ($rows as &$item){
  4333. $memberMobile = '';
  4334. if (!empty($item['member']) && !empty($item['member']['member_mobile'])){
  4335. $memberMobile = $item['member']['member_mobile'];
  4336. }
  4337. $memberNickname = '';
  4338. if (!empty($item['member_info']) && !empty($item['member_info']['member_info_nickname'])){
  4339. $memberNickname = $item['member_info']['member_info_nickname'];
  4340. }
  4341. $memberName = '';
  4342. if (!empty($item['cert']) && !empty($item['cert']['member_cert_name'])){
  4343. $memberName = $item['cert']['member_cert_name'];
  4344. }
  4345. unset($item['member'],$item['member_info'],$item['cert']);
  4346. $item['member_name'] = MemberService::getMemberName($memberMobile,$memberName,$memberNickname);
  4347. if (!empty($item['appointment_done_json'])){
  4348. $doneJson = json_decode($item['appointment_done_json'],true);
  4349. if (isset($doneJson['charge']) && !empty($doneJson['charge']['charge_user_id'])){
  4350. $item['username'] = SysUser::where('user_id',$doneJson['charge']['charge_user_id'])->value('user_name');
  4351. }
  4352. if (isset($doneJson['charge']) && !empty($doneJson['charge']['charge_premises'])){
  4353. $item['premise'] = $doneJson['charge']['charge_premises'];
  4354. }
  4355. $item['nbr'] = 1;
  4356. }
  4357. }
  4358. return json_success('', compact('rows', 'page', 'pageSize', 'total'));
  4359. }
  4360. public static $goodsClassify = [
  4361. // goodsClassify: {GOODS:"健康产品订单",SERVICE:"服务订单",DEVICE:"设备订单",SPECIAL:"专题业务订单",PACKAGE:"套餐订单",RECHARGE:"充值订单",OTHER:"其他订单"},
  4362. 'GOODS' => "产品订单",
  4363. 'SERVICE' => "服务订单",
  4364. 'CHNMED' => '服务订单',
  4365. 'CHNNCD' => '服务订单',
  4366. 'DEVICE' => '设备订单',
  4367. 'SPECIAL' => '专题业务订单',
  4368. 'PACKAGE' => '套包订单',
  4369. 'RECHARGE' => '充值订单',
  4370. 'OTHER' => '其他订单',
  4371. 'DISHES' => '餐饮订单',
  4372. 'MEALS' => '餐饮订单',
  4373. 'VIP' => '康养城订单'
  4374. ];
  4375. // systemStatus: {BEING:"待生效",PAYING:"待支付",PENDING:"待确认",WAITING:"待受理",SENDING:"待发货",RECVING:"待收货",SIGNED:"已签收",CONFIRM:"确认收货"},
  4376. // paymentStatus: {PENDING:"待支付",CANCEL:"取消支付",SUCCESS:"支付成功"},
  4377. public static $systemStatus = [
  4378. 'BEING' => '待生效',
  4379. 'PAYING' => "待支付",
  4380. 'PENDING' => "待确认",
  4381. 'WAITING' => "待使用",
  4382. 'SENDING' => "待发货",
  4383. 'RECVING' => "待收货",
  4384. 'SIGNED' => "已签收",
  4385. 'CONFIRM' => "确认收货",
  4386. 'DONE' => '已完成',
  4387. 'CANCEL' => '已取消'
  4388. ];
  4389. public static $paymentStatus = [
  4390. 'WAITING' => "待支付",
  4391. 'PENDING' => "待支付",
  4392. 'CANCEL' => "取消支付",
  4393. 'SUCCESS' => "支付成功",
  4394. 'AWAITING' => "挂账",
  4395. 'FREE' => "免单"
  4396. ];
  4397. }