WholeController.php 268 KB

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