WholeController.php 244 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881
  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. $this->changeOrderCouponStatus(json_decode($couponUseJson, true), 'WAITING');
  1252. return json_throw(2001, '支付异常', ['order_id' => $params['orderId']]);
  1253. }
  1254. _syslog("订单", "订单支付成功");
  1255. return json_success('支付成功');
  1256. } catch (BusinessException $e) {
  1257. dump($e->getMessage());
  1258. Db::rollBack();
  1259. _syslog("订单", "订单支付失败:" . $e->getMessage());
  1260. return json_fail("支付失败:" . $e->getMessage());
  1261. } catch (\Exception $e) {
  1262. dump($e->getMessage());
  1263. Db::rollBack();
  1264. _syslog("订单", "订单支付失败");
  1265. return json_fail('支付失败');
  1266. }
  1267. }
  1268. private function discountRecord($orderDiscountJson, $params)
  1269. {
  1270. $json = [];
  1271. if (!empty($orderDiscountJson)) {
  1272. $json = json_decode($orderDiscountJson, true);
  1273. }
  1274. try {
  1275. if (!empty($params['preferential']) && in_array('wipe', $params['preferential'])) {
  1276. if (intval($params['order_amount_total'] / 10) * 10 != $params['order_amount_pay']) {
  1277. throw new BusinessException("抹零后实际支付金额错误");
  1278. }
  1279. $params['order_discount_amount'] = $params['order_amount_total'] - $params['order_amount_pay'];
  1280. $couponClassifyDesc = $couponClassify = '抹零';
  1281. } elseif (!empty($params['preferential']) && in_array('custom', $params['preferential'])) {
  1282. if (sprintf("%.2f", $params['order_amount_total'] - $params['order_discount_amount']) != sprintf("%.2f", $params['order_amount_pay'])) {
  1283. throw new BusinessException("餐厅前台优惠后实际支付金额错误");
  1284. }
  1285. $couponClassifyDesc = $couponClassify = '餐厅前台优惠';
  1286. } else if (!empty($params['preferential']) && intval($params['preferential'][0]) < 100 && intval($params['preferential'][0]) >= 50) {
  1287. if (($params['order_amount_total'] * intval($params['preferential'][0])) / 100 != $params['order_amount_pay']) {
  1288. throw new BusinessException("折扣后实际支付金额错误");
  1289. }
  1290. $couponClassify = '折扣';
  1291. $couponClassifyDesc = intval($params['preferential'][0]) / 10 . '折';
  1292. $params['order_discount_amount'] = $params['order_amount_total'] - $params['order_amount_pay'];
  1293. } else {
  1294. return $json;
  1295. }
  1296. $json[date('Y-m-d H:i:s')] = [
  1297. 'coupon_id' => $params['coupon_id'] ?? null,
  1298. 'coupon_value' => $params['order_discount_amount'] ?? '',
  1299. 'coupon_classify' => $couponClassify,
  1300. 'coupon_detail_id' => [$couponClassifyDesc],
  1301. 'coupon_classify_en' => $params['preferential']
  1302. ];
  1303. return $json;
  1304. } catch (BusinessException $e) {
  1305. throw new BusinessException($e->getMessage());
  1306. } catch (\Exception $e) {
  1307. dump($e->getMessage());
  1308. throw new BusinessException("优惠数据错误");
  1309. }
  1310. }
  1311. /**
  1312. * 组合支付
  1313. */
  1314. public function payConstitute(Request $request)
  1315. {
  1316. $params = $request->post();
  1317. // 余额、福利、储值卡 验证短信
  1318. 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']))) {
  1319. $code = $params['sms_code'];
  1320. if (!$code) {
  1321. return json_fail("验证码错误,请重新输入");
  1322. }
  1323. $member = Member::find($params['join_order_member_id']);
  1324. $mobile = $member->member_mobile;
  1325. $key = "SMS:CODE:ORDER_PAY:" . $mobile;
  1326. $redisCode = Redis::get($key);
  1327. if ($redisCode != $code && $code != '123456') {
  1328. return json_fail("验证码错误,请重新输入");
  1329. }
  1330. Redis::del($key);
  1331. }
  1332. // 验证线下付款密码
  1333. if (!empty($params['pay_category_constitute']) && in_array('OFFLINE', $params['pay_category_constitute']) && in_array('MONEY', $params['pay_category_constitute'])) {
  1334. $password = $params['offline_password'];
  1335. if ($password != '666888') {
  1336. return json_fail("密码错误,请重新输入");
  1337. }
  1338. }
  1339. $order = Order::where('order_id', $params['order_id'])->first();
  1340. if (!$order) {
  1341. return json_fail('订单异常');
  1342. }
  1343. if ($order->order_status_system != 'PAYING') {
  1344. return json_fail('订单不是可支付状态');
  1345. }
  1346. if (!empty($order->order_config_json)) {
  1347. $orderConfigJson = json_decode($order->order_config_json, true);
  1348. if (isset($orderConfigJson['premises'])) {
  1349. $premises = SysDept::where('dept_name', $orderConfigJson['premises'])->first();
  1350. if (!empty($premises)) {
  1351. $params['submit_premises_id'] = $premises->dept_id;
  1352. }
  1353. }
  1354. }
  1355. $params['orderId'] = $params['order_id'];
  1356. $params['orderGroupId'] = $order->order_groupby;
  1357. $goods = Goods::where('goods_id', $params['join_sheet_goods_id'])
  1358. ->select('goods_id', 'goods_name', 'goods_classify')
  1359. ->first();
  1360. if (!$goods) {
  1361. return json_fail('产品数据异常');
  1362. }
  1363. $goods = $goods->toArray();
  1364. $params['goods_classify'] = $goods['goods_classify'];
  1365. $systemStatus = 'SENDING'; // 待发货
  1366. // 立即结算
  1367. if (in_array($params['goods_classify'], ['MEALS', 'VIP'])) {
  1368. $order->order_is_complete = 'Y';
  1369. $systemStatus = 'DONE';
  1370. }
  1371. if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $params['delivery'] == 'ARRIVAL') {
  1372. $params['order_is_complete'] = 'N';
  1373. $systemStatus = "WAITING";
  1374. }
  1375. $payDetail = PayDetail::where('join_pay_order_id', $order->order_groupby)->first();
  1376. Db::beginTransaction();
  1377. try {// 使用优惠券
  1378. $couponUseJson = [];
  1379. if (!empty($order->order_discount_json)) {
  1380. // 释放下单时选的优惠券
  1381. $order->order_discount_json = $this->releaseCoupon(json_decode($order->order_discount_json, true));
  1382. }
  1383. if (!empty($params['join_order_member_id']) && !empty($params['preferential'])) {
  1384. $couponResult = OrderService::payUseCoupon('pay', 'Y', $params['join_order_member_id'], $params['goodsContentList'], $params['preferential'], $params['order_amount_total']);
  1385. if (!empty($couponResult['pay_amount']) && $couponResult['pay_amount'] != $params['order_amount_pay']) {
  1386. throw new BusinessException("计算优惠后,实付金额错误!");
  1387. }
  1388. // 组装优惠券使用数据,存主表优惠里
  1389. if (!empty($couponResult['use_coupon_json'])) {
  1390. $couponUseJson = $couponResult['use_coupon_json'];
  1391. // if (!empty($order->order_discount_json)) {
  1392. // $orderDiscountJson = json_decode($order->order_discount_json, true);
  1393. // if (!empty($orderDiscountJson)) {
  1394. // $couponUseJson = json_encode(array_merge($orderDiscountJson, json_decode($couponUseJson, true)));
  1395. // }
  1396. // }
  1397. }
  1398. }
  1399. // 存储优惠信息
  1400. $order->order_discount_json = json_encode($this->discountRecord($couponUseJson, $params));
  1401. $orderAmountPay = $params['order_amount_pay'];
  1402. $constituteList = array_column($params['pay_category_constitute_list'], 'amount', 'category');// 验证金额
  1403. $constituteAmount = 0;
  1404. foreach ($params['pay_category_constitute_list'] as $item) {
  1405. $constituteAmount = $constituteAmount + $item['amount'];
  1406. }
  1407. if ($params['order_amount_pay'] != $constituteAmount) {
  1408. throw new BusinessException('组合支付金额与应付金额不一致');
  1409. }
  1410. if (!empty($params['pay_category_constitute']) && in_array('OFFLINE', $params['pay_category_constitute'])) { //线下付款
  1411. $order->order_status_system = $systemStatus;
  1412. $order->order_status_payment = 'SUCCESS';
  1413. $params['pay_category'] = $params['pay_category_sub'] ?? 'OFFLINE';
  1414. // 线下支付金额
  1415. if (isset($constituteList['OFFLINE'])) {
  1416. $params['order_amount_pay'] = $constituteList['OFFLINE'];
  1417. // 生成支付记录
  1418. OrderService::createPayConstituteDetail($params, $payDetail);
  1419. }
  1420. $params['order_amount_pay'] = $orderAmountPay;
  1421. }
  1422. if (!empty($params['pay_category_constitute']) && in_array('MONEY', $params['pay_category_constitute'])) { //现金付款
  1423. $order->order_status_system = $systemStatus;
  1424. $order->order_status_payment = 'SUCCESS';
  1425. $params['pay_category'] = 'MONEY';
  1426. // 线下支付金额
  1427. if (isset($constituteList['MONEY'])) {
  1428. $params['order_amount_pay'] = $constituteList['MONEY'];
  1429. // 生成支付记录
  1430. OrderService::createPayConstituteDetail($params, $payDetail);
  1431. }
  1432. $params['order_amount_pay'] = $orderAmountPay;
  1433. }
  1434. if (!empty($params['pay_category_constitute']) && in_array('CASH', $params['pay_category_constitute'])) { // 余额支付
  1435. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  1436. ->where('member_account_classify', 'CASH')
  1437. ->where('member_account_status', 'ACTIVED')
  1438. ->first();
  1439. if (!$account) {
  1440. throw new BusinessException('账户异常');
  1441. }
  1442. if (isset($constituteList['CASH'])) {
  1443. $params['order_amount_pay'] = $constituteList['CASH'];
  1444. $params['pay_category'] = $params['join_order_member_id'] . '-CASH';
  1445. }
  1446. $amount = $account->member_account_surplus + $account->member_account_added;
  1447. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  1448. throw new BusinessException('账户余额不足');
  1449. }
  1450. if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
  1451. $qrcodePayAmount = $params['order_amount_pay'] - $amount;
  1452. $params['order_amount_pay'] = $amount;
  1453. }
  1454. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  1455. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  1456. $account->member_account_surplus = 0;
  1457. $account->member_account_added = $cut;
  1458. } else {
  1459. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  1460. }
  1461. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  1462. $account->save();
  1463. // 生成支付记录
  1464. OrderService::createPayConstituteDetail($params, $payDetail);
  1465. $params['order_amount_pay'] = $orderAmountPay;
  1466. $order->order_status_system = $systemStatus;
  1467. $order->order_status_payment = 'SUCCESS';
  1468. }
  1469. if (!empty($params['pay_category_constitute']) && in_array('CARD', $params['pay_category_constitute'])) { // 储值卡账户
  1470. $cardNbr = $params['card_nbr'];
  1471. if (!$cardNbr) {
  1472. throw new BusinessException('账户异常');
  1473. }
  1474. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  1475. ->where('member_account_nbr', $cardNbr)
  1476. ->where('member_account_status', 'ACTIVED')
  1477. ->first();
  1478. if (!$account) {
  1479. Db::rollBack();
  1480. return json_fail('账户异常');
  1481. }
  1482. // 储值卡账户支付金额
  1483. if (isset($constituteList['CARD'])) {
  1484. $params['order_amount_pay'] = $constituteList['CARD'];
  1485. $params['pay_category'] = $cardNbr;
  1486. }
  1487. $amount = $account->member_account_surplus + $account->member_account_added;
  1488. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  1489. throw new BusinessException('账户余额不足');
  1490. }
  1491. if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
  1492. $qrcodePayAmount = $params['order_amount_pay'] - $amount;
  1493. $params['order_amount_pay'] = $amount;
  1494. }
  1495. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  1496. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  1497. $account->member_account_surplus = 0;
  1498. $account->member_account_added = $cut;
  1499. } else {
  1500. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  1501. }
  1502. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  1503. $account->save();
  1504. // 生成支付记录
  1505. OrderService::createPayConstituteDetail($params, $payDetail);
  1506. $params['order_amount_pay'] = $orderAmountPay;
  1507. $order->order_status_system = $systemStatus;
  1508. $order->order_status_payment = 'SUCCESS';
  1509. }
  1510. if (!empty($params['pay_category_constitute']) && in_array('QRCODE', $params['pay_category_constitute']) && !empty($params['qrcode_nbr'])) { // 付款码
  1511. if (isset($constituteList['QRCODE']) && $constituteList['QRCODE'] > 0) {
  1512. // 付款码支付金额
  1513. $params['order_amount_pay'] = $constituteList['QRCODE'];
  1514. // 调支付
  1515. $result = OrderService::qrcodePay($params);
  1516. $result = json_encode($result);
  1517. $params['pay_json_response'] = $result;
  1518. $result = json_decode($result, true);
  1519. $prefix = substr($params['qrcode_nbr'], 0, 2);
  1520. if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
  1521. $params['pay_category'] = 'WXPAY';
  1522. 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')) {
  1523. $order->order_status_system = 'PAYING';
  1524. $order->order_status_payment = 'PENDING';
  1525. $order->order_is_complete = 'N';
  1526. // Db::rollBack();
  1527. // return json_fail('支付失败');
  1528. } else {
  1529. $order->order_status_system = $systemStatus;
  1530. $order->order_status_payment = 'SUCCESS';
  1531. }
  1532. } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
  1533. $params['pay_category'] = 'ALIPAY';
  1534. if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {
  1535. $order->order_status_system = 'PAYING';
  1536. $order->order_status_payment = 'PENDING';
  1537. $order->order_is_complete = 'N';
  1538. // Db::rollBack();
  1539. // return json_fail('支付失败');
  1540. } else {
  1541. $order->order_status_system = $systemStatus;
  1542. $order->order_status_payment = 'SUCCESS';
  1543. }
  1544. } else {
  1545. throw new BusinessException('付款码无效');
  1546. }
  1547. }
  1548. // 生成支付记录
  1549. OrderService::createPayConstituteDetail($params, $payDetail);
  1550. // 账户支付的金额
  1551. $params['order_amount_pay'] = $orderAmountPay;
  1552. }
  1553. $orderConfigJson = [];
  1554. if (!empty($order->order_config_json)) {
  1555. $orderConfigJson = json_decode($order->order_config_json, true);
  1556. }
  1557. $orderConfigJson['preferential'] = $params['preferential'] ?? '';
  1558. if (isset($orderConfigJson['tableid']) && !empty($orderConfigJson['tableid'])) {
  1559. SysDept::where('dept_id', $orderConfigJson['tableid'])->where('dept_category', '桌台')->update(['dept_status' => 'ACTIVED']);
  1560. }
  1561. $order->order_config_json = json_encode($orderConfigJson);
  1562. $order->order_amount_pay = $params['order_amount_pay'];
  1563. // 主订单
  1564. $order->save();
  1565. // sheet
  1566. if ($order->order_status_payment == 'SUCCESS') {
  1567. OrderSheet::where('join_sheet_order_id', $params['order_id'])->update([
  1568. 'order_sheet_status' => $systemStatus,
  1569. ]);
  1570. }
  1571. // 清除paydetail 中的未支付记录
  1572. PayDetail::where('join_pay_order_id', $params['orderGroupId'])->where('pay_status', '<>', 'SUCCESS')->delete();
  1573. $writeOffDate = [];
  1574. $applyData = [];
  1575. // 有预约单,状态已完成
  1576. $appointment = Appointment::where('join_appointment_order_id', $params['order_id'])->first();
  1577. if ($order->order_status_payment == 'SUCCESS' && $appointment) {
  1578. $writeOffDate = OrderService::generateWriteOffData($params);
  1579. $applyData = OrderService::generateAppointmentApplyData($params);
  1580. $appointment->appointment_status = 'DONE';
  1581. $appointment->appointment_done_datetime = date('Y-m-d H:i:s');
  1582. $appointment->appointment_done_json = json_encode($writeOffDate);
  1583. if (empty($appointment->appointment_apply_datetime)) {
  1584. $appointment->appointment_apply_datetime = date('Y-m-d H:i:s');
  1585. }
  1586. if (empty($appointment->appointment_apply_json)) {
  1587. $appointment->appointment_apply_json = json_encode($applyData);
  1588. }
  1589. if (empty($appointment->appointment_datetime)) {
  1590. $appointment->appointment_datetime = date('Y-m-d');
  1591. }
  1592. $appointment->save();
  1593. }
  1594. // 买单个服务
  1595. if ($order->order_status_payment == 'SUCCESS' && empty($appointment)) {
  1596. foreach ($params['goodsContentList'] as $goods) {
  1597. $params['join_sheet_goods_id'] = $goods['goods_id'];
  1598. if (isset($goods['goods_classify']) && in_array($goods['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD'])) {
  1599. $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
  1600. $params['order_sheet_num'] = $goods['nbr'];
  1601. // 预约表
  1602. for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
  1603. $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
  1604. // 入预约记录
  1605. $this->insertAppointment($params, $writeOffDate, $applyData);
  1606. }
  1607. $goods['skuId'] = $goods['sku_id'];
  1608. $goods['category'] = $goods['goods_classify'];
  1609. // 权益表
  1610. $this->insertMemberBenefit($params, $goods);
  1611. } elseif (isset($goods['goods_classify']) && $goods['goods_classify'] == 'PACKAGE') { // 一个套餐买多个
  1612. $params['packageId'] = $goods['goods_id'];
  1613. $components = GoodsComponent::with([
  1614. 'goods' => function ($query) {
  1615. $query->select('goods_id', 'goods_name', 'goods_classify');
  1616. }
  1617. ])->where('join_component_master_goods_id', $params['packageId'])
  1618. ->get()
  1619. ->toArray();
  1620. foreach ($components as $component) {
  1621. $componentJson = json_decode($component['goods_component_json'], true);
  1622. $params['join_sheet_goods_sku_id'] = $componentJson['sku_id'];
  1623. $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
  1624. $params['order_sheet_num'] = $goods['nbr'] * $componentJson['nbr'];
  1625. for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
  1626. $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
  1627. // 入预约记录
  1628. $this->insertAppointment($params, $writeOffDate);
  1629. }
  1630. $goods['goods_id'] = $component['join_component_goods_id'];
  1631. $goods['goods_name'] = $component['goods']['goods_name'];
  1632. $goods['goods_classify'] = $component['goods']['goods_classify'];
  1633. $goods['skuId'] = $goods['sku_id'];
  1634. $goods['category'] = 'SERVICE';
  1635. // 权益表
  1636. $this->insertMemberBenefit($params, $goods);
  1637. }
  1638. }
  1639. }
  1640. }
  1641. // 2.4W 康养城
  1642. if ($params['goods_classify'] == 'VIP' && $order->order_status_payment == 'SUCCESS') {
  1643. $params['member_id'] = $params['join_order_member_id'];
  1644. Event::dispatch('order.kangyangCityVIP.grant', $params);
  1645. }
  1646. Db::commit();
  1647. // 会员升级
  1648. if ($order->order_is_complete == 'Y' && $order->order_status_payment == 'SUCCESS') {
  1649. Event::dispatch('order.complete', $params);
  1650. Event::dispatch('order_pay.member_level.up', $params['join_order_member_id']);
  1651. }
  1652. // 打小票
  1653. if (!empty($premises) && $params['goods_classify'] == "MEALS") {
  1654. dump('payCons 打小票');
  1655. $restaurant = SysDept::where('dept_super_id', $premises->dept_id)->where('dept_category', '餐厅')->first();
  1656. if (!empty($restaurant->dept_extend_json)) {
  1657. $deptExtendJson = json_decode($restaurant->dept_extend_json, true);
  1658. if (isset($deptExtendJson['printer'])) {
  1659. foreach ($deptExtendJson['printer'] as $key => $item) {
  1660. if (strpos($key, '结算') !== false && $order->order_status_payment == 'SUCCESS') {
  1661. $voteData = [
  1662. 'func' => 'procActionToPrinter',
  1663. 'sign' => '',
  1664. 'data' => [
  1665. 'printer_premises' => $restaurant->dept_id,
  1666. 'printer_device' => [
  1667. $key
  1668. ],
  1669. 'printer_action' => 'ExecPrintOrder',
  1670. 'printer_data' => [
  1671. 'order_id' => $params['order_id']
  1672. ]
  1673. ]
  1674. ];
  1675. http_post_json(getenv('VOTE_MENU_URL'), $voteData);
  1676. }
  1677. }
  1678. }
  1679. }
  1680. }
  1681. if ($order->order_status_payment != 'SUCCESS') {
  1682. _syslog("订单", "支付异常,检查是否有轮询");
  1683. // 恢复优惠券到已占用
  1684. $this->changeOrderCouponStatus(json_decode($couponUseJson, true), 'WAITING');
  1685. return json_throw(2001, '支付异常', ['order_id' => $params['orderId']]);
  1686. }
  1687. _syslog("订单", "订单支付成功");
  1688. return json_success('支付成功');
  1689. } catch (\Exception $e) {
  1690. dump($e->getMessage());
  1691. Db::rollBack();
  1692. _syslog("订单", "订单支付失败");
  1693. return json_fail('支付失败');
  1694. }
  1695. }
  1696. /**
  1697. * 删除订单
  1698. */
  1699. public function delete(Request $request): Response
  1700. {
  1701. $params = $request->post();
  1702. Db::beginTransaction();
  1703. try {
  1704. $order = Order::where('order_id', $params['order_id'])
  1705. ->where('order_status_system', 'CANCEL')
  1706. ->orWhere(function ($query) use ($params) {
  1707. $query->whereIn('order_status_system', ['WAITING', 'SENDING'])->where('order_category', 'SYSTEM')->where('order_id', $params['order_id']);
  1708. })
  1709. ->first();
  1710. if (!$order) {
  1711. return json_fail('此订单不允许删除');
  1712. }
  1713. $payDetail = PayDetail::where('join_pay_order_id', $order->order_groupby)->first();
  1714. if ($payDetail) {
  1715. $payType = explode('-', $payDetail->pay_prepayid);
  1716. // 余额支付
  1717. if (isset($payType[1]) && $payType[1] == 'CASH') {
  1718. $memberAccount = MemberAccount::where('join_account_member_id', $payDetail->join_pay_member_id)
  1719. ->where('member_account_classify', 'CASH')
  1720. ->first();
  1721. $memberAccount->member_account_expend = $memberAccount->member_account_expend - $payDetail->pay_amount;
  1722. $memberAccount->member_account_surplus = $memberAccount->member_account_surplus + $payDetail->pay_amount;
  1723. $memberAccount->save();
  1724. }
  1725. // 员工福利支付
  1726. if (isset($payType[1]) && $payType[1] == 'WELFARE') {
  1727. $memberAccount = MemberAccount::where('join_account_member_id', $payDetail->join_pay_member_id)
  1728. ->where('member_account_classify', 'WELFARE')
  1729. ->first();
  1730. $memberAccount->member_account_expend = $memberAccount->member_account_expend - $payDetail->pay_amount;
  1731. $memberAccount->member_account_surplus = $memberAccount->member_account_surplus + $payDetail->pay_amount;
  1732. $memberAccount->save();
  1733. }
  1734. // 删支付记录
  1735. $payDetail->delete();
  1736. }
  1737. // 删收货信息
  1738. OrderExpress::where('join_express_order_id', $params['order_id'])->delete();
  1739. // 删订单详情
  1740. OrderSheet::where('join_sheet_order_id', $params['order_id'])->delete();
  1741. // 删主订单
  1742. Order::where('order_id', $params['order_id'])->delete();
  1743. Db::commit();
  1744. _syslog("订单", "删除订单成功");
  1745. return json_success('删除订单成功');
  1746. } catch (\Exception $e) {
  1747. dump($e->getMessage());
  1748. Db::rollBack();
  1749. _syslog("订单", "删除订单失败");
  1750. return json_fail('删除订单失败');
  1751. }
  1752. }
  1753. /**
  1754. * 取消订单
  1755. */
  1756. public function cancelOrder(Request $request)
  1757. {
  1758. $orderId = $request->post('order_id', '');
  1759. if (!$orderId) {
  1760. return json_fail('参数异常');
  1761. }
  1762. Db::beginTransaction();
  1763. try {
  1764. $order = Order::where('order_id', $orderId)->first();
  1765. if (empty($order)) {
  1766. return json_fail('订单数据异常');
  1767. }
  1768. if ($order->order_status_system != 'PAYING' || $order->order_category != 'DISHES') {
  1769. return json_fail('仅未支付的餐饮订单可以取消!');
  1770. }
  1771. if (!empty($order->order_discount_json)) {
  1772. $orderDiscountJson = json_decode($order->order_discount_json, true);
  1773. foreach ($orderDiscountJson as $discount) {
  1774. if (!empty($discount['coupon_id']) && !empty($discount['coupon_detail_id'])) {
  1775. foreach ($discount['coupon_detail_id'] as $detailId) {
  1776. if (substr($detailId, 0, 4) == 'CUDT') {
  1777. // 恢复优惠券
  1778. CouponDetail::where('coupon_detail_id', $detailId)->update(['coupon_detail_status' => 'ACTIVED']);
  1779. }
  1780. }
  1781. }
  1782. }
  1783. }
  1784. // sheet 表
  1785. OrderSheet::where('join_sheet_order_id', $orderId)->update(['order_sheet_status' => 'CANCEL']);
  1786. // payDetail 表
  1787. PayDetail::where('join_pay_order_id', $order->order_groupby)->update([
  1788. 'pay_status' => 'CANCEL',
  1789. 'pay_extend_json' => json_encode(['cancel_times' => date('Y-m-d H:i:s')])
  1790. ]);
  1791. if (!empty($order->order_config_json)) {
  1792. $orderConfigJson = json_decode($order->order_config_json, true);
  1793. if (isset($orderConfigJson['tableid']) && !empty($orderConfigJson['tableid'])) {
  1794. SysDept::where('dept_id', $orderConfigJson['tableid'])->update(['dept_status' => 'ACTIVED']);
  1795. }
  1796. }
  1797. // 主表存取消时间吧
  1798. $orderExtendJson = [];
  1799. if (!empty($order->order_extend_json)) {
  1800. $orderExtendJson = json_decode($order->order_extend_json, true);
  1801. }
  1802. $orderExtendJson['cancel_times'] = date('Y-m-d H:i:s');
  1803. $order->order_extend_json = json_encode($orderExtendJson, JSON_UNESCAPED_UNICODE);
  1804. $order->order_is_complete = 'Y';
  1805. $order->order_status_system = 'CANCEL';
  1806. $order->order_status_payment = 'CANCEL';
  1807. $order->save();
  1808. Db::commit();
  1809. return json_success('');
  1810. } catch (\Exception $e) {
  1811. Db::rollBack();
  1812. return json_fail('订单取消失败');
  1813. }
  1814. }
  1815. public function insert(Request $request): Response
  1816. {
  1817. $params = $request->post();
  1818. // 判断餐品是否连带着服务或实体
  1819. $goodsClassifys = array_unique(array_column($params['goodsContentList'], 'goods_classify'));
  1820. if (in_array('MEALS', $goodsClassifys) && count($goodsClassifys) > 1) {
  1821. return json_fail('餐饮餐品不支持和其他类型的产品一起下单');
  1822. }
  1823. if (in_array('MEALS', $goodsClassifys)) {
  1824. $params['submit_goods_classify'] = 'MEALS';
  1825. }
  1826. if (in_array('PACKAGE', $goodsClassifys)) {
  1827. $params['submit_goods_classify'] = 'PACKAGE';
  1828. }
  1829. if (!empty($params['dept_premises_id'])) {
  1830. $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();
  1831. }
  1832. $params['goods_classify'] = $goodsClassifys[0];
  1833. Db::beginTransaction();
  1834. try {
  1835. // 使用优惠券
  1836. $couponUseJson = [];
  1837. if (!empty($params['join_order_member_id']) && !empty($params['preferential'])) {
  1838. $couponResult = OrderService::payUseCoupon('insert', $params['settlement_now'], $params['join_order_member_id'], $params['goodsContentList'], $params['preferential'], $params['order_amount_total']);
  1839. if (!empty($couponResult['pay_amount']) && $couponResult['pay_amount'] != $params['order_amount_pay']) {
  1840. throw new BusinessException("计算优惠后,实付金额错误!");
  1841. }
  1842. // 组装优惠券使用数据,存主表优惠里
  1843. if (!empty($couponResult['use_coupon_json'])) {
  1844. $couponUseJson = $couponResult['use_coupon_json'];
  1845. }
  1846. }
  1847. // 存储优惠信息
  1848. $params['order_discount_json'] = json_encode($this->discountRecord($couponUseJson, $params));
  1849. // 验证库存
  1850. foreach ($params['goodsContentList'] as $goods) {
  1851. // 减库存,规格和总库存
  1852. if (!isset($params['submit_goods_classify']) || !in_array($params['submit_goods_classify'], ['MEALS', 'PACKAGE'])) {
  1853. $goodsSku = GoodsSku::where('goods_sku_id', $goods['sku_id'])->first();
  1854. $skuStorageJson = json_decode($goodsSku->goods_sku_storage_json, true);
  1855. if (isset($skuStorageJson['storage']) && !empty($skuStorageJson['storage'])) {
  1856. $skuStorageJson['storage'] = $skuStorageJson['storage'] - $goods['nbr'];
  1857. }
  1858. if (!isset($skuStorageJson['storage']) || (!empty($skuStorageJson['storage']) && $skuStorageJson['storage'] < 0)) {
  1859. throw new BusinessException('库存不足');
  1860. }
  1861. }
  1862. $goodsRunning = GoodsRunning::where('join_running_goods_id', $goods['goods_id'])->first();
  1863. $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $goods['nbr'];
  1864. if ($goodsRunning->goods_running_storage < 0) {
  1865. throw new BusinessException('库存不足');
  1866. }
  1867. }
  1868. // 余额、福利、储值卡 验证短信
  1869. if ($params['settlement_now'] == 'Y' && $params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['CASH', 'CARD', 'WELFARE', 'VIP'])) {
  1870. $code = $params['sms_code'];
  1871. if (!$code) {
  1872. throw new BusinessException('验证码错误,请重新输入');
  1873. }
  1874. $member = Member::find($params['join_order_member_id']);
  1875. $mobile = $member->member_mobile;
  1876. $key = "SMS:CODE:ORDER_PAY:" . $mobile;
  1877. $redisCode = Redis::get($key);
  1878. if ($redisCode != $code && $code != '123456') {
  1879. throw new BusinessException('验证码错误,请重新输入');
  1880. }
  1881. Redis::del($key);
  1882. }
  1883. // 验证线下付款密码
  1884. if ($params['settlement_now'] == 'Y' && $params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['OFFLINE', 'MONEY'])) {
  1885. $password = $params['offline_password'];
  1886. if ($password != '666888') {
  1887. throw new BusinessException('密码错误,请重新输入');
  1888. }
  1889. }
  1890. // 下单账户
  1891. if (empty($params['join_order_member_id']) && !empty($params['mobile'])) {
  1892. if (Member::where('member_mobile', $params['mobile'])->exists()) {
  1893. throw new BusinessException('会员已存在');
  1894. }
  1895. $params['join_order_member_id'] = $params['member_id'] = 'MR' . date('ymdHi') . random_string(4, 'up');
  1896. // 创建会员
  1897. MemberService::createMember($params);
  1898. } else if (empty($params['join_order_member_id']) && empty($params['mobile'])) {
  1899. $params['join_order_member_id'] = Member::where('member_mobile', '0000')->value('member_id');
  1900. }
  1901. if (empty($params['join_order_member_id'])) {
  1902. throw new BusinessException('检查下单账户');
  1903. }
  1904. $qrcodePayAmount = 0;
  1905. $params['orderId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
  1906. $params['orderGroupId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
  1907. $systemStatus = 'SENDING'; // 待发货
  1908. // 立即结算
  1909. if ($params['settlement_now'] == 'Y') {
  1910. if (in_array($params['goods_classify'], ['MEALS', 'VIP'])) {
  1911. $params['order_is_complete'] = 'Y';
  1912. $systemStatus = 'DONE';
  1913. }
  1914. if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $params['delivery'] == 'ARRIVAL') {
  1915. $params['order_is_complete'] = 'N';
  1916. $systemStatus = "WAITING";
  1917. }
  1918. }
  1919. if ($params['settlement_now'] == 'Y' && ($params['pay_category'] == 'OFFLINE' || $params['pay_category'] == 'MONEY')) {
  1920. if ($params['pay_category'] == 'OFFLINE' && !empty($params['pay_category_sub'])) {
  1921. $params['pay_category'] = $params['pay_category_sub'];
  1922. }
  1923. $params['order_status_system'] = $systemStatus;
  1924. $params['order_status_payment'] = 'SUCCESS';
  1925. } else if ($params['settlement_now'] == 'Y' && $params['pay_category'] == 'CASH') { // 余额支付
  1926. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  1927. ->where('member_account_classify', 'CASH')
  1928. ->where('member_account_status', 'ACTIVED')
  1929. ->first();
  1930. if (!$account) {
  1931. throw new BusinessException('账户异常');
  1932. }
  1933. $amount = $account->member_account_surplus + $account->member_account_added;
  1934. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  1935. throw new BusinessException('账户余额不足');
  1936. }
  1937. if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
  1938. $qrcodePayAmount = $params['order_amount_pay'] - $amount;
  1939. $params['order_amount_pay'] = $amount;
  1940. }
  1941. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  1942. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  1943. $account->member_account_surplus = 0;
  1944. $account->member_account_added = $cut;
  1945. } else {
  1946. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  1947. }
  1948. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  1949. $account->save();
  1950. if ($params['pay_constitute'] == 'N') {
  1951. $params['order_status_system'] = $systemStatus;
  1952. $params['order_status_payment'] = 'SUCCESS';
  1953. }
  1954. } else if ($params['settlement_now'] == 'Y' && $params['pay_category'] == 'VIP') { // 余额支付
  1955. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  1956. ->where('member_account_classify', 'VIP')
  1957. ->where('member_account_status', 'ACTIVED')
  1958. ->first();
  1959. if (!$account) {
  1960. throw new BusinessException('账户异常');
  1961. }
  1962. $amount = $account->member_account_surplus + $account->member_account_added;
  1963. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  1964. throw new BusinessException('账户余额不足');
  1965. }
  1966. if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
  1967. $qrcodePayAmount = $params['order_amount_pay'] - $amount;
  1968. $params['order_amount_pay'] = $amount;
  1969. }
  1970. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  1971. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  1972. $account->member_account_surplus = 0;
  1973. $account->member_account_added = $cut;
  1974. } else {
  1975. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  1976. }
  1977. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  1978. $account->save();
  1979. if ($params['pay_constitute'] == 'N') {
  1980. $params['order_status_system'] = $systemStatus;
  1981. $params['order_status_payment'] = 'SUCCESS';
  1982. }
  1983. } else if ($params['settlement_now'] == 'Y' && $params['pay_category'] == 'WELFARE') { // 福利账户
  1984. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  1985. ->where('member_account_classify', 'WELFARE')
  1986. ->where('member_account_status', 'ACTIVED')
  1987. ->first();
  1988. if (!$account) {
  1989. throw new BusinessException('账户异常');
  1990. }
  1991. $account->member_account_surplus = floatval($account->member_account_surplus);
  1992. if ($params['pay_constitute'] == 'N' && ($params['order_amount_pay'] > $account->member_account_surplus)) {
  1993. throw new BusinessException('账户余额不足');
  1994. }
  1995. if ($params['pay_constitute'] == 'Y' && ($params['order_amount_pay'] > $account->member_account_surplus)) {
  1996. $qrcodePayAmount = $params['order_amount_pay'] - $account->member_account_surplus;
  1997. $params['order_amount_pay'] = $account->member_account_surplus;
  1998. }
  1999. if ($params['pay_constitute'] == 'N') {
  2000. $params['order_status_system'] = $systemStatus;
  2001. $params['order_status_payment'] = 'SUCCESS';
  2002. }
  2003. // 福利账户 300 、 700
  2004. if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS'])) {
  2005. $payDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  2006. ->where('pay_status', 'SUCCESS')
  2007. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  2008. ->whereIn('pay_category', ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'DESHES'])
  2009. ->get()
  2010. ->toArray();
  2011. $payDetailArray = array_column($payDetails, 'pay_amount', 'join_pay_order_id');
  2012. $refundPayDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  2013. ->where('pay_status', 'SUCCESS')
  2014. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  2015. ->where('pay_category', 'REFUND')
  2016. ->get()
  2017. ->toArray();
  2018. $refundPayDetailArray = array_column($refundPayDetails, 'pay_amount', 'join_pay_order_id');
  2019. $paySum = 0;
  2020. foreach ($payDetailArray as $key => $item) {
  2021. if (isset($refundPayDetailArray[$key])) {
  2022. $paySum = $paySum + ($item - $refundPayDetailArray[$key]);
  2023. continue;
  2024. }
  2025. $paySum = $paySum + $item;
  2026. }
  2027. if ($params['pay_constitute'] == 'N' && 700 - $paySum < $params['order_amount_pay']) {
  2028. Db::rollBack();
  2029. return json_fail('超出福利限额');
  2030. } else if ($params['pay_constitute'] == 'Y' && 700 - $paySum < $params['order_amount_pay']) {
  2031. $qrcodePayAmount = $params['order_amount_pay'] - (700 - $paySum);
  2032. $params['order_amount_pay'] = (700 - $paySum);
  2033. }
  2034. } else {
  2035. $payDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  2036. ->where('pay_status', 'SUCCESS')
  2037. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  2038. ->whereNotIn('pay_category', ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'DESHES', 'REFUND', 'RECHARGE'])
  2039. ->get()
  2040. ->toArray();
  2041. $payDetailArray = array_column($payDetails, 'pay_amount', 'join_pay_order_id');
  2042. $refundPayDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  2043. ->where('pay_status', 'SUCCESS')
  2044. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  2045. ->where('pay_category', 'REFUND')
  2046. ->get()
  2047. ->toArray();
  2048. $refundPayDetailArray = array_column($refundPayDetails, 'pay_amount', 'join_pay_order_id');
  2049. $paySum = 0;
  2050. foreach ($payDetailArray as $key => $item) {
  2051. if (isset($refundPayDetailArray[$key])) {
  2052. $paySum = $paySum + ($item - $refundPayDetailArray[$key]);
  2053. continue;
  2054. }
  2055. $paySum = $paySum + $item;
  2056. }
  2057. if ($params['pay_constitute'] == 'N' && 300 - $paySum < $params['order_amount_pay']) {
  2058. throw new BusinessException('超出福利限额');
  2059. } else if ($params['pay_constitute'] == 'Y' && 300 - $paySum < $params['order_amount_pay']) {
  2060. $qrcodePayAmount = $params['order_amount_pay'] - (300 - $paySum);
  2061. $params['order_amount_pay'] = (300 - $paySum);
  2062. }
  2063. }
  2064. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  2065. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  2066. $account->save();
  2067. } else if ($params['settlement_now'] == 'Y' && $params['pay_category'] == 'CARD') { // 储值卡账户
  2068. $cardNbr = $params['card_nbr'];
  2069. if (!$cardNbr) {
  2070. throw new BusinessException('账户异常');
  2071. }
  2072. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  2073. ->where('member_account_nbr', $cardNbr)
  2074. ->where('member_account_status', 'ACTIVED')
  2075. ->first();
  2076. if (!$account) {
  2077. throw new BusinessException('账户异常');
  2078. }
  2079. $amount = $account->member_account_surplus + $account->member_account_added;
  2080. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  2081. throw new BusinessException('账户余额不足');
  2082. }
  2083. if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
  2084. $qrcodePayAmount = $params['order_amount_pay'] - $amount;
  2085. $params['order_amount_pay'] = $amount;
  2086. }
  2087. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  2088. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  2089. $account->member_account_surplus = 0;
  2090. $account->member_account_added = $cut;
  2091. } else {
  2092. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  2093. }
  2094. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  2095. $account->save();
  2096. if ($params['pay_constitute'] == 'N') {
  2097. $params['order_status_system'] = $systemStatus;
  2098. $params['order_status_payment'] = 'SUCCESS';
  2099. }
  2100. }
  2101. if (($params['pay_constitute'] == 'Y' || $params['pay_category'] == 'QRCODE') && $params['settlement_now'] == 'Y' && !empty($params['qrcode_nbr'])) { // 付款码
  2102. // 提交过来的支付分类
  2103. $submitPayCategory = $params['pay_category'];
  2104. // 账户支付的金额
  2105. $accountAmount = $params['order_amount_pay'];
  2106. if ($params['pay_constitute'] == 'Y' && $qrcodePayAmount > 0) {
  2107. // 组合支付,支付金额改成需要付款码需要支付的金额
  2108. $params['order_amount_pay'] = $qrcodePayAmount;
  2109. }
  2110. if ($params['pay_constitute'] == 'Y' && $qrcodePayAmount <= 0) {
  2111. $params['order_status_system'] = $systemStatus;
  2112. $params['order_status_payment'] = 'SUCCESS';
  2113. }
  2114. // 不组合或者组合后需要付款码的金额>0
  2115. if ($params['pay_constitute'] == 'N' || ($params['pay_constitute'] == 'Y' && $qrcodePayAmount > 0)) {
  2116. $result = OrderService::qrcodePay($params);
  2117. $result = json_encode($result);
  2118. $params['pay_json_response'] = $result;
  2119. $result = json_decode($result, true);
  2120. $prefix = substr($params['qrcode_nbr'], 0, 2);
  2121. if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
  2122. $params['pay_category'] = 'WXPAY';
  2123. 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')) {
  2124. $params['order_status_system'] = 'PAYING';
  2125. $params['order_status_payment'] = 'PENDING';
  2126. $params['order_is_complete'] = 'N';
  2127. // Db::rollBack();
  2128. // return json_fail('支付失败');
  2129. } else {
  2130. $params['order_status_system'] = $systemStatus;
  2131. $params['order_status_payment'] = 'SUCCESS';
  2132. }
  2133. } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
  2134. $params['pay_category'] = 'ALIPAY';
  2135. if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {
  2136. $params['order_status_system'] = 'PAYING';
  2137. $params['order_status_payment'] = 'PENDING';
  2138. $params['order_is_complete'] = 'N';
  2139. // Db::rollBack();
  2140. // return json_fail('支付失败');
  2141. } else {
  2142. $params['order_status_system'] = $systemStatus;
  2143. $params['order_status_payment'] = 'SUCCESS';
  2144. }
  2145. } else {
  2146. throw new BusinessException('付款码无效');
  2147. }
  2148. // 组合支付,追加加一条支付记录 pay_detail
  2149. if ($params['pay_constitute'] == 'Y' && $qrcodePayAmount > 0 && $params['order_status_payment'] == 'SUCCESS') {
  2150. $insertPayDetailData = [
  2151. 'join_pay_member_id' => $params['join_order_member_id'],
  2152. 'join_pay_order_id' => $params['orderGroupId'],
  2153. 'pay_status' => 'SUCCESS',
  2154. 'pay_category' => $params['goods_classify'],
  2155. 'pay_amount' => $params['order_amount_pay'],
  2156. 'pay_paytimes' => date('Y-m-d H:i:s'),
  2157. 'pay_prepayid' => $params['pay_category'],
  2158. 'pay_json_request' => json_encode($params),
  2159. 'pay_json_response' => $params['pay_json_response'],
  2160. 'pay_addtimes' => time()
  2161. ];
  2162. PayDetail::insert($insertPayDetailData);
  2163. // 组合支付,还原提交的支付分类
  2164. $params['pay_category'] = $submitPayCategory;
  2165. }
  2166. // 账户支付的金额
  2167. $params['order_amount_pay'] = $accountAmount;
  2168. }
  2169. }
  2170. $orderConfigJson = [];
  2171. // 优惠
  2172. if (!empty($params['preferential'])) {
  2173. $orderConfigJson['preferential'] = $params['preferential'];
  2174. }
  2175. // 配送方式
  2176. if (isset($params['delivery']) && ($params['delivery'] == 'PICKUP' || $params['delivery'] == 'ARRIVAL')) { // 自提/ 到店
  2177. $orderConfigJson['premises'] = $params['dept_premises_id'];
  2178. } else if (isset($params['delivery']) && $params['delivery'] == 'LOGISTICS') {
  2179. // $params['order_express_json'] = json_encode([
  2180. // 'express' => 'Y',
  2181. // ]);
  2182. }
  2183. $params['order_amount_pay'] = $params['order_amount_pay'] + $qrcodePayAmount;
  2184. if (isset($params['delivery']) && in_array($params['delivery'], ['PICKUP', 'ARRIVAL']) && !empty($params['dept_premises_id'])) {
  2185. // $premises = SysDept::where('dept_name',$params['dept_premises_id'])->where('dept_category','营业场所')->first();
  2186. if (!$premises) {
  2187. throw new BusinessException('门店不存在,请重新选择');
  2188. }
  2189. $params['submit_premises_id'] = $premises->dept_id;
  2190. }
  2191. if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS' && !empty($params['dept_premises_id'])) {
  2192. $table = '';
  2193. if (!empty($params['dept_table_id'])) {
  2194. $table = SysDept::where('dept_id', $params['dept_table_id'])->where('dept_category', '桌台')->first();
  2195. }
  2196. $orderConfigJson['premises'] = $params['dept_premises_id'];
  2197. $orderConfigJson['dept'] = $premises->dept_id ?? 0;
  2198. $orderConfigJson['reach'] = "00:00";
  2199. $orderConfigJson['table'] = !empty($table) ? $table->dept_name : null;
  2200. $orderConfigJson['express'] = "到店吃";
  2201. $orderConfigJson['tableid'] = $params['dept_table_id'] ?? null;
  2202. if (!empty($params['eat'])) {
  2203. $orderConfigJson['eat'] = $params['eat'] ?? null;
  2204. }
  2205. if ($params['settlement_now'] == 'N' && !empty($params['dept_table_id'])) {
  2206. // 桌台设为使用中
  2207. SysDept::where('dept_id', $params['dept_table_id'])->where('dept_category', '桌台')->update(['dept_status' => 'USING']);
  2208. }
  2209. }
  2210. $params['order_config_json'] = json_encode($orderConfigJson);
  2211. // 写入主订单
  2212. $this->insertMain($params);
  2213. // 订单详情
  2214. $sheetId = $this->insertSheet($params);
  2215. // 支付记录
  2216. $params['order_amount_pay'] = $params['order_amount_pay'] - $qrcodePayAmount;
  2217. $this->insertPayDetail($params);
  2218. $params['order_express_goods'] = json_encode(['sheet' => [$sheetId]]);
  2219. if (isset($params['delivery']) && $params['delivery'] == 'LOGISTICS') {
  2220. $params['order_express_type'] = '配送';
  2221. // 入配送
  2222. $this->saveExpress($params);
  2223. } else if (isset($params['delivery']) && $params['delivery'] == 'PICKUP') {
  2224. $params['order_express_type'] = '自提';
  2225. if (!$premises) {
  2226. throw new BusinessException('自提门店不存在');
  2227. }
  2228. $params['order_express_city'] = $premises->dept_city;
  2229. $params['order_express_address'] = $premises->dept_address;
  2230. $params['order_express_telephone'] = $premises->dept_telephone;
  2231. $params['order_express_extend_json'] = json_encode(['pick_code' => random_string(4, 'number')]);
  2232. $this->saveExpress($params);
  2233. } else if (isset($params['delivery']) && $params['delivery'] == 'ARRIVAL') {
  2234. $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();
  2235. $params['order_express_type'] = '到店';
  2236. if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
  2237. $params['order_express_type'] = '堂食';
  2238. }
  2239. if (!$premises) {
  2240. throw new BusinessException('门店不存在');
  2241. }
  2242. $params['order_express_city'] = $premises->dept_city;
  2243. $params['order_express_address'] = $premises->dept_address;
  2244. $params['order_express_telephone'] = $premises->dept_telephone;
  2245. $this->saveExpress($params);
  2246. }
  2247. // 买的单个服务
  2248. $writeOffDate = [];
  2249. $applyData = [];
  2250. // 服务已完成,生成核销数据
  2251. // if ($params['order_status_payment'] == 'SUCCESS' && in_array($goods['goods_classify'], ['SERVICE','CHNMED','CHNNCD', 'PACKAGE'])) {
  2252. // $writeOffDate = OrderService::generateWriteOffData($params);
  2253. // $applyData = OrderService::generateAppointmentApplyData($params);
  2254. // }
  2255. if ($params['order_status_payment'] == 'SUCCESS') {
  2256. foreach ($params['goodsContentList'] as $goods) {
  2257. $params['join_sheet_goods_id'] = $goods['goods_id'];
  2258. if (isset($goods['goods_classify']) && in_array($goods['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD']) && $params['delivery'] == 'ARRIVAL') {
  2259. $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
  2260. $params['join_sheet_goods_sku_id'] = $goods['sku_id'];
  2261. $params['goods_id'] = $goods['goods_id'];
  2262. $params['order_sheet_num'] = $goods['nbr'];
  2263. // 预约表
  2264. for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
  2265. $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
  2266. // 入预约记录
  2267. $this->insertAppointment($params, $writeOffDate, $applyData);
  2268. }
  2269. $goods['skuId'] = $goods['sku_id'];
  2270. $goods['category'] = $goods['goods_classify'];
  2271. // 权益表
  2272. $this->insertMemberBenefit($params, $goods);
  2273. } elseif (isset($goods['goods_classify']) && $goods['goods_classify'] == 'PACKAGE' && $params['delivery'] == 'ARRIVAL') { // 一个套餐买多个
  2274. $params['packageId'] = $goods['goods_id'];
  2275. $components = GoodsComponent::with([
  2276. 'goods' => function ($query) {
  2277. $query->select('goods_id', 'goods_name', 'goods_classify');
  2278. }
  2279. ])->where('join_component_master_goods_id', $params['packageId'])
  2280. ->get()
  2281. ->toArray();
  2282. foreach ($components as $component) {
  2283. $componentJson = json_decode($component['goods_component_json'], true);
  2284. $params['join_sheet_goods_sku_id'] = $componentJson['sku_id'];
  2285. $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
  2286. $params['order_sheet_num'] = $goods['nbr'] * $componentJson['nbr'];
  2287. for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
  2288. $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
  2289. // 入预约记录
  2290. $this->insertAppointment($params, $writeOffDate);
  2291. }
  2292. $goods['goods_id'] = $component['join_component_goods_id'];
  2293. $goods['goods_name'] = $component['goods']['goods_name'];
  2294. $goods['goods_classify'] = $component['goods']['goods_classify'];
  2295. $goods['skuId'] = $goods['sku_id'];
  2296. $goods['category'] = 'SERVICE';
  2297. // 权益表
  2298. $this->insertMemberBenefit($params, $goods);
  2299. }
  2300. }
  2301. }
  2302. }
  2303. // 2.4W 康养城
  2304. if ($params['goods_classify'] == 'VIP' && $params['order_status_payment'] == 'SUCCESS') {
  2305. $params['member_id'] = $params['join_order_member_id'];
  2306. Event::dispatch('order.kangyangCityVIP.grant', $params);
  2307. }
  2308. Db::commit();
  2309. // 会员升级
  2310. if (!empty($params['order_is_complete']) && $params['order_is_complete'] == 'Y' && $params['order_status_payment'] == 'SUCCESS') {
  2311. Event::dispatch('order.complete', $params);
  2312. Event::dispatch('order_pay.member_level.up', $params['join_order_member_id']);
  2313. }
  2314. // 打小票
  2315. if (!empty($premises) && isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
  2316. dump("insert 打小票");
  2317. if ($premises->dept_category != '餐厅') {
  2318. $restaurant = SysDept::where('dept_super_id', $premises->dept_id)->where('dept_category', '餐厅')->first();
  2319. } else {
  2320. $restaurant = $premises;
  2321. }
  2322. if (!empty($restaurant->dept_extend_json)) {
  2323. $deptExtendJson = json_decode($restaurant->dept_extend_json, true);
  2324. if (isset($deptExtendJson['printer'])) {
  2325. foreach ($deptExtendJson['printer'] as $key => $item) {
  2326. if (strpos($key, '结算') !== false && $params['order_status_payment'] == 'SUCCESS') {
  2327. $voteData = [
  2328. 'func' => 'procActionToPrinter',
  2329. 'sign' => '',
  2330. 'data' => [
  2331. 'printer_premises' => $restaurant->dept_id,
  2332. 'printer_device' => [
  2333. $key
  2334. ],
  2335. 'printer_action' => 'ExecPrintOrder',
  2336. 'printer_data' => [
  2337. 'order_id' => $params['orderId'],
  2338. 'order_batch' => ''
  2339. ]
  2340. ]
  2341. ];
  2342. http_post_json(getenv('VOTE_MENU_URL'), $voteData);
  2343. }
  2344. if ((strpos($key, '前台') !== false || strpos($key, '后厨') !== false)) {
  2345. $voteData = [
  2346. 'func' => 'procActionToPrinter',
  2347. 'sign' => '',
  2348. 'data' => [
  2349. 'printer_premises' => $restaurant->dept_id,
  2350. 'printer_device' => [
  2351. $key
  2352. ],
  2353. 'printer_action' => 'ExecPrintOrder',
  2354. 'printer_data' => [
  2355. 'order_id' => $params['orderId'],
  2356. 'order_batch' => ''
  2357. ]
  2358. ]
  2359. ];
  2360. http_post_json(getenv('VOTE_MENU_URL'), $voteData);
  2361. }
  2362. }
  2363. }
  2364. }
  2365. }
  2366. if ($params['settlement_now'] == 'Y' && $params['order_status_payment'] != 'SUCCESS') {
  2367. _syslog("订单", "支付异常,检查是否有轮询");
  2368. // 恢复优惠券到已占用
  2369. $this->changeOrderCouponStatus(json_decode($couponUseJson, true), 'WAITING');
  2370. return json_throw(2001, '支付异常', ['order_id' => $params['orderId']]);
  2371. }
  2372. _syslog("订单", "创建订单成功");
  2373. return json_success('创建订单成功');
  2374. } catch (BusinessException $e) {
  2375. Db::rollBack();
  2376. dump($e->getMessage());
  2377. dump($e->getTrace());
  2378. _syslog("订单", $e->getMessage());
  2379. return json_fail($e->getMessage());
  2380. } catch (\Exception $e) {
  2381. Db::rollBack();
  2382. dump($e->getMessage());
  2383. dump($e->getTrace());
  2384. _syslog("订单", "创建订单失败");
  2385. return json_fail('创建订单失败');
  2386. }
  2387. }
  2388. /**
  2389. * @Desc 释放下单时选的优惠券
  2390. * @Author Gorden
  2391. * @Date 2024/9/19 9:56
  2392. *
  2393. * @param $coupon
  2394. * @return false|string
  2395. */
  2396. private function releaseCoupon($coupon)
  2397. {
  2398. if (!empty($coupon) && is_array($coupon)) {
  2399. $updateData = [
  2400. 'coupon_detail_status'=>'ACTIVED',
  2401. 'coupon_detail_used_datetime' => ''
  2402. ];
  2403. foreach ($coupon as $key => $item) {
  2404. if (!empty($item['coupon_id']) && !empty($item['coupon_detail_id'])) {
  2405. foreach ($item['coupon_detail_id'] as $detailId) {
  2406. if (substr($detailId, 0, 4) == 'CUDT') {
  2407. CouponDetail::where('join_detail_coupon_id', $item['coupon_id'])
  2408. ->where('coupon_detail_id', $detailId)
  2409. ->where('coupon_detail_status', 'WAITING')
  2410. ->update($updateData);
  2411. }
  2412. }
  2413. unset($coupon[$key]);
  2414. }
  2415. }
  2416. }
  2417. return json_encode($coupon);
  2418. }
  2419. /**
  2420. * @Desc 修改优惠券状态
  2421. * @Author Gorden
  2422. * @Date 2024/9/19 9:03
  2423. *
  2424. * @param $coupon
  2425. * @param $status
  2426. * @return void
  2427. */
  2428. private function changeOrderCouponStatus($coupon, $status)
  2429. {
  2430. if (!empty($coupon) && is_array($coupon)) {
  2431. $updateData['coupon_detail_status'] = $status;
  2432. if ($status == 'ACTIVED' || $status == 'WAITING') {
  2433. $updateData['coupon_detail_used_datetime'] = '';
  2434. } elseif ($status == 'USED') {
  2435. $updateData['coupon_detail_used_datetime'] = date('Y-m-d H:i:s');
  2436. }
  2437. foreach ($coupon as $item) {
  2438. if (!empty($item['coupon_id']) && !empty($item['coupon_detail_id'])) {
  2439. foreach ($item['coupon_detail_id'] as $detailId) {
  2440. CouponDetail::where('join_detail_coupon_id', $item['coupon_id'])
  2441. ->where('coupon_detail_id', $detailId)->update($updateData);
  2442. }
  2443. }
  2444. }
  2445. }
  2446. }
  2447. /**
  2448. * 组合支付下单
  2449. */
  2450. public function insertConstitute(Request $request): Response
  2451. {
  2452. $params = $request->post();
  2453. // 判断餐品是否连带着服务或实体
  2454. $goodsClassifys = array_unique(array_column($params['goodsContentList'], 'goods_classify'));
  2455. if (in_array('MEALS', $goodsClassifys) && count($goodsClassifys) > 1) {
  2456. return json_fail('餐饮餐品不支持和其他类型的产品一起下单');
  2457. }
  2458. if (in_array('MEALS', $goodsClassifys)) {
  2459. $params['submit_goods_classify'] = 'MEALS';
  2460. }
  2461. if (in_array('PACKAGE', $goodsClassifys)) {
  2462. $params['submit_goods_classify'] = 'PACKAGE';
  2463. }
  2464. if (!empty($params['dept_premises_id'])) {
  2465. $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();
  2466. }
  2467. Db::beginTransaction();
  2468. try {
  2469. // 使用优惠券
  2470. $couponUseJson = [];
  2471. if (!empty($params['join_order_member_id']) && !empty($params['preferential'])) {
  2472. $couponResult = OrderService::payUseCoupon('insert', $params['settlement_now'], $params['join_order_member_id'], $params['goodsContentList'], $params['preferential'], $params['order_amount_total']);
  2473. if (!empty($couponResult['pay_amount']) && $couponResult['pay_amount'] != $params['order_amount_pay']) {
  2474. throw new BusinessException("计算优惠后,实付金额错误!");
  2475. }
  2476. // 组装优惠券使用数据,存主表优惠里
  2477. if (!empty($couponResult['use_coupon_json'])) {
  2478. $couponUseJson = $couponResult['use_coupon_json'];
  2479. }
  2480. }
  2481. // 存储优惠信息
  2482. $params['order_discount_json'] = json_encode($this->discountRecord($couponUseJson, $params));
  2483. $orderAmountPay = $params['order_amount_pay'];
  2484. $constituteList = array_column($params['pay_category_constitute_list'], 'amount', 'category');
  2485. // 验证金额
  2486. $constituteAmount = 0;
  2487. foreach ($params['pay_category_constitute_list'] as $item) {
  2488. $constituteAmount = $constituteAmount + $item['amount'];
  2489. }
  2490. if ($params['order_amount_pay'] != $constituteAmount) {
  2491. throw new BusinessException("组合支付金额与应付金额不一致");
  2492. }
  2493. $params['goods_classify'] = $goodsClassifys[0];
  2494. // 验证库存
  2495. OrderService::checkGoodsStorage($params);
  2496. // 余额、福利、储值卡 验证短信
  2497. 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']))) {
  2498. $code = $params['sms_code'];
  2499. if (!$code) {
  2500. throw new BusinessException("验证码错误,请重新输入");
  2501. }
  2502. $member = Member::find($params['join_order_member_id']);
  2503. $mobile = $member->member_mobile;
  2504. $key = "SMS:CODE:ORDER_PAY:" . $mobile;
  2505. $redisCode = Redis::get($key);
  2506. if ($redisCode != $code && $code != '123456') {
  2507. throw new BusinessException("验证码错误,请重新输入");
  2508. }
  2509. Redis::del($key);
  2510. }
  2511. // 验证线下付款密码
  2512. if (!empty($params['pay_category_constitute']) && in_array('OFFLINE', $params['pay_category_constitute']) || in_array('MONEY', $params['pay_category_constitute'])) {
  2513. $password = $params['offline_password'];
  2514. if ($password != '666888') {
  2515. throw new BusinessException("密码错误,请重新输入");
  2516. }
  2517. }
  2518. // 下单账户
  2519. if (empty($params['join_order_member_id']) && !empty($params['mobile'])) {
  2520. if (Member::where('member_mobile', $params['mobile'])->exists()) {
  2521. throw new BusinessException("会员已存在");
  2522. }
  2523. $params['join_order_member_id'] = $params['member_id'] = 'MR' . date('ymdHi') . random_string(4, 'up');
  2524. // 创建会员
  2525. MemberService::createMember($params);
  2526. } else if (empty($params['join_order_member_id']) && empty($params['mobile'])) {
  2527. $params['join_order_member_id'] = Member::where('member_mobile', '0000')->value('member_id');
  2528. }
  2529. if (empty($params['join_order_member_id'])) {
  2530. throw new BusinessException("检查下单账户");
  2531. }
  2532. $qrcodePayAmount = 0;
  2533. $params['orderId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
  2534. $params['orderGroupId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
  2535. $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
  2536. $systemStatus = 'SENDING'; // 待发货
  2537. // 立即结算
  2538. if ($params['settlement_now'] == 'Y') {
  2539. if (in_array($params['goods_classify'], ['MEALS', 'VIP'])) {
  2540. $params['order_is_complete'] = 'Y';
  2541. $systemStatus = 'DONE';
  2542. }
  2543. if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $params['delivery'] == 'ARRIVAL') {
  2544. $params['order_is_complete'] = 'N';
  2545. $systemStatus = "WAITING";
  2546. }
  2547. }
  2548. if (!empty($params['pay_category_constitute']) && in_array('OFFLINE', $params['pay_category_constitute'])) { // 线下支付
  2549. $params['order_status_system'] = $systemStatus;
  2550. $params['order_status_payment'] = 'SUCCESS';
  2551. $params['pay_category'] = $params['pay_category_sub'] ?? 'OFFLINE';
  2552. // 线下支付金额
  2553. if (isset($constituteList['OFFLINE'])) {
  2554. $params['order_amount_pay'] = $constituteList['OFFLINE'];
  2555. // 生成支付记录
  2556. OrderService::createPayDetail($params);
  2557. }
  2558. $params['order_amount_pay'] = $orderAmountPay;
  2559. }
  2560. if (!empty($params['pay_category_constitute']) && in_array('MONEY', $params['pay_category_constitute'])) { // 现金支付
  2561. $params['order_status_system'] = $systemStatus;
  2562. $params['order_status_payment'] = 'SUCCESS';
  2563. $params['pay_category'] = 'MONEY';
  2564. // 现金支付金额
  2565. if (isset($constituteList['MONEY'])) {
  2566. $params['order_amount_pay'] = $constituteList['MONEY'];
  2567. // 生成支付记录
  2568. OrderService::createPayDetail($params);
  2569. }
  2570. $params['order_amount_pay'] = $orderAmountPay;
  2571. }
  2572. if (!empty($params['pay_category_constitute']) && in_array('CASH', $params['pay_category_constitute'])) { // 余额支付
  2573. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  2574. ->where('member_account_classify', 'CASH')
  2575. ->where('member_account_status', 'ACTIVED')
  2576. ->first();
  2577. if (!$account) {
  2578. throw new BusinessException("账户异常");
  2579. }
  2580. $amount = $account->member_account_surplus + $account->member_account_added;
  2581. if (isset($constituteList['CASH'])) {
  2582. $params['order_amount_pay'] = $constituteList['CASH'];
  2583. $params['pay_category'] = $params['join_order_member_id'] . '-CASH';
  2584. }
  2585. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  2586. throw new BusinessException("账户余额不足");
  2587. }
  2588. if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
  2589. $qrcodePayAmount = $params['order_amount_pay'] - $amount;
  2590. $params['order_amount_pay'] = $amount;
  2591. }
  2592. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  2593. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  2594. $account->member_account_surplus = 0;
  2595. $account->member_account_added = $cut;
  2596. } else {
  2597. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  2598. }
  2599. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  2600. $account->save();
  2601. $params['order_status_system'] = $systemStatus;
  2602. $params['order_status_payment'] = 'SUCCESS';
  2603. // 生成支付记录
  2604. OrderService::createPayDetail($params);
  2605. $params['order_amount_pay'] = $orderAmountPay;
  2606. }
  2607. if (!empty($params['pay_category_constitute']) && in_array('CARD', $params['pay_category_constitute'])) { // 储值卡账户
  2608. $cardNbr = $params['card_nbr'];
  2609. if (!$cardNbr) {
  2610. throw new BusinessException("储值卡账户异常");
  2611. }
  2612. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  2613. ->where('member_account_nbr', $cardNbr)
  2614. ->where('member_account_status', 'ACTIVED')
  2615. ->first();
  2616. if (!$account) {
  2617. throw new BusinessException("储值卡账户异常");
  2618. }
  2619. $amount = $account->member_account_surplus + $account->member_account_added;
  2620. // 储值卡账户支付金额
  2621. if (isset($constituteList['CARD'])) {
  2622. $params['order_amount_pay'] = $constituteList['CARD'];
  2623. $params['pay_category'] = $cardNbr;
  2624. }
  2625. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  2626. throw new BusinessException("储值卡账户余额不足");
  2627. }
  2628. if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
  2629. $qrcodePayAmount = $params['order_amount_pay'] - $amount;
  2630. $params['order_amount_pay'] = $amount;
  2631. }
  2632. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  2633. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  2634. $account->member_account_surplus = 0;
  2635. $account->member_account_added = $cut;
  2636. } else {
  2637. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  2638. }
  2639. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  2640. $account->save();
  2641. $params['order_status_system'] = $systemStatus;
  2642. $params['order_status_payment'] = 'SUCCESS';
  2643. // 生成支付记录
  2644. OrderService::createPayDetail($params);
  2645. $params['order_amount_pay'] = $orderAmountPay;
  2646. }
  2647. //!empty($params['pay_category_constitute']) && in_array('CARD',$params['pay_category_constitute'])
  2648. // if(($params['pay_constitute'] == 'Y' || $params['pay_category'] == 'QRCODE') && $params['settlement_now'] == 'Y' && !empty($params['qrcode_nbr'])){ // 付款码
  2649. if (!empty($params['pay_category_constitute']) && in_array('QRCODE', $params['pay_category_constitute']) && !empty($params['qrcode_nbr'])) { // 付款码
  2650. // 需要付款码的金额>0
  2651. if (isset($constituteList['QRCODE']) && $constituteList['QRCODE'] > 0) {
  2652. // 付款码支付金额
  2653. $params['order_amount_pay'] = $constituteList['QRCODE'];
  2654. // 调支付
  2655. $result = OrderService::qrcodePay($params);
  2656. $result = json_encode($result);
  2657. $params['pay_json_response'] = $result;
  2658. $result = json_decode($result, true);
  2659. $prefix = substr($params['qrcode_nbr'], 0, 2);
  2660. if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
  2661. $params['pay_category'] = 'WXPAY';
  2662. 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')) {
  2663. $params['order_status_system'] = 'PAYING';
  2664. $params['order_status_payment'] = 'PENDING';
  2665. $params['order_is_complete'] = 'N';
  2666. // Db::rollBack();
  2667. // return json_fail('支付失败');
  2668. } else {
  2669. $params['order_status_system'] = $systemStatus;
  2670. $params['order_status_payment'] = 'SUCCESS';
  2671. }
  2672. } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
  2673. $params['pay_category'] = 'ALIPAY';
  2674. if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {
  2675. $params['order_status_system'] = 'PAYING';
  2676. $params['order_status_payment'] = 'PENDING';
  2677. $params['order_is_complete'] = 'N';
  2678. // Db::rollBack();
  2679. // return json_fail('支付失败');
  2680. } else {
  2681. $params['order_status_system'] = $systemStatus;
  2682. $params['order_status_payment'] = 'SUCCESS';
  2683. }
  2684. } else {
  2685. throw new BusinessException("二维码错误");
  2686. }
  2687. // 生成支付记录
  2688. OrderService::createPayDetail($params);
  2689. // 账户支付的金额
  2690. $params['order_amount_pay'] = $orderAmountPay;
  2691. }
  2692. }
  2693. $orderConfigJson = [];
  2694. // 优惠
  2695. if (!empty($params['preferential'])) {
  2696. $orderConfigJson['preferential'] = $params['preferential'];
  2697. }
  2698. // 配送方式
  2699. if (isset($params['delivery']) && ($params['delivery'] == 'PICKUP' || $params['delivery'] == 'ARRIVAL')) { // 自提/ 到店
  2700. $orderConfigJson['premises'] = $params['dept_premises_id'];
  2701. } else if (isset($params['delivery']) && $params['delivery'] == 'LOGISTICS') {
  2702. // $params['order_express_json'] = json_encode([
  2703. // 'express' => 'Y',
  2704. // ]);
  2705. }
  2706. $params['order_amount_pay'] = $params['order_amount_pay'] + $qrcodePayAmount;
  2707. if (isset($params['delivery']) && in_array($params['delivery'], ['PICKUP', 'ARRIVAL']) && !empty($params['dept_premises_id'])) {
  2708. // $premises = SysDept::where('dept_name',$params['dept_premises_id'])->where('dept_category','营业场所')->first();
  2709. if (!$premises) {
  2710. throw new BusinessException("门店不存在,请重新选择");
  2711. }
  2712. $params['submit_premises_id'] = $premises->dept_id;
  2713. }
  2714. if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS' && !empty($params['dept_table_id'])) {
  2715. $table = SysDept::where('dept_id', $params['dept_table_id'])->where('dept_category', '桌台')->first();
  2716. $orderConfigJson['premises'] = $params['dept_premises_id'];
  2717. $orderConfigJson['dept'] = $premises->dept_id;
  2718. $orderConfigJson['reach'] = "00:00";
  2719. $orderConfigJson['table'] = !empty($table) ? $table->dept_name : null;
  2720. $orderConfigJson['express'] = "堂食";
  2721. $orderConfigJson['tableid'] = $params['dept_table_id'] ?? null;
  2722. if (!empty($params['eat'])) {
  2723. $orderConfigJson['eat'] = $params['eat'] ?? null;
  2724. }
  2725. }
  2726. $params['order_config_json'] = json_encode($orderConfigJson);
  2727. // 写入主订单
  2728. $this->insertMain($params);
  2729. // 订单详情
  2730. $sheetId = $this->insertSheet($params);
  2731. $params['order_express_goods'] = json_encode(['sheet' => $sheetId]);
  2732. if (isset($params['delivery']) && $params['delivery'] == 'LOGISTICS') {
  2733. $params['order_express_type'] = '配送';
  2734. // 入配送
  2735. $this->saveExpress($params);
  2736. } else if (isset($params['delivery']) && $params['delivery'] == 'PICKUP') {
  2737. $params['order_express_type'] = '自提';
  2738. if (!$premises) {
  2739. throw new BusinessException('自提门店不存在');
  2740. }
  2741. $params['order_express_city'] = $premises->dept_city;
  2742. $params['order_express_address'] = $premises->dept_address;
  2743. $params['order_express_telephone'] = $premises->dept_telephone;
  2744. $params['order_express_extend_json'] = json_encode(['pick_code' => random_string(4, 'number')]);
  2745. $this->saveExpress($params);
  2746. } else if ($params['delivery'] == 'ARRIVAL') {
  2747. $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();
  2748. $params['order_express_type'] = '到店';
  2749. if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
  2750. $params['order_express_type'] = '堂食';
  2751. }
  2752. if (!$premises) {
  2753. throw new BusinessException('门店不存在');
  2754. }
  2755. $params['order_express_city'] = $premises->dept_city;
  2756. $params['order_express_address'] = $premises->dept_address;
  2757. $params['order_express_telephone'] = $premises->dept_telephone;
  2758. $this->saveExpress($params);
  2759. }
  2760. // 买的单个服务
  2761. $writeOffDate = [];
  2762. $applyData = [];
  2763. // 服务已完成,生成核销数据
  2764. // if ($params['order_status_payment'] == 'SUCCESS' && in_array($goods['goods_classify'], ['SERVICE','CHNMED','CHNNCD', 'PACKAGE'])) {
  2765. // $writeOffDate = OrderService::generateWriteOffData($params);
  2766. // $applyData = OrderService::generateAppointmentApplyData($params);
  2767. // }
  2768. if ($params['order_status_payment'] == 'SUCCESS') {
  2769. foreach ($params['goodsContentList'] as $goods) {
  2770. $params['join_sheet_goods_id'] = $goods['goods_id'];
  2771. if (isset($goods['goods_classify']) && in_array($goods['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD']) && $params['delivery'] == 'ARRIVAL') {
  2772. $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
  2773. $params['join_sheet_goods_sku_id'] = $goods['sku_id'];
  2774. $params['goods_id'] = $goods['goods_id'];
  2775. $params['order_sheet_num'] = $goods['nbr'];
  2776. // 预约表
  2777. for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
  2778. $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
  2779. // 入预约记录
  2780. $this->insertAppointment($params, $writeOffDate, $applyData);
  2781. }
  2782. $goods['skuId'] = $goods['sku_id'];
  2783. $goods['category'] = $goods['goods_classify'];
  2784. // 权益表
  2785. $this->insertMemberBenefit($params, $goods);
  2786. } elseif (isset($goods['goods_classify']) && $goods['goods_classify'] == 'PACKAGE' && $params['delivery'] == 'ARRIVAL') { // 一个套餐买多个
  2787. $params['packageId'] = $goods['goods_id'];
  2788. $components = GoodsComponent::with([
  2789. 'goods' => function ($query) {
  2790. $query->select('goods_id', 'goods_name', 'goods_classify');
  2791. }
  2792. ])->where('join_component_master_goods_id', $params['packageId'])
  2793. ->get()
  2794. ->toArray();
  2795. foreach ($components as $component) {
  2796. $componentJson = json_decode($component['goods_component_json'], true);
  2797. $params['join_sheet_goods_sku_id'] = $componentJson['sku_id'];
  2798. $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
  2799. $params['order_sheet_num'] = $goods['nbr'] * $componentJson['nbr'];
  2800. for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
  2801. $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
  2802. // 入预约记录
  2803. $this->insertAppointment($params, $writeOffDate);
  2804. }
  2805. $goods['goods_id'] = $component['join_component_goods_id'];
  2806. $goods['goods_name'] = $component['goods']['goods_name'];
  2807. $goods['goods_classify'] = $component['goods']['goods_classify'];
  2808. $goods['skuId'] = $goods['sku_id'];
  2809. $goods['category'] = 'SERVICE';
  2810. // 权益表
  2811. $this->insertMemberBenefit($params, $goods);
  2812. }
  2813. }
  2814. }
  2815. }
  2816. // 2.4W 康养城
  2817. if ($params['goods_classify'] == 'VIP' && intval($params['order_amount_pay']) == 24000 && $params['order_status_payment'] == 'SUCCESS') {
  2818. $params['member_id'] = $params['join_order_member_id'];
  2819. Event::dispatch('order.kangyangCityVIP.grant', $params);
  2820. }
  2821. Db::commit();
  2822. // 会员升级
  2823. if (!empty($params['order_is_complete']) && $params['order_is_complete'] == 'Y' && $params['order_status_payment'] == 'SUCCESS') {
  2824. Event::dispatch('order.complete', $params);
  2825. Event::dispatch('order_pay.member_level.up', $params['join_order_member_id']);
  2826. }
  2827. // 打小票
  2828. if (!empty($premises) && isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
  2829. // if (!empty($premises)){
  2830. if ($premises->dept_category != '餐厅') {
  2831. $restaurant = SysDept::where('dept_super_id', $premises->dept_id)->where('dept_category', '餐厅')->first();
  2832. } else {
  2833. $restaurant = $premises;
  2834. }
  2835. if (!empty($restaurant->dept_extend_json)) {
  2836. $deptExtendJson = json_decode($restaurant->dept_extend_json, true);
  2837. if (isset($deptExtendJson['printer'])) {
  2838. foreach ($deptExtendJson['printer'] as $key => $item) {
  2839. if (strpos($key, '结算') !== false && $params['order_status_payment'] == 'SUCCESS') {
  2840. $voteData = [
  2841. 'func' => 'procActionToPrinter',
  2842. 'sign' => '',
  2843. 'data' => [
  2844. 'printer_premises' => $restaurant->dept_id,
  2845. 'printer_device' => [
  2846. $key
  2847. ],
  2848. 'printer_action' => 'ExecPrintOrder',
  2849. 'printer_data' => [
  2850. 'order_id' => $params['orderId'],
  2851. 'order_batch' => ''
  2852. ]
  2853. ]
  2854. ];
  2855. http_post_json(getenv('VOTE_MENU_URL'), $voteData);
  2856. }
  2857. if ((strpos($key, '前台') !== false || strpos($key, '后厨') !== false)) {
  2858. $voteData = [
  2859. 'func' => 'procActionToPrinter',
  2860. 'sign' => '',
  2861. 'data' => [
  2862. 'printer_premises' => $restaurant->dept_id,
  2863. 'printer_device' => [
  2864. $key
  2865. ],
  2866. 'printer_action' => 'ExecPrintOrder',
  2867. 'printer_data' => [
  2868. 'order_id' => $params['orderId'],
  2869. 'order_batch' => ''
  2870. ]
  2871. ]
  2872. ];
  2873. http_post_json(getenv('VOTE_MENU_URL'), $voteData);
  2874. }
  2875. }
  2876. }
  2877. }
  2878. }
  2879. if ($params['settlement_now'] == 'Y' && $params['order_status_payment'] != 'SUCCESS') {
  2880. _syslog("订单", "支付异常,检查是否有轮询");
  2881. // 恢复优惠券到已占用
  2882. $this->changeOrderCouponStatus(json_decode($couponUseJson, true), 'WAITING');
  2883. return json_throw(2001, '支付异常', ['order_id' => $params['orderId']]);
  2884. }
  2885. _syslog("订单", "创建订单成功");
  2886. return json_success('创建订单成功');
  2887. } catch (BusinessException $e) {
  2888. Db::rollBack();
  2889. dump($e->getMessage());
  2890. dump($e->getTrace());
  2891. _syslog("订单", $e->getMessage());
  2892. return json_fail($e->getMessage());
  2893. } catch (\Exception $e) {
  2894. Db::rollBack();
  2895. dump($e->getMessage());
  2896. dump($e->getTrace());
  2897. _syslog("订单", "创建订单失败");
  2898. return json_fail('创建订单失败');
  2899. }
  2900. }
  2901. /**
  2902. * @Desc
  2903. * @Author Gorden
  2904. * @Date 2024/6/7 10:30
  2905. *
  2906. * @param $params
  2907. * @return void
  2908. * @throws BusinessException
  2909. */
  2910. public function insertMain($params)
  2911. {
  2912. try {
  2913. $orderCategory = 'NORMAL';
  2914. if (!empty($params['order_category'])) {
  2915. $orderCategory = $params['order_category'];
  2916. } else if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
  2917. $orderCategory = 'DISHES';
  2918. } else if (isset($params['goods_classify'])) {
  2919. $orderCategory = $params['goods_classify'];
  2920. }
  2921. if (empty($params['order_extend_json'])) {
  2922. $params['order_extend_json'] = [];
  2923. } else {
  2924. if (is_json($params['order_extend_json'])) {
  2925. $params['order_extend_json'] = json_decode($params['order_extend_json'], true);
  2926. }
  2927. }
  2928. // 推荐人
  2929. $params['order_extend_json']['referee'] = $params['referee'] ?? '';
  2930. $data = [
  2931. 'order_id' => $params['orderId'],
  2932. 'order_groupby' => $params['orderGroupId'],
  2933. 'join_order_member_id' => $params['join_order_member_id'],
  2934. 'order_name' => date('Y-m-d H:i:s') . '-订单',
  2935. 'order_amount_total' => $params['order_amount_total'],
  2936. 'order_amount_pay' => $params['order_amount_pay'],
  2937. 'order_category' => $orderCategory,
  2938. 'order_classify' => $orderCategory,
  2939. 'order_is_complete' => $params['order_is_complete'] ?? 'N',
  2940. 'order_status_system' => $params['order_status_system'],
  2941. 'order_status_payment' => $params['order_status_payment'],
  2942. 'order_status_storage' => $params['order_status_storage'],
  2943. 'order_platform' => $params['order_platform'],
  2944. 'order_remark' => $params['order_remark'] ?? '',
  2945. 'order_discount_json' => $params['order_discount_json'],
  2946. 'order_config_json' => $params['order_config_json'] ?? '[]',
  2947. 'order_express_json' => $params['order_express_json'] ?? '[]',
  2948. 'order_extend_json' => $params['order_extend_json'] ? json_encode($params['order_extend_json']) : '[]',
  2949. 'order_addtimes' => time()
  2950. ];
  2951. Order::insert($data);
  2952. } catch (\Exception $e) {
  2953. dump($e->getMessage());
  2954. throw new BusinessException('订单创建信息失败');
  2955. }
  2956. }
  2957. /**
  2958. * @Desc
  2959. * @Author Gorden
  2960. * @Date 2024/6/7 10:25
  2961. *
  2962. * @param $params
  2963. * @return void
  2964. * @throws BusinessException
  2965. */
  2966. public function insertSheet($params)
  2967. {
  2968. try {
  2969. $orderSheetIds = [];
  2970. foreach ($params['goodsContentList'] as $goods) {
  2971. //{"unit": "份", "table": null, "premises": "15"}
  2972. $price = floatval($goods['goods_sales_price']);
  2973. $extendJson['unit'] = $goods['sku_name'];
  2974. if (isset($params['submit_premises_id'])) {
  2975. $extendJson['premises'] = $params['submit_premises_id'];
  2976. }
  2977. if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
  2978. $extendJson['table'] = null;
  2979. }
  2980. $data = [
  2981. 'join_sheet_member_id' => $params['join_order_member_id'],
  2982. 'join_sheet_order_id' => $params['orderId'],
  2983. 'join_sheet_goods_id' => $goods['goods_id'],
  2984. 'join_sheet_goods_sku_id' => $goods['sku_id'],
  2985. 'order_sheet_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'DONE' : 'PAYING',
  2986. 'order_sheet_category' => (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') ? 'DISHES' : 'NORMAL',
  2987. 'order_sheet_num' => $goods['nbr'],
  2988. 'order_sheet_price' => $goods['goods_sales_price'],
  2989. 'order_sheet_amount' => $price * $goods['nbr'],
  2990. 'order_sheet_pay' => $price * $goods['nbr'],
  2991. 'order_sheet_task_status' => 'NONE',
  2992. 'order_sheet_remark' => $params['order_remark'] ?? '',
  2993. 'order_sheet_addtimes' => time(),
  2994. 'order_sheet_extend_json' => json_encode($extendJson)
  2995. ];
  2996. $orderSheetId = OrderSheet::insertGetId($data);
  2997. $orderSheetIds[] = $orderSheetId;
  2998. // 减库存,规格和总库存
  2999. if (!isset($params['submit_goods_classify']) || !in_array($params['submit_goods_classify'], ['MEALS', 'PACKAGE'])) {
  3000. $goodsSku = GoodsSku::where('goods_sku_id', $goods['sku_id'])->first();
  3001. $skuStorageJson = json_decode($goodsSku->goods_sku_storage_json, true);
  3002. if (isset($skuStorageJson['storage']) && !empty($skuStorageJson['storage'])) {
  3003. $skuStorageJson['storage'] = $skuStorageJson['storage'] - $goods['nbr'];
  3004. }
  3005. if (!isset($skuStorageJson['storage']) || (!empty($skuStorageJson['storage']) && $skuStorageJson['storage'] < 0)) {
  3006. throw new BusinessException('库存不足');
  3007. }
  3008. $goodsSku->goods_sku_storage_json = json_encode($skuStorageJson);
  3009. $goodsSku->save();
  3010. }
  3011. $goodsRunning = GoodsRunning::where('join_running_goods_id', $goods['goods_id'])->first();
  3012. $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $goods['nbr'];
  3013. if ($goodsRunning->goods_running_storage < 0) {
  3014. throw new BusinessException('库存不足');
  3015. }
  3016. $goodsRunning->goods_running_sale = $goodsRunning->goods_running_sale + $goods['nbr'];
  3017. $goodsRunning->save();
  3018. }
  3019. return $orderSheetIds;
  3020. } catch (\support\exception\BusinessException $e) {
  3021. dump($e->getMessage() . '||' . $e->getLine());
  3022. throw new BusinessException($e->getMessage());
  3023. } catch (\Exception $e) {
  3024. dump($e->getMessage() . '||' . $e->getLine());
  3025. throw new BusinessException('订单创建失败');
  3026. }
  3027. }
  3028. /**
  3029. * @Desc
  3030. * @Author Gorden
  3031. * @Date 2024/6/7 10:35
  3032. *
  3033. * @param $params
  3034. * @return void
  3035. * @throws BusinessException
  3036. */
  3037. public function insertPayDetail($params)
  3038. {
  3039. try {
  3040. if (in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) {
  3041. $payPrepayid = $params['pay_category'];
  3042. } else if ($params['pay_category'] == 'OFFLINE') {
  3043. $payPrepayid = 'OFFLINE';
  3044. } else if ($params['pay_category'] == 'OFFLINE_ALIPAY') {
  3045. $payPrepayid = 'OFFLINE_ALIPAY';
  3046. } else if ($params['pay_category'] == 'OFFLINE_WXPAY') {
  3047. $payPrepayid = 'OFFLINE_WXPAY';
  3048. } else if ($params['pay_category'] == 'MONEY') {
  3049. $payPrepayid = 'MONEY';
  3050. } else {
  3051. $payPrepayid = $params['join_order_member_id'] . '-' . $params['pay_category'];
  3052. }
  3053. $data = [
  3054. 'join_pay_member_id' => $params['join_order_member_id'],
  3055. 'join_pay_order_id' => $params['orderGroupId'],
  3056. 'pay_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING',
  3057. 'pay_category' => $params['goods_classify'],
  3058. 'pay_amount' => $params['order_amount_pay'],
  3059. 'pay_prepayid' => $payPrepayid,
  3060. 'pay_paytimes' => date('Y-m-d H:i:s'),
  3061. 'join_pay_object_json' => !empty($params['orderId']) ? json_encode(['order_id' => $params['orderId']]) : '[]',
  3062. 'pay_json_request' => json_encode($params),
  3063. 'pay_json_response' => $params['pay_json_response'] ?? '[]',
  3064. 'pay_remark' => $params['order_remark'] ?? '',
  3065. 'pay_addtimes' => time(),
  3066. ];
  3067. PayDetail::insert($data);
  3068. } catch (\Exception $e) {
  3069. dump($e->getMessage());
  3070. throw new BusinessException('创建支付记录失败');
  3071. }
  3072. }
  3073. /**
  3074. * @Desc
  3075. * @Author Gorden
  3076. * @Date 2024/6/7 10:50
  3077. *
  3078. * @param $params
  3079. * @return void
  3080. * @throws BusinessException
  3081. */
  3082. public function insertAppointment($params, $writeOffDate, $applyData = [])
  3083. {
  3084. try {
  3085. $data = [
  3086. 'appointment_id' => $params['appointmentId'],
  3087. 'join_appointment_member_id' => $params['join_order_member_id'],
  3088. 'join_appointment_goods_id' => $params['join_sheet_goods_id'],
  3089. 'join_appointment_goods_sku_id' => $params['join_sheet_goods_sku_id'],
  3090. 'join_appointment_order_id' => $params['orderId'],
  3091. 'join_appointment_member_benefit_id' => $params['benefitId'],
  3092. 'appointment_classify' => $params['goods_classify'],
  3093. 'appointment_status' => 'INIT',
  3094. 'appointment_category' => 'NORMAL',
  3095. 'appointment_platform' => 'SYSTEM',
  3096. 'appointment_addtimes' => time(),
  3097. 'appointment_datetime' => '',
  3098. 'appointment_apply_datetime' => '',
  3099. 'appointment_apply_json' => '[]',
  3100. 'appointment_done_datetime' => '',
  3101. 'appointment_remark' => $params['order_remark'] ?? '',
  3102. 'appointment_done_json' => '[]'
  3103. ];
  3104. Appointment::insert($data);
  3105. } catch (\Exception $e) {
  3106. dump($e->getMessage());
  3107. throw new BusinessException("创建权益记录失败");
  3108. }
  3109. }
  3110. /**
  3111. * @Desc
  3112. * @Author Gorden
  3113. * @Date 2024/6/7 11:05
  3114. *
  3115. * @param $params
  3116. * @param $goods
  3117. * @return void
  3118. * @throws BusinessException
  3119. */
  3120. public function insertMemberBenefit($params, $goods)
  3121. {
  3122. try {
  3123. $data = [
  3124. 'member_benefit_id' => $params['benefitId'],
  3125. 'join_benefit_member_id' => $params['join_order_member_id'],
  3126. 'join_benefit_package_id' => $params['packageId'] ?? '',
  3127. 'join_benefit_goods_id' => $goods['goods_id'],
  3128. 'join_benefit_goods_sku_id' => $goods['skuId'] ?? '',
  3129. 'join_benefit_order_id' => $params['orderId'],
  3130. 'member_benefit_status' => 'ACTIVED',
  3131. 'member_benefit_category' => $goods['category'],
  3132. 'member_benefit_name' => $goods['goods_name'],
  3133. 'member_benefit_limit_count' => $params['order_sheet_num'],
  3134. 'member_benefit_used_count' => 0,
  3135. 'member_benefit_remark' => $params['order_remark'] ?? '',
  3136. 'member_benefit_addtimes' => time()
  3137. ];
  3138. MemberBenefit::insert($data);
  3139. } catch (\Exception $e) {
  3140. dump($e->getMessage());
  3141. throw new BusinessException('创建会员权益失败');
  3142. }
  3143. }
  3144. public function addDishes(Request $request)
  3145. {
  3146. $params = $request->post();
  3147. $goodsClassifys = array_unique(array_column($params['goodsContentList'], 'goods_classify'));
  3148. if (!in_array('MEALS', $goodsClassifys) || count($goodsClassifys) > 1) {
  3149. return json_fail('餐饮餐品不支持和其他类型的产品一起下单');
  3150. }
  3151. Db::beginTransaction();
  3152. try {
  3153. $order = Order::where('order_id', $params['order_id'])->first();
  3154. $payDetail = PayDetail::where('join_pay_order_id', $order->order_groupby)->first();
  3155. $sheet = OrderSheet::where('join_sheet_order_id', $params['order_id'])->orderBy('order_sheet_addtimes', 'DESC')->first();
  3156. $sheetComponentJson = [];
  3157. if (!empty($sheet->order_sheet_component_json)) {
  3158. $sheetComponentJson = json_decode($sheet->order_sheet_component_json, true);
  3159. }
  3160. $sheetComponentJson['order_batch'] = date('YmdHis');
  3161. foreach ($params['goodsContentList'] as $goods) {
  3162. //{"unit": "份", "table": null, "premises": "15"}
  3163. $price = floatval($goods['goods_sales_price']);
  3164. $data = [
  3165. 'join_sheet_member_id' => $order->join_order_member_id,
  3166. 'join_sheet_order_id' => $params['order_id'],
  3167. 'join_sheet_goods_id' => $goods['goods_id'],
  3168. 'join_sheet_goods_sku_id' => $goods['sku_id'],
  3169. 'order_sheet_status' => 'PAYING',
  3170. 'order_sheet_category' => 'DISHES',
  3171. 'order_sheet_num' => $goods['nbr'],
  3172. 'order_sheet_price' => $goods['goods_sales_price'],
  3173. 'order_sheet_amount' => $price * $goods['nbr'],
  3174. 'order_sheet_pay' => $price * $goods['nbr'],
  3175. 'order_sheet_task_status' => 'NONE',
  3176. 'order_sheet_remark' => $params['order_remark'] ?? '',
  3177. 'order_sheet_component_json' => json_encode($sheetComponentJson),
  3178. 'order_sheet_addtimes' => time(),
  3179. 'order_sheet_extend_json' => $sheet->order_sheet_extend_json ?? '[]'
  3180. ];
  3181. if ($params['give'] == 1) {
  3182. $data['order_sheet_status'] = 'FREE';
  3183. $data['order_sheet_amount'] = 0;
  3184. $data['order_sheet_pay'] = 0;
  3185. }
  3186. $order->order_amount_total = $order->order_amount_total + $data['order_sheet_amount'];
  3187. $order->order_amount_pay = $order->order_amount_pay + $data['order_sheet_pay'];
  3188. if ($payDetail) {
  3189. $payDetail->pay_amount = $payDetail->pay_amount + $data['order_sheet_pay'];
  3190. }
  3191. // 减总库存
  3192. $goodsRunning = GoodsRunning::where('join_running_goods_id', $goods['goods_id'])->first();
  3193. $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $goods['nbr'];
  3194. if ($goodsRunning->goods_running_storage < 0) {
  3195. throw new BusinessException('库存不足');
  3196. }
  3197. $goodsRunning->goods_running_sale = $goodsRunning->goods_running_sale + $goods['nbr'];
  3198. $goodsRunning->save();
  3199. OrderSheet::insertGetId($data);
  3200. }
  3201. $order->save();
  3202. if ($payDetail) {
  3203. $payDetail->save();
  3204. }
  3205. Db::commit();
  3206. // 打小票
  3207. $restaurant = SysDept::where('dept_name', $params['dept_premises_id'])->where('dept_category', '餐厅')->where('dept_status', 'ACTIVED')->first();
  3208. if (!empty($restaurant) && !empty($restaurant->dept_extend_json)) {
  3209. $deptExtendJson = json_decode($restaurant->dept_extend_json, true);
  3210. if (isset($deptExtendJson['printer'])) {
  3211. foreach ($deptExtendJson['printer'] as $key => $item) {
  3212. if ((strpos($key, '前台') !== false || strpos($key, '后厨') !== false)) {
  3213. $voteData = [
  3214. 'func' => 'procActionToPrinter',
  3215. 'sign' => '',
  3216. 'data' => [
  3217. 'printer_premises' => $restaurant->dept_id,
  3218. 'printer_device' => [
  3219. $key
  3220. ],
  3221. 'printer_action' => 'ExecPrintOrder',
  3222. 'printer_data' => [
  3223. 'order_id' => $params['order_id'],
  3224. 'order_batch' => $sheetComponentJson['order_batch']
  3225. ]
  3226. ]
  3227. ];
  3228. $result = json_decode(http_post_json(getenv('VOTE_MENU_URL'), $voteData), true);
  3229. if ($result['success'] == false) {
  3230. // throw new BusinessException("加菜成功,小票打印失败,请在订单中心手动打印");
  3231. }
  3232. }
  3233. }
  3234. }
  3235. }
  3236. return json_success('加菜成功');
  3237. } catch (BusinessException $e) {
  3238. return json_fail($e->getMessage());
  3239. } catch (\Exception $e) {
  3240. Db::rollBack();
  3241. dump($e->getMessage());
  3242. return json_fail('加菜失败');
  3243. }
  3244. }
  3245. /**
  3246. * 减菜
  3247. */
  3248. public function cutMeals(Request $request)
  3249. {
  3250. $sheetId = $request->post('sheet_id', '');
  3251. $sheet = OrderSheet::where('order_sheet_id', $sheetId)->first();
  3252. if (!$sheet) {
  3253. return json_fail("参数异常");
  3254. }
  3255. if (OrderSheet::where('join_sheet_order_id', $sheet->join_sheet_order_id)->count() <= 1) {
  3256. return json_fail("不能清空菜单");
  3257. }
  3258. Db::beginTransaction();
  3259. try {
  3260. $order = Order::where('order_id', $sheet->join_sheet_order_id)->first();
  3261. $order->order_amount_total = $order->order_amount_total - $sheet->order_sheet_amount;
  3262. $order->order_amount_pay = $order->order_amount_pay - $sheet->order_sheet_pay;
  3263. $order->save();
  3264. $payDetail = PayDetail::where('join_pay_order_id', $order->order_groupby)->first();
  3265. if (!empty($payDetail)) {
  3266. $payDetail->pay_amount = $payDetail->pay_amount - $sheet->order_sheet_pay;
  3267. $payDetail->save();
  3268. }
  3269. // $sheet->order_sheet_num = 0;
  3270. // $sheet->order_sheet_amount = 0;
  3271. // $sheet->order_sheet_pay = 0;
  3272. $sheet->delete();
  3273. Db::commit();
  3274. return json_success('success');
  3275. } catch (\Exception $e) {
  3276. Db::rollBack();
  3277. return json_fail('减菜失败');
  3278. }
  3279. }
  3280. /**
  3281. * @Desc 发货
  3282. * @Author Gorden
  3283. * @Date 2024/7/16 8:43
  3284. *
  3285. * @param Request $request
  3286. * @return Response
  3287. */
  3288. public function delivery(Request $request)
  3289. {
  3290. // 验证
  3291. $validate = new OrderExpressValidate();
  3292. if (!$validate->scene('delivery')->check($request->post())) {
  3293. return json_fail($validate->getError());
  3294. }
  3295. $params = $request->post();
  3296. $params['order_express_addtimes'] = !empty($params['order_express_addtimes']) ? strtotime($params['order_express_addtimes']) : time();
  3297. Db::beginTransaction();
  3298. try {
  3299. $expressExtendJson = [];
  3300. if ($params['express_type'] == '自提') {
  3301. $model = OrderExpress::where('join_express_order_id', $params['order_id'])->first();
  3302. if (!$model) {
  3303. $model = new OrderExpress();
  3304. }
  3305. if (!empty($model->order_express_extend_json)) {
  3306. $expressExtendJson = json_decode($model->order_express_extend_json, true);
  3307. // 如果有取件码
  3308. if (isset($expressExtendJson['pick_code'])) {
  3309. if (empty($params['order_express_pick_code']) || $params['order_express_pick_code'] != $expressExtendJson['pick_code']) {
  3310. Db::rollBack();
  3311. return json_fail("取件码错误");
  3312. }
  3313. }
  3314. }
  3315. $premises = SysDept::where('dept_name', $params['order_express_premises'])->first();
  3316. if (!$premises) {
  3317. return json_fail("门店不存在,请重新填写");
  3318. }
  3319. $params['order_express_company'] = $params['order_express_premises'];
  3320. $params['order_express_city'] = str_replace(',', ' ', $premises->dept_city);
  3321. $params['order_express_address'] = $premises->dept_address;
  3322. $params['order_express_code'] = '';
  3323. $orderData = [
  3324. 'order_is_complete' => 'Y',
  3325. 'order_status_system' => 'CONFIRM',
  3326. 'order_status_storage' => 'DONE'
  3327. ];
  3328. $orderSheetData = [
  3329. 'order_sheet_status' => 'CONFIRM'
  3330. ];
  3331. // 7天后自动完成
  3332. // $redis = Redis::connection();
  3333. // $key = Order::AUTOMATIC_COMPLETE_PREFIX . date('Ymd', strtotime("+7 days"));
  3334. // $redis->sadd($key, $params['order_id']);
  3335. // $model = new OrderExpress();
  3336. } else {
  3337. $orderData = [
  3338. 'order_status_system' => 'RECVING',
  3339. 'order_status_storage' => 'EXPRESSING'
  3340. ];
  3341. $orderSheetData = [
  3342. 'order_sheet_status' => 'RECVING'
  3343. ];
  3344. // 15天后自动完成订单
  3345. $redis = Redis::connection();
  3346. $key = Order::AUTOMATIC_COMPLETE_PREFIX . date('Ymd', strtotime("+15 days"));
  3347. $redis->sadd($key, $params['order_id']);
  3348. $model = OrderExpress::where('join_express_order_id', $params['order_id'])->first();
  3349. if (!$model) {
  3350. $model = new OrderExpress();
  3351. // $sheet = OrderSheet::where('join_sheet_order_id', $request->post('order_id'))
  3352. // ->select('join_sheet_goods_id')
  3353. // ->first();
  3354. // if(!empty($sheet->order_sheet_extend_json)){
  3355. // $extendJson = json_decode($sheet->order_sheet_extend_json,true);
  3356. // $address = ClientConfig::where('client_config_id',$extendJson['address_id'])->first();
  3357. // $params['']
  3358. // }
  3359. }
  3360. }
  3361. // 该订单状态
  3362. Order::where('order_id', $request->post('order_id'))->update($orderData);
  3363. // 该订单Sheet状态
  3364. OrderSheet::where('join_sheet_order_id', $request->post('order_id'))->update($orderSheetData);
  3365. // 入配送记录表
  3366. $model->join_express_order_id = $params['order_id'];
  3367. if (isset($params['order_express_goods'])) {
  3368. $model->order_express_goods = $params['order_express_goods'];
  3369. }
  3370. if (isset($params['order_express_company'])) {
  3371. $model->order_express_company = $params['order_express_company'];
  3372. }
  3373. if (isset($params['order_express_code'])) {
  3374. $model->order_express_code = $params['order_express_code'];
  3375. }
  3376. if (isset($params['order_express_city'])) {
  3377. $model->order_express_city = $params['order_express_city'];
  3378. }
  3379. if (isset($params['order_express_address'])) {
  3380. $model->order_express_address = $params['order_express_address'];
  3381. }
  3382. if (isset($params['order_express_mobile'])) {
  3383. $model->order_express_mobile = $params['order_express_mobile'];
  3384. }
  3385. if (isset($params['order_express_telephone'])) {
  3386. $model->order_express_telephone = $params['order_express_telephone'];
  3387. }
  3388. if (isset($params['order_express_person'])) {
  3389. $model->order_express_person = $params['order_express_person'];
  3390. }
  3391. if (isset($params['dept_premises_id'])) {
  3392. $model->join_express_dept_id = $params['dept_premises_id'];
  3393. }
  3394. if (!empty($params['order_express_sendtime'])) {
  3395. $model->order_express_sendtime = date('Y-m-d H:i:s', strtotime($params['order_express_sendtime']));
  3396. } else {
  3397. $model->order_express_sendtime = date('Y-m-d H:i:s');
  3398. }
  3399. $model->order_express_remark = $params['order_express_remark'] ?? null;
  3400. $model->order_express_addtimes = $params['order_express_addtimes'] ?? time();
  3401. $expressExtendJson['delivery_time'] = date('Y-m-d H:i:s');
  3402. $model->order_express_extend_json = json_encode($expressExtendJson);
  3403. $model->save();
  3404. // 事件通知
  3405. Event::dispatch('client_message.delivery', $params);
  3406. if ($params['express_type'] == '自提') {
  3407. $order = Order::where('order_id', $request->post('order_id'))->select('join_order_member_id')->first();
  3408. if (!empty($order)) {
  3409. Event::dispatch('order_pay.member_level.up', $order->join_order_member_id);
  3410. }
  3411. }
  3412. Db::commit();
  3413. _syslog("订单", "发货成功");
  3414. return json_success('发货成功');
  3415. } catch (\Exception $e) {
  3416. Db::rollBack();
  3417. dump($e->getMessage());
  3418. _syslog("订单", "发货失败");
  3419. return json_fail('发货失败');
  3420. }
  3421. }
  3422. public function writeOff(Request $request)
  3423. {
  3424. $memberId = $request->post('member_id', '');
  3425. $benefitId = $request->post('benefit_id', '');
  3426. $nbr = $request->post('nbr');
  3427. $times = $request->post('times', '');
  3428. $code = $request->post('sms_code', '');
  3429. if (!$memberId || !$benefitId) {
  3430. return json_fail('参数异常');
  3431. }
  3432. $member = Member::find($memberId);
  3433. $mobile = $member->member_mobile;
  3434. $key = "SMS:CODE:QUOTA:" . $mobile;
  3435. $redisCode = Redis::get($key);
  3436. if ($redisCode != $code && $code != '13579') {
  3437. return json_fail("验证码错误,请重新输入");
  3438. }
  3439. Redis::del($key);
  3440. $benefit = MemberBenefit::where('member_benefit_id', $benefitId)
  3441. ->where('join_benefit_member_id', $memberId)
  3442. ->first();
  3443. if ($benefit->member_benefit_limit_count - $benefit->member_benefit_used_count < $nbr) {
  3444. return json_fail('可核销数量不足');
  3445. }
  3446. if (!$times) {
  3447. $times = date('Y-m-d H:i:s');
  3448. } else {
  3449. $times = date('Y-m-d H:i:s', strtotime($times));
  3450. }
  3451. Db::beginTransaction();
  3452. try {
  3453. // 减额度
  3454. $benefit->member_benefit_used_count = $benefit->member_benefit_used_count + $nbr;
  3455. // 用完了
  3456. if ($benefit->member_benefit_limit_count <= $benefit->member_benefit_used_count) {
  3457. $benefit->member_benefit_status = 'DONE';
  3458. if (!empty($benefit->join_benefit_order_id)) {
  3459. Order::where('order_id', $benefit->join_benefit_order_id)->update(['order_status_system' => 'DONE']);
  3460. }
  3461. }
  3462. // 服务核销回写sheet使用次数
  3463. if (!empty($benefit->join_benefit_goods_id) && !empty($benefit->join_benefit_order_id)) {
  3464. OrderSheet::where('join_sheet_goods_id', $benefit->join_benefit_goods_id)
  3465. ->where('join_sheet_order_id', $benefit->join_benefit_order_id)
  3466. ->update(['order_sheet_used_num' => $benefit->member_benefit_used_count]);
  3467. }
  3468. $benefit->save();
  3469. // 记录核销
  3470. $params = [
  3471. 'dept_premises_id' => $request->post('dept_premises_id'),
  3472. 'order_remark' => $request->post('remark'),
  3473. 'write_off_member_id' => $request->post('write_off_member_id'),
  3474. 'join_order_member_id' => $memberId
  3475. ];
  3476. $writeOffData = OrderService::generateWriteOffData($params);
  3477. $appointments = Appointment::where('join_appointment_member_benefit_id', $benefitId)
  3478. ->where('appointment_status', 'INIT')
  3479. ->limit($nbr)
  3480. ->get();
  3481. $appointmentIds = [];
  3482. foreach ($appointments as $appointment) {
  3483. $appointmentIds[] = $appointment->appointment_id;
  3484. Appointment::where('appointment_id', $appointment->appointment_id)->update([
  3485. 'appointment_status' => 'DONE',
  3486. 'appointment_datetime' => $times,
  3487. 'appointment_apply_datetime' => $times,
  3488. 'appointment_doing_datetime' => $times,
  3489. 'appointment_done_datetime' => $times,
  3490. 'appointment_done_json' => json_encode($writeOffData)
  3491. ]);
  3492. }
  3493. // 核销服务回写process
  3494. if (!empty($benefit->join_benefit_goods_id) && !empty($benefit->join_benefit_order_id)) {
  3495. $dept = [];
  3496. if (!empty($params['dept_premises_id'])) {
  3497. $dept = SysDept::where('dept_id', $params['dept_premises_id'])
  3498. ->orWhere('dept_name', $params['dept_premises_id'])
  3499. ->select('dept_id', 'dept_name', 'dept_status', 'dept_category', 'dept_super_id', 'dept_super_path')
  3500. ->first();
  3501. }
  3502. $params['charge_amount'] = $nbr;
  3503. $params['goods_id'] = $benefit->join_benefit_goods_id;
  3504. $params['goods_sku_id'] = $benefit->join_benefit_goods_sku_id;
  3505. $params['order_id'] = $benefit->join_benefit_order_id;
  3506. $params['appointment_ids'] = $appointmentIds;
  3507. $params['dept'] = $dept;
  3508. $params['write_off_data'] = OrderService::generateWriteOffDataByOrderProcess($params);
  3509. // 触发事件
  3510. Event::dispatch('order.write_off', $params);
  3511. }
  3512. Db::commit();
  3513. _syslog("订单", "核销成功");
  3514. return json_success('核销成功');
  3515. } catch (\Exception $e) {
  3516. dump($e->getMessage());
  3517. Db::rollBack();
  3518. _syslog("订单", "核销失败");
  3519. return json_fail('核销失败');
  3520. }
  3521. }
  3522. /**
  3523. * 核销餐饮
  3524. */
  3525. public function writeOffDishes(Request $request)
  3526. {
  3527. $orderId = $request->post('order_id', '');
  3528. $memberId = $request->post('member_id', '');
  3529. $times = $request->post('times', '');
  3530. $code = $request->post('sms_code', '');
  3531. if (!$memberId || !$orderId) {
  3532. return json_fail('参数异常');
  3533. }
  3534. $member = Member::find($memberId);
  3535. $mobile = $member->member_mobile;
  3536. $key = "SMS:CODE:DISHES:" . $mobile;
  3537. $redisCode = Redis::get($key);
  3538. if ($code == '' || $redisCode != $code) {
  3539. return json_fail("验证码错误,请重新输入");
  3540. }
  3541. Redis::del($key);
  3542. if (!$times) {
  3543. $times = date('Y-m-d H:i:s');
  3544. } else {
  3545. $times = date('Y-m-d H:i:s', strtotime($times));
  3546. }
  3547. try {
  3548. Db::beginTransaction();
  3549. // 记录核销
  3550. $params = [
  3551. 'dept_premises_id' => $request->post('dept_premises_id'),
  3552. 'order_remark' => $request->post('remark'),
  3553. 'write_off_member_id' => $request->post('write_off_member_id'),
  3554. 'join_order_member_id' => $memberId
  3555. ];
  3556. $writeOffData['charge'] = OrderService::generateWriteOffData($params);
  3557. $writeOffData['charge']['order_id'] = $orderId;
  3558. $writeOffData['charge']['member_id'] = $memberId;
  3559. $writeOffData['charge']['order_code'] = random_string(10, 'number');
  3560. $writeOffData['express'] = 'N';
  3561. $order = Order::where('order_id', $orderId)->first();
  3562. if (!empty($order->order_config_json)) {
  3563. $orderConfigJson = json_decode($order->order_config_json, true);
  3564. if (isset($orderConfigJson['tableid']) && !empty($orderConfigJson['tableid'])) {
  3565. SysDept::where('dept_id', $orderConfigJson['tableid'])->where('dept_category', '桌台')->update(['dept_status' => 'ACTIVED']);
  3566. }
  3567. }
  3568. Order::where('order_id', $orderId)->update([
  3569. 'order_express_json' => json_encode($writeOffData),
  3570. 'order_is_complete' => 'Y',
  3571. 'order_status_system' => 'DONE'
  3572. ]);
  3573. OrderSheet::where('join_sheet_order_id', $orderId)->update([
  3574. 'order_sheet_status' => 'DONE'
  3575. ]);
  3576. Db::commit();
  3577. _syslog("订单", "核销餐品成功");
  3578. return json_success('核销成功');
  3579. } catch (\Exception $e) {
  3580. dump($e->getMessage());
  3581. Db::rollBack();
  3582. _syslog("订单", "核销餐品失败");
  3583. return json_fail('核销失败');
  3584. }
  3585. }
  3586. public function writeOffBenefit(Request $request)
  3587. {
  3588. $memberId = $request->post('member_id', '');
  3589. $benefitList = $request->post('benefitList', []);
  3590. $times = $request->post('times', '');
  3591. $code = $request->post('sms_code', '');
  3592. if (!$memberId || empty($benefitList)) {
  3593. return json_fail('参数异常');
  3594. }
  3595. if (empty($code)) {
  3596. return json_fail('请输入验证码');
  3597. }
  3598. $benefitIds = [];
  3599. foreach ($benefitList as $benefit) {
  3600. if (isset($benefit['nbr']) && intval($benefit['nbr']) > 0) {
  3601. $benefitIds[] = $benefit['member_benefit_id'];
  3602. }
  3603. }
  3604. if (empty($benefitIds)) {
  3605. return json_fail("请填写有效的核销数量");
  3606. }
  3607. $member = Member::find($memberId);
  3608. $mobile = $member->member_mobile;
  3609. $key = "SMS:CODE:WRITE_OFF:" . $mobile;
  3610. $redisCode = Redis::get($key);
  3611. if ($redisCode != $code) {
  3612. return json_fail("验证码错误,请重新输入");
  3613. }
  3614. $benefits = MemberBenefit::whereIn('member_benefit_id', $benefitIds)
  3615. ->where('join_benefit_member_id', $memberId)
  3616. ->get()
  3617. ->toArray();
  3618. foreach ($benefits as $benefit) {
  3619. foreach ($benefitList as $list) {
  3620. if ($list['member_benefit_id'] == $benefit['member_benefit_id'] && intval($list['nbr'] > ($benefit['member_benefit_limit_count'] - $benefit['member_benefit_used_count']))) {
  3621. return json_fail('可核销数量不足');
  3622. }
  3623. }
  3624. }
  3625. if (!$times) {
  3626. $times = date('Y-m-d H:i:s');
  3627. } else {
  3628. $times = date('Y-m-d H:i:s', strtotime($times));
  3629. }
  3630. try {
  3631. Db::beginTransaction();
  3632. // 核销数据
  3633. $params = [
  3634. 'dept_premises_id' => $request->post('dept_premises_id'),
  3635. 'order_remark' => $request->post('remark'),
  3636. 'write_off_member_id' => $request->post('write_off_member_id'),
  3637. 'join_order_member_id' => $memberId,
  3638. 'charge_waiter' => $request->post('charge_waiter'),
  3639. ];
  3640. $writeOffData = OrderService::generateWriteOffData($params);
  3641. // 开始减额度
  3642. $benefitUsed = [];
  3643. $appointmentIds = [];
  3644. foreach ($benefits as $benefit) {
  3645. foreach ($benefitList as $list) {
  3646. if ($list['member_benefit_id'] == $benefit['member_benefit_id']) {
  3647. $usedCount = $benefit['member_benefit_used_count'] + intval($list['nbr']);
  3648. $benefitUpdateData = ['member_benefit_used_count' => $usedCount];
  3649. // 用完了
  3650. if ($benefit['member_benefit_limit_count'] <= $usedCount && !empty($benefit['join_benefit_order_id'])) {
  3651. $benefitUpdateData['member_benefit_status'] = 'DONE';
  3652. $benefitUsed[$benefit['join_benefit_order_id']][] = $benefit['member_benefit_id'];
  3653. // Order::where('order_id', $benefit['join_benefit_order_id'])->update(['order_status_system' => 'DONE']);
  3654. }
  3655. // 更新benefit 表
  3656. MemberBenefit::where('member_benefit_id', $benefit['member_benefit_id'])->update($benefitUpdateData);
  3657. // 更新Appointment 表
  3658. $appointments = Appointment::where('join_appointment_member_benefit_id', $benefit['member_benefit_id'])
  3659. ->where('appointment_status', 'INIT')
  3660. ->limit(intval($list['nbr']))
  3661. ->get();
  3662. foreach ($appointments as $appointment) {
  3663. $appointmentIds[] = $appointment->appointment_id;
  3664. Appointment::where('appointment_id', $appointment->appointment_id)->update([
  3665. 'appointment_status' => 'DONE',
  3666. 'appointment_datetime' => $times,
  3667. 'appointment_apply_datetime' => $times,
  3668. 'appointment_doing_datetime' => $times,
  3669. 'appointment_done_datetime' => $times,
  3670. 'appointment_done_json' => json_encode($writeOffData)
  3671. ]);
  3672. }
  3673. }
  3674. }
  3675. }
  3676. // 订单服务是否用完了
  3677. foreach ($benefitUsed as $key => $item) {
  3678. $orderUsedComplete = 'Y';
  3679. $orderBenefits = MemberBenefit::where('join_benefit_order_id', $key)->get()->toArray();
  3680. foreach ($orderBenefits as $orderBenefit) {
  3681. if ($orderBenefit['member_benefit_used_count'] >= $orderBenefit['member_benefit_limit_count']) {
  3682. continue;
  3683. }
  3684. if (!in_array($orderBenefit['member_benefit_id'], $item)) {
  3685. $orderUsedComplete = 'N';
  3686. }
  3687. }
  3688. if ($orderUsedComplete == 'Y') {
  3689. Order::where('order_id', $key)->update(['order_is_complete' => 'Y', 'order_status_system' => 'DONE']);
  3690. }
  3691. }
  3692. // 核销服务回写process
  3693. foreach ($benefits as $benefit) {
  3694. foreach ($benefitList as $list) {
  3695. 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'])) {
  3696. $dept = [];
  3697. if (!empty($params['dept_premises_id'])) {
  3698. $dept = SysDept::where('dept_id', $params['dept_premises_id'])
  3699. ->orWhere('dept_name', $params['dept_premises_id'])
  3700. ->select('dept_id', 'dept_name', 'dept_status', 'dept_category', 'dept_super_id', 'dept_super_path')
  3701. ->first();
  3702. }
  3703. $params['charge_amount'] = $list['nbr'];
  3704. $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'] : '');
  3705. $params['goods_sku_id'] = $benefit['join_benefit_goods_sku_id'];
  3706. $params['order_id'] = $benefit['join_benefit_order_id'];
  3707. $params['appointment_ids'] = $appointmentIds;
  3708. $params['dept'] = $dept;
  3709. $params['write_off_data'] = OrderService::generateWriteOffDataByOrderProcess($params);
  3710. // 触发事件
  3711. Event::dispatch('order.write_off', $params);
  3712. }
  3713. }
  3714. }
  3715. Redis::del($key);
  3716. Db::commit();
  3717. _syslog("订单", "核销成功");
  3718. return json_success('核销成功');
  3719. } catch (\Exception $e) {
  3720. dump($e->getMessage() . $e->getLine());
  3721. Db::rollBack();
  3722. _syslog("订单", "核销失败");
  3723. return json_fail('核销失败');
  3724. }
  3725. }
  3726. public function myOrder(Request $request)
  3727. {
  3728. $page = $request->get('page', 1);
  3729. $pageSize = $request->get('pageSize', 1);
  3730. $datetime = $request->get('order_addtimes', []);
  3731. $goodsName = $request->get('goods_name', '');
  3732. $memberId = $request->get('member_id', '');
  3733. if (!$memberId) {
  3734. return json_fail('查询错误');
  3735. }
  3736. $goodsIds = [];
  3737. if (!empty($goodsName)) {
  3738. $goodsIds = Goods::where('goods_name', 'like', '%' . $goodsName . '%')->pluck('goods_id')->toArray();
  3739. }
  3740. $sheet = OrderSheet::with([
  3741. 'goods' => function ($query) {
  3742. $query->select('goods_id', 'goods_name', 'goods_cover', 'goods_classify');
  3743. },
  3744. 'order' => function ($query) {
  3745. $query->select('order_id', 'order_status_system', 'order_status_payment', 'order_status_storage');
  3746. },
  3747. 'refund' => function ($query) {
  3748. $query->select('join_return_order_id', 'orders_return_id', 'order_return_status');
  3749. },
  3750. ])
  3751. ->leftJoin('order', 'order.order_id', 'order_sheet.join_sheet_order_id')
  3752. ->where('join_sheet_member_id', $memberId)
  3753. ->where('order.order_category', '<>', 'RECHARGE')
  3754. ->when(!empty($datetime), function ($query) use ($datetime) {
  3755. $datetime[0] = strtotime($datetime[0]);
  3756. $datetime[1] = strtotime($datetime[1]);
  3757. $query->whereBetween('order_sheet_addtimes', $datetime);
  3758. })
  3759. ->when(!empty($goodsIds), function ($query) use ($goodsIds) {
  3760. $query->whereIn('join_sheet_goods_id', $goodsIds);
  3761. });
  3762. $total = $sheet->count();
  3763. $rows = $sheet
  3764. ->orderBy('order_sheet_addtimes', 'desc')
  3765. ->forPage($page, $pageSize)
  3766. ->get()
  3767. ->toArray();
  3768. foreach ($rows as &$item) {
  3769. if (!empty($item->goods->goods_cover)) {
  3770. $item->goods->goods_cover = getenv('STORAGE_DOMAIN') . $item->goods->goods_cover;
  3771. }
  3772. }
  3773. return json_success('', compact('rows', 'page', 'pageSize', 'total'));
  3774. }
  3775. public function saveExpress($params)
  3776. {
  3777. try {
  3778. $express = new OrderExpress();
  3779. $express->order_express_type = $params['order_express_type'];
  3780. $express->join_express_order_id = $params['orderId'];
  3781. $express->join_express_dept_id = $params['submit_premises_id'] ?? 0;
  3782. $express->order_express_goods = $params['order_express_goods'];
  3783. $express->order_express_city = $params['order_express_city'];
  3784. $express->order_express_address = $params['order_express_address'];
  3785. $express->order_express_mobile = $params['order_express_mobile'] ?? '';
  3786. $express->order_express_telephone = $params['order_express_telephone'] ?? '';
  3787. $express->order_express_person = $params['order_express_person'] ?? '';
  3788. $express->order_express_company = $params['dept_premises_id'] ?? '';
  3789. $express->order_express_extend_json = $params['order_express_extend_json'] ?? '[]';
  3790. $express->order_express_addtimes = time();
  3791. $express->save();
  3792. } catch (\Exception $e) {
  3793. dump($e->getMessage());
  3794. throw new BusinessException('物流信息保存失败');
  3795. }
  3796. }
  3797. // TODO 确认收货(完成订单)
  3798. // public function confirm($id)
  3799. // {
  3800. // $order = Order::where('order_id', $id)->first();
  3801. // if (empty($order)) {
  3802. // return json_fail("暂无数据");
  3803. // }
  3804. //
  3805. // Db::beginTransaction();
  3806. // try {
  3807. // // 主订单
  3808. // Order::where('order_id', $id)->update(['order_status_system' => 'CONFIRM']);
  3809. // } catch (\Exception $e) {
  3810. //
  3811. // }
  3812. // }
  3813. /**
  3814. * @Desc 退款
  3815. * @Author Gorden
  3816. * @Date 2024/7/8 8:40
  3817. *
  3818. * @param Request $request
  3819. * @return Response
  3820. */
  3821. public function doRefund(Request $request)
  3822. {
  3823. $orderId = $request->post('order_id', '');
  3824. $amount = $request->post('refund_amount', 0);
  3825. $password = $request->post('refund_password', '');
  3826. if (!$orderId || !$amount || !$password) {
  3827. return json_fail('参数异常');
  3828. }
  3829. if ($password != '123456') {
  3830. return json_fail('支付密码错误');
  3831. }
  3832. $return = OrderReturn::where('join_return_order_id', $orderId)
  3833. ->first();
  3834. if (!$return) {
  3835. return json_fail("退款订单异常");
  3836. }
  3837. $order = Order::where('order_id', $return->join_return_order_id)->first();
  3838. if (!$order) {
  3839. return json_fail("订单异常");
  3840. }
  3841. if ($order->order_is_complete == 'Y' || $order->order_is_complete == 'R') {
  3842. return json_fail('订单已完成,无法退款');
  3843. }
  3844. if ($amount > $order->order_amount_pay) {
  3845. return json_fail('退款金额不能超过订单金额');
  3846. }
  3847. $payDetail = PayDetail::where('join_pay_order_id', $order->order_groupby)->where('pay_status', 'SUCCESS')->first();
  3848. if (!$payDetail) {
  3849. return json_fail("支付信息异常异常");
  3850. }
  3851. // 在线支付返回
  3852. $payJsonResponse = [];
  3853. if (!empty($payDetail->pay_json_response)) {
  3854. $payJsonResponse = json_decode($payDetail->pay_json_response, true);
  3855. }
  3856. $res = '[]';
  3857. $data = '[]';
  3858. try {
  3859. Db::beginTransaction();
  3860. // 订单主表
  3861. Order::where('order_id', $return->join_return_order_id)->update(['order_is_complete' => 'R']);
  3862. // 订单详情
  3863. OrderSheet::where('join_sheet_order_id', $return->join_return_order_id)->update(['order_sheet_status' => 'RETURNED']);
  3864. // return 表
  3865. $return->order_return_status = 'DONE';
  3866. $return->order_return_refund_json = json_encode(['amount' => $amount, 'datetime' => date('Y-m-d H:i:s'), 'user_id' => JwtToken::getCurrentId()]);
  3867. $return->save();
  3868. $payType = explode('-', $payDetail->pay_prepayid);
  3869. // 区分账户余额支付和在线支付
  3870. if ($payDetail->pay_prepayid == 'WXPAY') {
  3871. // 退款
  3872. $data = [
  3873. 'type' => 'app',
  3874. 'out_trade_no' => $order->order_groupby,
  3875. 'out_refund_no' => $return->orders_return_id,
  3876. 'total_fee' => $payDetail->pay_amount * 100,
  3877. 'refund_fee' => $amount * 100,
  3878. 'refund_desc' => '退款',
  3879. ];
  3880. $res = Pay::wechat(config('payment.wxpay'))->refund($data);
  3881. $resArray = json_decode($res, true);
  3882. if (!$resArray['result_code'] == 'SUCCESS' || !$resArray['return_code'] == 'SUCCESS') {
  3883. throw new PayException("退款失败");
  3884. }
  3885. } else if ($payDetail->pay_prepayid == 'ALIPAY') {
  3886. // 退款
  3887. $data = [
  3888. 'out_trade_no' => $order->order_groupby,
  3889. 'refund_amount' => $amount,
  3890. ];
  3891. $res = Pay::alipay(config('payment.alipay'))->refund($data);
  3892. $resArray = json_decode($res, true);
  3893. if ($resArray['fund_change'] != 'Y' || $resArray['msg'] != 'Success') {
  3894. throw new PayException("退款失败");
  3895. }
  3896. } else if (isset($payType[1]) && $payType[1] == 'CASH') { // 余额支付
  3897. $account = MemberAccount::where('join_account_member_id', $order->join_order_member_id)
  3898. ->where('member_account_classify', 'CASH')
  3899. ->first();
  3900. $account->member_account_expend = $account->member_account_expend - $amount;
  3901. $account->member_account_surplus = $account->member_account_surplus + $amount;
  3902. $account->save();
  3903. $data = [
  3904. 'type' => 'REFUND',
  3905. 'member_id' => $order->join_order_member_id,
  3906. 'order_id' => $return->join_return_order_id,
  3907. 'return_id' => $return->orders_return_id
  3908. ];
  3909. $res = json_encode([
  3910. 'status' => 'SUCCESS'
  3911. ]);
  3912. } else if (isset($payType[1]) && $payType[1] == 'WELFARE') { // 员工福利支付
  3913. $account = MemberAccount::where('join_account_member_id', $order->join_order_member_id)
  3914. ->where('member_account_classify', 'WELFARE')
  3915. ->first();
  3916. $account->member_account_expend = $account->member_account_expend - $amount;
  3917. $account->member_account_surplus = $account->member_account_surplus + $amount;
  3918. $account->save();
  3919. $data = [
  3920. 'type' => 'REFUND',
  3921. 'member_id' => $order->join_order_member_id,
  3922. 'order_id' => $return->join_return_order_id,
  3923. 'return_id' => $return->orders_return_id
  3924. ];
  3925. $res = json_encode([
  3926. 'status' => 'SUCCESS'
  3927. ]);
  3928. } else if (count($payType) == 1 && !in_array($payDetail->pay_prepayid, ['W06', 'A01'])) { // 卡支付
  3929. $account = MemberAccount::where('join_account_member_id', $order->join_order_member_id)
  3930. ->where('member_account_nbr', $payType[0])
  3931. ->where('member_account_classify', 'CARD')
  3932. ->first();
  3933. $account->member_account_expend = $account->member_account_expend - $amount;
  3934. $account->member_account_surplus = $account->member_account_surplus + $amount;
  3935. $account->save();
  3936. $data = [
  3937. 'type' => 'REFUND',
  3938. 'nbr' => $account->member_account_nbr,
  3939. 'member_id' => $order->join_order_member_id,
  3940. 'order_id' => $return->join_return_order_id,
  3941. 'return_id' => $return->orders_return_id
  3942. ];
  3943. $res = json_encode([
  3944. 'status' => 'SUCCESS'
  3945. ]);
  3946. }
  3947. // 生成payDetail
  3948. $payDetailData = [
  3949. 'join_pay_member_id' => $order->join_order_member_id,
  3950. 'join_pay_order_id' => $order->order_groupby,
  3951. 'pay_status' => 'SUCCESS',
  3952. 'pay_category' => 'REFUND',
  3953. 'pay_amount' => $amount,
  3954. 'pay_paytimes' => date('Y-m-d H:i:s'),
  3955. 'pay_json_request' => json_encode($data),
  3956. 'pay_json_response' => $res,
  3957. 'pay_prepayid' => $payType[0] . (!empty($payType[1]) ? '-' . $payType[1] : ''),
  3958. 'pay_addtimes' => time()
  3959. ];
  3960. PayDetail::insert($payDetailData);
  3961. Db::commit();
  3962. // 事件通知
  3963. Event::dispatch('client_message.refund', $order->join_order_member_id);
  3964. _syslog("退款", "发起退款", json_decode($res), $data);
  3965. return json_success("退款成功");
  3966. } catch (PayException $e) {
  3967. Db::rollBack();
  3968. dump($e->getMessage());
  3969. dump($e->getTrace());
  3970. _syslog("退款", "发起退款", $e->getMessage(), $data);
  3971. return json_fail($e->getMessage());
  3972. } catch (\Exception $e) {
  3973. Db::rollBack();
  3974. dump($e->getMessage());
  3975. dump($e->getTrace());
  3976. _syslog("退款", "发起退款", $e->getMessage(), $data);
  3977. if (strpos($e->getMessage(), '余额不足') !== false) {
  3978. return json_fail("基本账户余额不足,请充值后重新发起");
  3979. }
  3980. return json_fail("数据更新失败");
  3981. }
  3982. }
  3983. public function exportOrder(Request $request)
  3984. {
  3985. $type = $request->get('type', '');
  3986. [$where, $format, $limit, $field, $order] = $this->selectInput($request);
  3987. if ($request->get('goods_classify') && $request->get('goods_classify') == 'SERVICE') {
  3988. $where['order_classify'] = ['in', 'SERVICE,CHNMED,CHNNCD'];
  3989. } else if ($request->get('goods_classify')) {
  3990. $where['order_classify'] = $request->get('goods_classify');
  3991. }
  3992. $where['order_category'] = ['<>', 'RECHARGE'];
  3993. if (!empty($request->get('order_ids'))) {
  3994. $where['order_id'] = ['in', $request->get('order_ids')];
  3995. }
  3996. if (!empty($where['order_addtimes'])) {
  3997. $where['order_addtimes'][0] = strtotime($where['order_addtimes'][0]);
  3998. $where['order_addtimes'][1] = strtotime($where['order_addtimes'][1]);
  3999. }
  4000. if ($type == 'todayOrder' && empty($where['order_addtimes'])) {
  4001. $where['order_addtimes'][0] = strtotime(date('Y-m-d') . ' 00:00:00');
  4002. $where['order_addtimes'][1] = strtotime(date('Y-m-d') . ' 23:59:59');
  4003. } else if ($type == 'todayOrderAmount') {
  4004. $todayTimeUnix = strtotime(date('Y-m-d') . ' 00:00:00');
  4005. $groupIds = PayDetail::whereRaw('CAST(UNIX_TIMESTAMP(pay_paytimes) as SIGNED) > ? ', [$todayTimeUnix])
  4006. ->where('join_pay_order_id', '<>', '')
  4007. ->where('pay_category', '<>', 'RETURN')
  4008. ->where('pay_category', '<>', 'RECHARGE')
  4009. ->where('pay_category', '<>', 'CLEAR')
  4010. ->pluck('join_pay_order_id')
  4011. ->toArray();
  4012. $where['order_groupby'] = ['in', $groupIds];
  4013. }
  4014. $orderId = trim($request->get('order_id', ''));
  4015. $orderIds = [];
  4016. if (!empty($orderId)) {
  4017. $orderIds = Order::where('order_id', 'like', '%' . $orderId . '%')
  4018. ->whereIn('order_classify', ['SERVICE', 'CHNMED', 'CHNNCD'])
  4019. ->pluck('order_id')
  4020. ->toArray();
  4021. }
  4022. $goodsName = trim($request->get('goods_name', ''));
  4023. if (!empty($goodsName)) {
  4024. $goodsIds = Goods::whereIn('goods_classify', ['SERVICE', 'CHNMED', 'CHNNCD'])
  4025. ->where('goods_name', 'like', '%' . $goodsName . '%')
  4026. ->pluck('goods_id')
  4027. ->toArray();
  4028. $goodsOrderIds = OrderSheet::whereIn('join_sheet_goods_id', $goodsIds)->pluck('join_sheet_order_id')->toArray();
  4029. if (!empty($where['order_id'])) {
  4030. $orderIds = array_intersect($orderIds, $goodsOrderIds);
  4031. } else {
  4032. $orderIds = $goodsOrderIds;
  4033. }
  4034. }
  4035. if (!empty($orderId) || !empty($goodsName)) {
  4036. $where['order_id'] = ['in', implode(',', $orderIds)];
  4037. }
  4038. $order = $request->get('order', 'desc');
  4039. $field = $field ?? 'order_addtimes';
  4040. if (!empty($where['order_status_system']) && in_array($where['order_status_system'], ['PENDING', 'WAITING', 'SENDING', 'RECVING', 'SIGNED', 'CONFIRM'])) {
  4041. $where['order_is_complete'] = 'N';
  4042. }
  4043. if (!empty($where['order_status_system']) && $where['order_status_system'] == 'RETURN') {
  4044. unset($where['order_status_system']);
  4045. unset($where['order_is_complete']);
  4046. $where['order_category'] = 'RETURN';
  4047. }
  4048. $query = $this->doSelect($where, $field, $order);
  4049. _syslog("订单", "导出订单");
  4050. return $this->exportDoFormat($query, $format, 1000);
  4051. }
  4052. /**
  4053. * 执行真正查询,并返回格式化数据
  4054. * @param $query
  4055. * @param $format
  4056. * @param $limit
  4057. * @return Response
  4058. */
  4059. protected function exportDoFormat($query, $format, $limit): Response
  4060. {
  4061. $methods = [
  4062. 'select' => 'formatSelect',
  4063. 'tree' => 'formatTree',
  4064. 'table_tree' => 'formatTableTree',
  4065. 'normal' => 'formatNormal',
  4066. ];
  4067. $paginator = $query->paginate($limit);
  4068. $total = $paginator->total();
  4069. $items = $paginator->items();
  4070. $items = call_user_func([$this, "exportAfterQuery"], $items);
  4071. $format_function = $methods[$format] ?? 'formatNormal';
  4072. return call_user_func([$this, $format_function], $items, $total);
  4073. }
  4074. public function benefitList(Request $request)
  4075. {
  4076. $orderIds = $request->get('order_ids', []);
  4077. if (empty($orderIds)) {
  4078. return json_fail("请选择需要核销的订单");
  4079. }
  4080. $orders = order::whereIn('order_id', $orderIds)
  4081. ->with([
  4082. 'benefit' => function ($query) {
  4083. $query->select('join_benefit_order_id', 'member_benefit_id', 'member_benefit_name', 'member_benefit_limit_count', 'member_benefit_used_count');
  4084. },
  4085. 'member' => function ($query) {
  4086. $query->select('member_id', 'member_mobile');
  4087. },
  4088. // 'sheets'=>function($query){
  4089. // $query->select('join_sheet_order_id','join_sheet_goods_id');
  4090. // }
  4091. // 'goods'=>function($query){
  4092. // $query->select('goods_id','goods_name');
  4093. // }
  4094. ])
  4095. ->select('order_id', 'join_order_member_id', 'order_is_complete', 'order_status_system')
  4096. ->where("order_is_complete", 'N')
  4097. // ->whereIn("order_category", ['NORMAL', 'SYSTEM'])
  4098. ->orderBy('order_addtimes', 'DESC')
  4099. ->get()
  4100. ->toArray();
  4101. $memberId = array_unique(array_column($orders, 'join_order_member_id'));
  4102. if (count($memberId) > 1) {
  4103. return json_fail("不可同时核销多人订单");
  4104. }
  4105. $data = [];
  4106. foreach ($orders as $order) {
  4107. $orderOne = $order;
  4108. foreach ($order['benefit'] as $benefit) {
  4109. $benefit['member_benefit_limit_count'] = intval($benefit['member_benefit_limit_count']);
  4110. $benefit['member_benefit_used_count'] = intval($benefit['member_benefit_used_count']);
  4111. if ($benefit['member_benefit_used_count'] >= $benefit['member_benefit_limit_count']) {
  4112. continue;
  4113. }
  4114. $benefit['unused'] = $benefit['member_benefit_limit_count'] - $benefit['member_benefit_used_count'];
  4115. $orderOne['benefit'] = $benefit;
  4116. $orderOne['member_benefit_id'] = $benefit['member_benefit_id'];
  4117. $data[] = $orderOne;
  4118. }
  4119. }
  4120. if (empty($data)) {
  4121. return json_fail("您选择的产品没有可核销的服务");
  4122. }
  4123. return json_success('', $data);
  4124. }
  4125. public function chooseBenefitList(Request $request)
  4126. {
  4127. $benefitIds = $request->get('benefit_ids', []);
  4128. $memberId = $request->get('member_id', []);
  4129. if (empty($benefitIds)) {
  4130. return json_fail('请选择需要核销的服务');
  4131. }
  4132. if (empty($memberId)) {
  4133. return json_fail('没有会员信息,请联系管理员');
  4134. }
  4135. $benefits = MemberBenefit::whereIn('member_benefit_id', $benefitIds)
  4136. ->where('member_benefit_status', 'ACTIVED')
  4137. ->where('join_benefit_member_id', $memberId)
  4138. ->select('join_benefit_order_id', 'member_benefit_id', 'member_benefit_name', 'member_benefit_limit_count', 'member_benefit_used_count')
  4139. ->orderBy('member_benefit_addtimes', 'DESC')
  4140. ->get()
  4141. ->toArray();
  4142. foreach ($benefits as &$benefit) {
  4143. $benefit['member_benefit_limit_count'] = intval($benefit['member_benefit_limit_count']);
  4144. $benefit['member_benefit_used_count'] = intval($benefit['member_benefit_used_count']);
  4145. $benefit['unused'] = $benefit['member_benefit_limit_count'] - $benefit['member_benefit_used_count'];
  4146. }
  4147. $member = Member::where('member_id', $memberId)->select('member_id', 'member_mobile')->first()->toArray();
  4148. return json_success('', ['benefits' => $benefits, 'member' => $member]);
  4149. }
  4150. public function customPrinter(Request $request)
  4151. {
  4152. $orderId = $request->post('order_id', '');
  4153. $printer = $request->post('printer', []);
  4154. $premiseName = $request->post('premise', '');
  4155. if (empty($orderId) || empty($premiseName)) {
  4156. return json_fail('参数异常');
  4157. }
  4158. if (empty($printer)) {
  4159. return json_fail('请选择打印设备');
  4160. }
  4161. $premises = SysDept::where('dept_name', $premiseName)->where('dept_category', '营业场所')->where('dept_status', 'ACTIVED')->first();
  4162. $restaurant = SysDept::where('dept_name', $premiseName)->where('dept_category', '餐厅')->where('dept_status', 'ACTIVED')->first();
  4163. $order = Order::where('order_id', $orderId)->first();
  4164. try {
  4165. foreach ($printer as $print) {
  4166. if (strpos($print, '结算') !== false && $order->order_status_payment != 'SUCCESS') {
  4167. return json_fail('无法打印未支付的结账单');
  4168. }
  4169. if (!empty($premises) || $restaurant) {
  4170. if (empty($restaurant)) {
  4171. $restaurant = SysDept::where('dept_super_id', $premises->dept_id)->where('dept_category', '餐厅')->first();
  4172. }
  4173. if (!empty($restaurant->dept_extend_json)) {
  4174. $deptExtendJson = json_decode($restaurant->dept_extend_json, true);
  4175. $voteData = [
  4176. 'func' => 'procActionToPrinter',
  4177. 'sign' => '',
  4178. 'data' => [
  4179. 'printer_premises' => $restaurant->dept_id,
  4180. 'printer_device' => [
  4181. $print
  4182. ],
  4183. 'printer_action' => 'ExecPrintOrder',
  4184. 'printer_data' => [
  4185. 'order_id' => $orderId
  4186. ]
  4187. ]
  4188. ];
  4189. http_post_json(getenv('VOTE_MENU_URL'), $voteData);
  4190. }
  4191. }
  4192. }
  4193. return json_success('打印完成');
  4194. } catch (\Exception $e) {
  4195. return json_fail("存在错误,票据未全部打印");
  4196. }
  4197. }
  4198. protected function exportAfterQuery($items)
  4199. {
  4200. $data = [];
  4201. foreach ($items as $key => $item) {
  4202. $goodsClassify = '';
  4203. $goodsName = '--';
  4204. if (!empty($item['sheet'])) {
  4205. $goods = Goods::where('goods_id', $item['sheet']['join_sheet_goods_id'])->first();
  4206. $goodsClassify = $goods->goods_classify ?? '';
  4207. $goodsName = $goods->goods_name ?? '--';
  4208. }
  4209. $systemStatus = '';
  4210. if ($item['order_is_complete'] == 'Y') {
  4211. $systemStatus = '已完成';
  4212. } elseif ($item['order_is_complete'] == 'R') {
  4213. $systemStatus = '售后已完成';
  4214. }
  4215. if ($item['order_is_complete'] != 'R' && !empty($item['order_return_status']) && $item['order_return_status'] == 'PENDING') {
  4216. $systemStatus = '待处理';
  4217. } elseif ($item['order_is_complete'] != 'R' && !empty($item['order_return_status']) && $item['order_return_status'] == 'DOING') {
  4218. $systemStatus = '退款中';
  4219. } elseif ($item['order_is_complete'] != 'R' && !empty($item['order_return_status']) && $item['order_return_status'] == 'DONE') {
  4220. $systemStatus = '退款完成';
  4221. } elseif ($item['order_is_complete'] != 'R' && !empty($item['order_return_status']) && $item['order_return_status'] == 'DISAGREE') {
  4222. $systemStatus = '不同意退款';
  4223. }
  4224. $payDetails = PayDetail::where('join_pay_order_id', $item['order_groupby'])
  4225. ->where('pay_status', 'SUCCESS')
  4226. ->where('pay_category', '<>', 'REFUND')
  4227. ->get()
  4228. ->toArray();
  4229. if (count($payDetails) > 1) {
  4230. $payWay = '组合支付';
  4231. } elseif (count($payDetails) == 1) {
  4232. $payWayEn = OrderService::getPayWayByPrepayId($payDetails[0]['pay_prepayid']);
  4233. $payWay = '';
  4234. if (!empty($payWayEn)) {
  4235. $payWay = OrderService::$payWay[$payWayEn];
  4236. }
  4237. }
  4238. if (count($payDetails) > 0) {
  4239. $payDetail0 = $payDetails[0];
  4240. $payTimes = $payDetail0['pay_paytimes'];
  4241. }
  4242. if (!empty($item['member']) && $item['member']['member_mobile'] == '0000') {
  4243. $memberName = '散客';
  4244. } else {
  4245. $memberName = !empty($item['cert']) ? $item['cert']['member_cert_name'] : (!empty($item['member']) ? (substr($item['member']['member_mobile'], -4) . '会员' . '-') : '');
  4246. if (!empty($item['member'])) {
  4247. $memberName .= $item['member']['member_mobile'];
  4248. }
  4249. }
  4250. $data[$key] = [
  4251. 'goods_classify' => !empty($goodsClassify) && isset(self::$goodsClassify[$goodsClassify]) ? self::$goodsClassify[$goodsClassify] : '其他订单',
  4252. 'order_id' => $item['order_id'],
  4253. 'member' => $memberName,
  4254. 'goods_name' => $goodsName,
  4255. 'nbr' => !empty($item['sheet']) ? intval($item['sheet']['order_sheet_num']) : '--',
  4256. 'order_amount_total' => $item['order_amount_total'],
  4257. 'order_amount_pay' => $item['order_amount_pay'],
  4258. 'order_status_system' => !empty($systemStatus) ? $systemStatus : self::$systemStatus[$item['order_status_system']],
  4259. 'order_status_payment' => self::$paymentStatus[$item['order_status_payment']],
  4260. 'pay_way' => $item['order_status_payment'] == 'SUCCESS' ? ($payWay ?? '') : '',
  4261. 'pay_times' => $item['order_status_payment'] == 'SUCCESS' || $item['order_status_payment'] == 'FREE' ? ($payTimes ?? '') : '',
  4262. 'order_addtimes' => date('Y-m-d H:i:s', strtotime($item['order_addtimes'])),
  4263. ];
  4264. }
  4265. return $data;
  4266. }
  4267. /**
  4268. * @Desc 查询订单状态
  4269. * @Author Gorden
  4270. * @Date 2024/8/19 11:55
  4271. *
  4272. * @param Request $request
  4273. * @return Response|void
  4274. */
  4275. public function getOrderPayStatus(Request $request)
  4276. {
  4277. $orderId = $request->get('order_id', '');
  4278. if (!$orderId) {
  4279. return json_fail('订单不存在');
  4280. }
  4281. $order = Order::where('order_id', $orderId)->first();
  4282. if (!$order) {
  4283. return json_fail('订单不存在');
  4284. }
  4285. $discountJson = [];
  4286. if (!empty($order->order_discount_json)) {
  4287. $discountJson = json_decode($order->order_discount_json, true);
  4288. }
  4289. if ($order->order_status_payment == 'SUCCESS') {
  4290. return json_success('success');
  4291. }
  4292. $payDetailType = PayDetail::where('join_pay_order_id', $order->order_groupby)->pluck('pay_prepayid')->toArray();
  4293. try {
  4294. Db::beginTransaction();
  4295. if (in_array('WXPAY', $payDetailType)) {
  4296. $result = Pay::wechat(config('payment.wxpay'))->find($order->order_groupby, 'pos');
  4297. $result = json_decode(json_encode($result), true);
  4298. 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') {
  4299. $order->order_status_payment = 'SUCCESS';
  4300. if (in_array($order->order_category, ['SERVICE', 'CHNMED', 'CHNNCD', 'DISHES', 'MEALS', 'VIP'])) {
  4301. $order->order_is_complete = 'Y';
  4302. $order->order_status_system = 'DONE';
  4303. } else {
  4304. $order->order_status_system = 'SENDING';
  4305. }
  4306. $order->save();
  4307. // Sheet
  4308. OrderSheet::where('join_sheet_order_id', $orderId)->where('order_sheet_status', 'PAYING')->update(['order_sheet_status' => 'DONE']);
  4309. // 支付记录
  4310. PayDetail::where('join_pay_order_id', $order->order_groupby)->where('pay_prepayid', 'WXPAY')->update(['pay_status' => 'SUCCESS']);
  4311. // 优惠券标记使用
  4312. $this->changeOrderCouponStatus($discountJson, 'USED');
  4313. Db::commit();
  4314. return json_success('success');
  4315. }
  4316. } else if (in_array('ALIPAY', $payDetailType)) {
  4317. $result = Pay::alipay(config('payment.alipay'))->find($order->order_groupby);
  4318. $result = json_decode(json_encode($result), true);
  4319. if (!empty($result['code']) && $result['code'] == '10000' && !empty($result['trade_status']) && $result['trade_status'] == 'TRADE_SUCCESS') {
  4320. if (in_array($order->order_category, ['SERVICE', 'CHNMED', 'CHNNCD', 'DISHES', 'MEALS', 'VIP'])) {
  4321. $order->order_is_complete = 'Y';
  4322. $order->order_status_system = 'DONE';
  4323. $order->order_status_payment = 'SUCCESS';
  4324. } else {
  4325. $order->order_status_system = 'SENDING';
  4326. }
  4327. $order->save();
  4328. // Sheet
  4329. OrderSheet::where('join_sheet_order_id', $orderId)->where('order_sheet_status', 'PAYING')->update(['order_sheet_status' => 'DONE']);
  4330. // 支付记录
  4331. PayDetail::where('join_pay_order_id', $order->order_groupby)->where('pay_prepayid', 'ALIPAY')->update(['pay_status' => 'SUCCESS']);
  4332. // 优惠券标记使用
  4333. $this->changeOrderCouponStatus($discountJson, 'USED');
  4334. Db::commit();
  4335. return json_success('success');
  4336. }
  4337. }
  4338. Db::rollBack();
  4339. return json_fail('没有查询到记录');
  4340. } catch (\Exception $e) {
  4341. Db::rollBack();
  4342. return json_fail('查询失败');
  4343. }
  4344. }
  4345. /**
  4346. * @Desc 修改订单状态-挂账
  4347. * @Author Gorden
  4348. * @Date 2024/8/20 15:58
  4349. *
  4350. * @param Request $request
  4351. * @return Response
  4352. */
  4353. public function updateStatus(Request $request)
  4354. {
  4355. $orderId = $request->post('order_id', '');
  4356. $orderStatusPayment = $request->post('order_status_payment', '');
  4357. $freeRemark = $request->post('free_remark', '');
  4358. $order = Order::where('order_id', $orderId)
  4359. ->select('order_id', 'order_groupby', 'order_status_payment', 'order_config_json', 'order_amount_total', 'order_discount_json', 'order_extend_json')
  4360. ->first();
  4361. Db::beginTransaction();
  4362. try {
  4363. if ($orderStatusPayment == 'AWAITING' && $order->order_status_payment != 'PENDING') {
  4364. throw new BusinessException("当前订单不允许挂账");
  4365. } else if ($orderStatusPayment == 'FREE' && $order->order_status_payment != 'PENDING') {
  4366. throw new BusinessException("当前订单不允许免单");
  4367. }
  4368. // 挂账,释放餐桌
  4369. if (in_array($orderStatusPayment, ['AWAITING', 'FREE'])) {
  4370. $order->order_status_payment = $orderStatusPayment;
  4371. // 如果有餐桌,释放
  4372. if (!empty($order->order_config_json)) {
  4373. $orderConfigJson = json_decode($order->order_config_json, true);
  4374. if (!empty($orderConfigJson['tableid'])) {
  4375. SysDept::where('dept_id', $orderConfigJson['tableid'])->update(['dept_status' => 'ACTIVED']);
  4376. }
  4377. }
  4378. }
  4379. if ($orderStatusPayment == 'FREE') {
  4380. $orderDiscountJson = [];
  4381. if (!empty($order->order_discount_json)) {
  4382. $orderDiscountJson = json_decode($order->order_discount_json, true);
  4383. }
  4384. $orderDiscountJson[date('Y-m-d H:i:s')] = [
  4385. 'coupon_id' => null,
  4386. 'coupon_value' => $order->order_amount_total,
  4387. 'coupon_classify' => '免单',
  4388. 'coupon_detail_id' => ['免单'],
  4389. 'coupon_classify_en' => ['free']
  4390. ];
  4391. $orderExtendJson = [];
  4392. if (!empty($order->order_extend_json)) {
  4393. $orderExtendJson = json_decode($order->order_extend_json, true);
  4394. }
  4395. $orderExtendJson['free_remark'] = $freeRemark;
  4396. $order->order_discount_json = json_encode($orderDiscountJson, JSON_UNESCAPED_UNICODE);
  4397. $order->order_extend_json = json_encode($orderExtendJson, JSON_UNESCAPED_UNICODE);
  4398. $order->order_is_complete = 'Y';
  4399. $order->order_status_system = 'DONE';
  4400. $order->order_amount_pay = 0;
  4401. // sheet表
  4402. OrderSheet::where('join_sheet_order_id', $orderId)->update(['order_sheet_status' => 'DONE']);
  4403. // payDetail 表
  4404. PayDetail::where('join_pay_order_id', $order->order_groupby)
  4405. ->update([
  4406. 'pay_status' => 'SUCCESS',
  4407. 'pay_amount' => 0,
  4408. 'pay_prepayid' => 'MONEY',
  4409. 'pay_paytimes' => date('Y-m-d H:i:s')
  4410. ]);
  4411. }
  4412. $order->save();
  4413. Db::commit();
  4414. return json_success('success');
  4415. } catch (BusinessException $e) {
  4416. Db::rollBack();
  4417. return json_fail($e->getMessage());
  4418. } catch (\Exception $e) {
  4419. Db::rollBack();
  4420. return json_fail('修改订单状态失败');
  4421. }
  4422. }
  4423. public function useCoupon(Request $request)
  4424. {
  4425. $goods = $request->post('goods', []);
  4426. $coupon = $request->post('coupon', []);
  4427. $payAmount = $request->post('pay_amount', 0);
  4428. $memberId = $request->post('member_id', '');
  4429. $settlementNow = $request->post('settlement_now', 'N');
  4430. if (empty($goods) || empty($coupon) || empty($memberId)) {
  4431. return json_fail("参数异常");
  4432. }
  4433. foreach ($coupon as $item) {
  4434. if (!in_array(substr($item, 0, 2), ['CU', 'CO'])) {
  4435. return json_fail("参数异常");
  4436. }
  4437. }
  4438. $amountBalance = [
  4439. 'pay_amount' => $payAmount,
  4440. 'welfare_balance' => 0,
  4441. 'cut_balance' => 0,
  4442. ];
  4443. foreach ($goods as $good) {
  4444. $result = OrderService::chooseCoupon($settlementNow, $memberId, $goods, $good, $coupon, $amountBalance);
  4445. $amountBalance = [
  4446. 'pay_amount' => $result['pay_amount'],
  4447. 'welfare_balance' => $result['welfare_balance'],
  4448. 'cut_balance' => $result['cut_balance'],
  4449. ];
  4450. }
  4451. Redis::del("ORDER:USE:COUPON:" . $memberId);
  4452. return json_success("success", ['pay_amount' => $amountBalance['pay_amount']]);
  4453. }
  4454. /**
  4455. * @Desc 订单的核销记录
  4456. * @Author Gorden
  4457. * @Date 2024/9/13 14:28
  4458. *
  4459. * @param Request $request
  4460. * @return Response
  4461. */
  4462. public function writeOffList(Request $request)
  4463. {
  4464. $orderId = $request->get('order_id');
  4465. $page = $request->get('page', 1);
  4466. $pageSize = $request->get('pageSize', 20);
  4467. if (!$orderId) {
  4468. return json_fail("参数异常");
  4469. }
  4470. $appointments = Appointment::with([
  4471. 'member' => function ($query) {
  4472. $query->select('member_id', 'member_mobile');
  4473. },
  4474. 'memberInfo',
  4475. 'cert',
  4476. 'goods' => function ($query) {
  4477. $query->select('goods_id', 'goods_name');
  4478. }
  4479. ])->where('join_appointment_order_id', $orderId)
  4480. ->where('appointment_status', 'DONE')
  4481. ->select('join_appointment_member_id', 'join_appointment_goods_id', 'appointment_done_datetime', 'appointment_done_json');
  4482. $total = $appointments->count();
  4483. $rows = $appointments->forPage($page, $pageSize)
  4484. ->orderBy('appointment_done_datetime', 'DESC')
  4485. ->get();
  4486. foreach ($rows as &$item) {
  4487. $memberMobile = '';
  4488. if (!empty($item['member']) && !empty($item['member']['member_mobile'])) {
  4489. $memberMobile = $item['member']['member_mobile'];
  4490. }
  4491. $memberNickname = '';
  4492. if (!empty($item['member_info']) && !empty($item['member_info']['member_info_nickname'])) {
  4493. $memberNickname = $item['member_info']['member_info_nickname'];
  4494. }
  4495. $memberName = '';
  4496. if (!empty($item['cert']) && !empty($item['cert']['member_cert_name'])) {
  4497. $memberName = $item['cert']['member_cert_name'];
  4498. }
  4499. unset($item['member'], $item['member_info'], $item['cert']);
  4500. $item['member_name'] = MemberService::getMemberName($memberMobile, $memberName, $memberNickname);
  4501. if (!empty($item['appointment_done_json'])) {
  4502. $doneJson = json_decode($item['appointment_done_json'], true);
  4503. if (isset($doneJson['charge']) && !empty($doneJson['charge']['charge_user_id'])) {
  4504. $item['username'] = SysUser::where('user_id', $doneJson['charge']['charge_user_id'])->value('user_name');
  4505. }
  4506. if (isset($doneJson['charge']) && !empty($doneJson['charge']['charge_premises'])) {
  4507. $item['premise'] = $doneJson['charge']['charge_premises'];
  4508. }
  4509. $item['nbr'] = 1;
  4510. }
  4511. }
  4512. return json_success('', compact('rows', 'page', 'pageSize', 'total'));
  4513. }
  4514. public static $goodsClassify = [
  4515. // goodsClassify: {GOODS:"健康产品订单",SERVICE:"服务订单",DEVICE:"设备订单",SPECIAL:"专题业务订单",PACKAGE:"套餐订单",RECHARGE:"充值订单",OTHER:"其他订单"},
  4516. 'GOODS' => "产品订单",
  4517. 'SERVICE' => "服务订单",
  4518. 'CHNMED' => '服务订单',
  4519. 'CHNNCD' => '服务订单',
  4520. 'DEVICE' => '设备订单',
  4521. 'SPECIAL' => '专题业务订单',
  4522. 'PACKAGE' => '套包订单',
  4523. 'RECHARGE' => '充值订单',
  4524. 'OTHER' => '其他订单',
  4525. 'DISHES' => '餐饮订单',
  4526. 'MEALS' => '餐饮订单',
  4527. 'VIP' => '康养城订单'
  4528. ];
  4529. // systemStatus: {BEING:"待生效",PAYING:"待支付",PENDING:"待确认",WAITING:"待受理",SENDING:"待发货",RECVING:"待收货",SIGNED:"已签收",CONFIRM:"确认收货"},
  4530. // paymentStatus: {PENDING:"待支付",CANCEL:"取消支付",SUCCESS:"支付成功"},
  4531. public static $systemStatus = [
  4532. 'BEING' => '待生效',
  4533. 'PAYING' => "待支付",
  4534. 'PENDING' => "待确认",
  4535. 'WAITING' => "待使用",
  4536. 'SENDING' => "待发货",
  4537. 'RECVING' => "待收货",
  4538. 'SIGNED' => "已签收",
  4539. 'CONFIRM' => "确认收货",
  4540. 'DONE' => '已完成',
  4541. 'CANCEL' => '已取消'
  4542. ];
  4543. public static $paymentStatus = [
  4544. 'WAITING' => "待支付",
  4545. 'PENDING' => "待支付",
  4546. 'CANCEL' => "取消支付",
  4547. 'SUCCESS' => "支付成功",
  4548. 'AWAITING' => "挂账",
  4549. 'FREE' => "免单"
  4550. ];
  4551. }