WholeController.php 244 KB

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