WholeController.php 273 KB

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