WholeController.php 285 KB

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