WholeController.php 286 KB

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