WholeController.php 245 KB

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