12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705 |
- <?php
- namespace app\admin\controller\order;
- use app\admin\service\coupon\CouponDetailService;
- use app\admin\service\coupon\CouponService;
- use app\admin\service\member\MemberService;
- use app\admin\service\order\OrderService;
- use app\admin\service\order\OrderSheetService;
- use app\admin\service\order\PayDetailService;
- use app\admin\validate\coupon\CouponValidate;
- use app\admin\validate\device\DeviceValidate;
- use app\admin\validate\order\OrderExpressValidate;
- use app\admin\validate\order\OrderValidate;
- use app\common\payment\AppUtil;
- use app\common\payment\Tlpay;
- use app\controller\Curd;
- use app\model\Appointment;
- use app\model\Card;
- use app\model\ClientConfig;
- use app\model\Coupon;
- use app\model\CouponDetail;
- use app\model\Device;
- use app\model\Goods;
- use app\model\GoodsComponent;
- use app\model\GoodsRunning;
- use app\model\GoodsSku;
- use app\model\Member;
- use app\model\MemberAccount;
- use app\model\MemberBenefit;
- use app\model\MemberRole;
- use app\model\Order;
- use app\model\OrderExpress;
- use app\model\OrderProcess;
- use app\model\OrderReturn;
- use app\model\OrderSheet;
- use app\model\PayDetail;
- use app\model\Premises;
- use app\model\Supplier;
- use app\model\SysDept;
- use app\model\SysSerial;
- use app\model\SysUser;
- use Payment\Common\PayException;
- use support\Db;
- use support\exception\BusinessException;
- use support\Log;
- use support\Redis;
- use support\Request;
- use support\Response;
- use Tinywan\Jwt\JwtToken;
- use Webman\Event\Event;
- use Yansongda\Pay\Pay;
- class WholeController extends Curd
- {
- public function __construct()
- {
- $this->model = new Order();
- $this->validate = true;
- $this->validateClass = new OrderValidate();
- }
- /**
- * @Desc 列表
- * @Author Gorden
- * @Date 2024/3/28 15:01
- *
- * @param Request $request
- * @return Response
- * @throws \support\exception\BusinessException
- */
- public function select(Request $request): Response
- {
- $timeType = $request->get('time_type', 'add');
- [$where, $format, $limit, $field, $order] = $this->selectInput($request);
- if (!empty($where['order_addtimes']) && $timeType == 'add') {
- $where['order_addtimes'][0] = strtotime($where['order_addtimes'][0]);
- $where['order_addtimes'][1] = strtotime($where['order_addtimes'][1]);
- }
- if ($request->get('goods_classify') && $request->get('goods_classify') == 'SERVICE') {
- $where['order_classify'] = ['in', 'SERVICE,CHNMED,CHNNCD'];
- } else if ($request->get('goods_classify')) {
- $where['order_classify'] = $request->get('goods_classify');
- }
- $order = $request->get('order', 'desc');
- $type = $request->get('type', '');
- if ($type == 'todayOrder' && empty($where['order_addtimes'])) {
- $where['order_addtimes'][0] = strtotime(date('Y-m-d') . ' 00:00:00');
- $where['order_addtimes'][1] = strtotime(date('Y-m-d') . ' 23:59:59');
- } else if ($type == 'todayOrderAmount') {
- $todayTimeUnix = strtotime(date('Y-m-d') . ' 00:00:00');
- $groupIds = PayDetail::whereRaw('CAST(UNIX_TIMESTAMP(pay_paytimes) as SIGNED) > ? ', [$todayTimeUnix])
- ->where('join_pay_order_id', '<>', '')
- ->whereIn('pay_category', ['GOODS', 'SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE', 'MEALS'])
- ->where('pay_status', 'SUCCESS')
- ->pluck('join_pay_order_id')
- ->toArray();
- $where['order_groupby'] = ['in', $groupIds];
- } else if ($type == 'todaySalesOrderAmount') {
- $todayTimeUnix = strtotime(date('Y-m-d') . ' 00:00:00');
- $groupIds = PayDetail::whereRaw('CAST(UNIX_TIMESTAMP(pay_paytimes) as SIGNED) > ? ', [$todayTimeUnix])
- ->where('join_pay_order_id', '<>', '')
- ->whereIn('pay_prepayid', ['WXPAY', 'ALIPAY', 'OFFLINE_WXPAY', 'OFFLINE_ALIPAY', 'MONEY'])
- ->where('pay_status', 'SUCCESS')
- ->pluck('join_pay_order_id')
- ->toArray();
- $where['order_groupby'] = ['in', $groupIds];
- } else if ($type == 'todayRechargeOrder') {
- $where['order_classify'] = ['in', ['RECHARGE', 'COMBINE', 'PARTNER', 'REFERRER', 'VIP']];
- $todayTimeUnix = strtotime(date('Y-m-d') . ' 00:00:00');
- $where['order_addtimes'] = ['>', $todayTimeUnix];
- } else if ($type == 'todayCash') {
- $todayTimeUnix = strtotime(date('Y-m-d') . ' 00:00:00');
- $groupIds = PayDetail::whereRaw('CAST(UNIX_TIMESTAMP(pay_paytimes) as SIGNED) > ? ', [$todayTimeUnix])
- ->where(function ($query) {
- $query->where('pay_prepayid', 'like', '%CASH%')
- ->OrWhere('pay_prepayid', 'like', '%VIP%')
- ->orWhere('pay_prepayid', 'like', '%WELFARE%');
- })
- ->where('join_pay_order_id', '<>', '')
- ->whereIn('pay_category', ['GOODS', 'SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE', 'MEALS'])
- ->where('pay_status', 'SUCCESS')
- ->pluck('join_pay_order_id')
- ->toArray();
- $where['order_groupby'] = ['in', $groupIds];
- }
- $orderIds = [];
- if (!empty($where['order_id'])) {
- $orderIds = Order::where('order_id', 'like', '%' . $where['order_id'] . '%')->pluck('order_id')->toArray();
- }
- $field = $field ?? 'order_addtimes';
- if (!empty($where['order_status_system']) && in_array($where['order_status_system'], ['PENDING', 'WAITING', 'SENDING', 'RECVING', 'SIGNED', 'CONFIRM'])) {
- if ($where['order_status_system'] == 'SENDING') {
- $where['order_express.order_express_type'] = '配送';
- }
- $where['order_is_complete'] = 'N';
- $where['order_category'] = isset($where['order_category']) ? $where['order_category'] : ['in', 'SYSTEM,NORMAL,DISHES'];
- }
- if (!empty($where['order_status_system']) && $where['order_status_system'] == 'RETURN') {
- unset($where['order_status_system']);
- unset($where['order_is_complete']);
- $where['order_category'] = 'RETURN';
- }
- if ($request->get('return')) {
- $where['order_return.order_return_status'] = $request->get('return');
- }
- $goodsIds = [];
- if ($request->get('goods_classify') || $request->get('goods_name')) {
- // $where['order_id'] = '';
- $goodsClassify = $request->get('goods_classify', '');
- if ($goodsClassify == 'DISHES') {
- $goodsClassify = 'MEALS';
- }
- $goodsName = $request->get('goods_name', '');
- if (!empty($goodsName) && empty($goodsClassify)) {
- $goodsIds = Goods::where('goods_name', 'like', '%' . $request->get('goods_name') . '%')->pluck('goods_id')->toArray();
- } else if (!empty($goodsClassify)) {
- if ($goodsClassify == 'SERVICE') {
- $goodsModel = Goods::whereIn('goods_classify', ['SERVICE', 'CHNMED', 'CHNNCD']);
- } else {
- $goodsModel = Goods::where('goods_classify', $goodsClassify);
- }
- if (!empty($goodsName)) {
- $goodsModel->where('goods_name', 'like', '%' . $goodsName . '%');
- }
- $goodsIds = $goodsModel->pluck('goods_id')->toArray();
- }
- }
- if ($request->get('goods_classify') || $request->get('goods_name')) {
- $orderGoodsIds = OrderSheet::whereIn('join_sheet_goods_id', $goodsIds)->pluck('join_sheet_order_id')->toArray();
- if (!empty($where['order_id'])) {
- $orderIds = array_intersect($orderIds, $orderGoodsIds);
- // $where['order_id'] = ['in', implode(',', $orderIds)];
- } else {
- $orderIds = $orderGoodsIds;
- // $where['order_id'] = ['in', implode(',', $orderGoodsIds)];
- }
- }
- // 付款时间
- $payOrderIds = [];
- if ($timeType == 'pay' && !empty($where['order_addtimes'])) {
- $payTimeStart = strtotime($where['order_addtimes'][0]);
- $payTimeEnd = strtotime($where['order_addtimes'][1]);
- unset($where['order_addtimes']);
- $payOrderIds = PayDetailService::getPayOrderId($payTimeStart, $payTimeEnd);
- }
- if ((!empty($orderId) || !empty($goodsName)) && $timeType == 'pay') {
- $orderIds = array_intersect($orderIds, $payOrderIds);
- $where['order_id'] = ['in', implode(',', $orderIds)];
- } elseif (!empty($orderId) || !empty($goodsName)) {
- $where['order_id'] = ['in', implode(',', $orderIds)];
- } elseif ($timeType == 'pay') {
- $where['order_id'] = ['in', implode(',', $payOrderIds)];
- }
- // 自提订单
- if (!empty($where['order_status_system']) && $where['order_status_system'] == 'PICKUP') {
- $where['order_is_complete'] = 'N';
- $where['order_status_system'] = 'SENDING';
- $where['order_express.order_express_type'] = '自提';
- }
- $query = $this->doSelect($where, $field, $order);
- return $this->doFormat($query, $format, $limit);
- }
- protected function doSelect(array $where, string $field = null, string $order = 'desc')
- {
- $model = $this->model->with([
- 'sheets' => function ($query) {
- $query->select('join_sheet_order_id', 'order_sheet_id', 'join_sheet_goods_id', 'order_sheet_num', 'order_sheet_price');
- },
- 'member' => function ($query) {
- $query->select('member_id', 'member_mobile');
- },
- 'cert' => function ($query) {
- $query->select('join_cert_member_id', 'member_cert_name');
- },
- // 'return' => function ($query) use ($where){
- // if (isset($where['return'])){
- // dump($where['return']);
- // $query = $query->where('order_return_status',$where['return']);
- // }
- // $query->select('orders_return_id', 'join_return_order_id', 'order_return_status');
- // },
- // 'express' => function ($query) {
- // $query->select('join_express_order_id', 'order_express_type');
- // }
- ])->leftJoin('order_return', 'order_return.join_return_order_id', '=', 'order.order_id')
- ->leftJoin('order_express', 'order_express.join_express_order_id', '=', 'order.order_id');
- // ->leftJoin('pay_detail', 'pay_detail.join_pay_order_id', '=', 'order.order_groupby');
- // ->leftJoin('order_sheet','join_sheet_order_id','=','order.order_id');
- foreach ($where as $column => $value) {
- if (is_array($value)) {
- if ($value[0] === 'like' || $value[0] === 'not like') {
- $model = $model->where($column, $value[0], "%$value[1]%");
- } elseif (in_array($value[0], ['>', '=', '<', '<>'])) {
- $model = $model->where($column, $value[0], $value[1]);
- } elseif ($value[0] == 'in' && !empty($value[1])) {
- $valArr = $value[1];
- if (is_string($value[1])) {
- $valArr = explode(",", trim($value[1]));
- }
- $model = $model->whereIn($column, $valArr);
- } elseif ($value[0] == 'not in' && !empty($value[1])) {
- $valArr = $value[1];
- if (is_string($value[1])) {
- $valArr = explode(",", trim($value[1]));
- }
- $model = $model->whereNotIn($column, $valArr);
- } elseif ($value[0] == 'null') {
- $model = $model->whereNull($column);
- } elseif ($value[0] == 'not null') {
- $model = $model->whereNotNull($column);
- } elseif ($value[0] !== '' || $value[1] !== '') {
- $model = $model->whereBetween($column, $value);
- }
- } else {
- $model = $model->where($column, $value);
- }
- }
- if ($field) {
- $model = $model->orderBy($field, $order);
- }
- $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');
- return $model;
- }
- public function afterQuery($items)
- {
- foreach ($items as &$item) {
- $sheetDeng = '';
- $item['sheet'] = $item['sheets'][0] ?? [];
- if (!empty($item['sheet'])) {
- $goods = Goods::where('goods_id', $item['sheet']['join_sheet_goods_id'])->first();
- if (count($item['sheets']) > 1 && !empty($goods) && $goods->goods_classify == 'MEALS') {
- $sheetDeng = ' 等餐品';
- }
- $item['sheet']['goods_name'] = ($goods && $goods->goods_name) ? $goods->goods_name . $sheetDeng : '';
- $item['sheet']['goods_classify'] = $goods->goods_classify ?? '';
- $item['sheet']['order_sheet_num'] = intval($item['sheet']['order_sheet_num']);
- }
- unset($item['sheets']);
- $item['order_return_amount'] = 0;
- if (isset($item['orders_return_id'])) {
- $item['return'] = [
- 'orders_return_id' => $item['orders_return_id'],
- 'join_return_order_id' => $item['join_return_order_id'],
- 'order_return_status' => $item['order_return_status'],
- 'order_return_apply_json' => $item['order_return_apply_json'],
- 'order_return_remark' => $item['order_return_remark'],
- ];
- if (!empty($item['order_return_refund_json'])) {
- $refundJson = json_decode($item['order_return_refund_json'], true);
- if (isset($refundJson['amount'])) {
- $item['order_return_amount'] = $refundJson['amount'];
- }
- }
- }
- if (isset($item['join_express_order_id'])) {
- $item['express'] = [
- 'join_express_order_id' => $item['join_express_order_id'],
- 'order_express_type' => $item['order_express_type']
- ];
- unset($item['join_express_order_id'], $item['order_express_type']);
- }
- $item['payDetail'] = PayDetailService::getPayWay($item['order_groupby'], $item['order_id']);
- }
- return $items;
- }
- /**
- * @Desc 订单商品详情
- * @Author Gorden
- * @Date 2024/3/29 8:50
- *
- * @param Request $request
- * @return Response
- */
- public function sheet(Request $request)
- {
- try {
- $orderId = $request->get('order_id');
- $orderSheet = OrderSheet::with([
- 'member' => function ($query) {
- $query->select('member_id', 'member_mobile', 'member_is_owner', 'join_member_role_id', 'member_is_vip', 'member_is_partner', 'member_is_referrer', 'member_is_franchisee');
- },
- 'goods' => function ($query) {
- $query->select('goods_id', 'goods_name', 'goods_cover', 'goods_market_price', 'goods_sales_price', 'goods_classify', 'goods_if_express');
- },
- 'memberInfo',
- 'cert',
- 'sku' => function ($query) {
- $query->where('goods_sku_status', 'ON')
- ->select('goods_sku_id', 'join_sku_goods_id', 'goods_sku_specs_json', 'goods_sku_sales_price');
- },
- 'skus',
- 'refund' => function ($query) {
- $query->select('join_return_order_id', 'order_return_status');
- }
- ])->where('join_sheet_order_id', $orderId)
- ->orderBy('order_sheet_id', 'DESC')
- ->get()
- ->toArray();
- $order = Order::where('order_id', $orderId)->first();
- $express = OrderExpress::where('join_express_order_id', $orderId)->first();
- $premises = '';
- if ($express && $express->order_express_type == '自提') {
- $premises = $express->order_express_company;
- }
- $sheetAmount = 0;
- $coupons = [];
- foreach ($orderSheet as &$item) {
- $item['order_sheet_num'] = floatval($item['order_sheet_num']);
- $sheetAmount += $item['order_sheet_amount'];
- $item['goods']['goods_cover'] = getenv('STORAGE_DOMAIN') . $item['goods']['goods_cover'];
- if (!empty($item['goods']) && $item['goods']['goods_classify'] == 'PACKAGE') {
- $components = GoodsComponent::with('goods')
- ->where('join_component_master_goods_id', $item['goods']['goods_id'])
- ->select('join_component_master_goods_id', 'join_component_goods_id', 'goods_component_price',
- 'goods_component_price', 'goods_component_json')
- ->get()
- ->toArray();
- $goodsArr = [];
- foreach ($components as $component) {
- $configJson = !empty($component['goods_component_json']) ? json_decode($component['goods_component_json'], true) : [];
- if (!empty($component['goods'])) {
- $supplierName = Supplier::where('supplier_id', $component['goods']['join_goods_supplier_id'])->value('supplier_name');
- $benefit = MemberBenefit::where('join_benefit_member_id', $item['join_sheet_member_id'])
- ->where('join_benefit_goods_id', $component['goods']['goods_id'])
- ->where('join_benefit_order_id', $orderId)
- ->first();
- $goodsArr[] = [
- 'goods_name' => $component['goods']['goods_name'],
- 'goods_cover' => getenv('STORAGE_DOMAIN') . $component['goods']['goods_cover'],
- 'supplier_name' => $supplierName,
- 'nbr' => $configJson['nbr'] ?? 0,
- 'used' => !empty($benefit->member_benefit_used_count) ? intval($benefit->member_benefit_used_count) : ''
- ];
- }
- }
- $item['goods']['components'] = $goodsArr;
- $goodsModel = Goods::where('goods_id', $item['goods']['goods_id'])->select('goods_attribute_json')->first();
- if (!empty($goodsModel) && !empty($goodsModel->goods_attribute_json)) {
- $goodsAttributeJson = json_decode($goodsModel->goods_attribute_json, true);
- if (!empty($goodsAttributeJson['coupon'])) {
- foreach ($goodsAttributeJson['coupon'] as $key => $coupon) {
- $couponCount = CouponDetail::where('join_detail_coupon_id', $key)
- ->whereJsonContains('coupon_detail_extend_json->order_id', $item['join_sheet_order_id'])
- ->count();
- $couponUsedCount = CouponDetail::where('join_detail_coupon_id', $key)
- ->where('coupon_detail_status', 'USED')
- ->whereJsonContains('coupon_detail_extend_json->order_id', $item['join_sheet_order_id'])
- ->count();
- $couponUnUsedCount = CouponDetail::where('join_detail_coupon_id', $key)
- ->whereIn('coupon_detail_status', ['ACTIVED', 'WAITING'])
- ->whereJsonContains('coupon_detail_extend_json->order_id', $item['join_sheet_order_id'])
- ->count();
- $coupon['total'] = $couponCount;
- $coupon['used'] = $couponUsedCount;
- $coupon['unused'] = $couponUnUsedCount;
- $coupon['invalid'] = $couponCount - $couponUsedCount - $couponUnUsedCount;
- $coupons[] = $coupon;
- }
- }
- }
- }
- if (!empty($item['sku'])) {
- if (!empty($item['sku']['goods_sku_specs_json'])) {
- $specsJson = json_decode($item['sku']['goods_sku_specs_json'], true);
- $skuName = '';
- foreach ($specsJson as $specsKey => $skuSpecs) {
- if (is_array($skuSpecs)) {
- $skuName = $skuName . ' ' . implode(' ', $skuSpecs) . ';';
- } else {
- $skuName = $skuName . ' ' . $skuSpecs . ';';
- }
- }
- $item['sku']['goods_sku_title'] = rtrim($skuName, ';');
- }
- }
- if (!empty($item['skus'])) {
- foreach ($item['skus'] as $key => $skus) {
- if (!empty($skus['goods_sku_specs_json'])) {
- $item['skus'][$key]['goods_sku_specs_json'] = json_decode($skus['goods_sku_specs_json']);
- $skuName = '';
- foreach ($item['skus'][$key]['goods_sku_specs_json'] as $specsKey => $skuSpecs) {
- $keyStr = ($specsKey == '规格') ? '' : ($specsKey . ':');
- if (is_array($skuSpecs)) {
- $skuName = $skuName . $keyStr . ' ' . implode(' ', $skuSpecs) . '; ';
- } else {
- $skuName = $skuName . $keyStr . ' ' . $skuSpecs . '; ';
- }
- }
- $item['skus'][$key]['sku_name'] = rtrim($skuName, '; ');
- }
- }
- } else {
- $item['skus'] = [];
- }
- if (in_array($item['goods']['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD'])) {
- $item['appontment'] = [];
- $appontments = Appointment::where('join_appointment_order_id', $orderId)
- ->where('appointment_status', 'DONE')
- ->select('appointment_status', 'appointment_id', 'appointment_done_datetime', 'appointment_done_json', 'appointment_apply_json')
- ->get()
- ->toArray();
- foreach ($appontments as $appontment) {
- $doneJson = [];
- $username = '';
- if (!empty($appontment['appointment_done_json'])) {
- $doneJson = json_decode($appontment['appointment_done_json'], true);
- if (isset($doneJson['charge'])) {
- $username = SysUser::where('user_id', $doneJson['charge']['charge_user_id'])->value('user_name');
- }
- }
- $person = 1;
- if (!empty($appontment->appointment_apply_json)) {
- $applyJson = json_decode($appontment->appointment_apply_json, true);
- if (isset($applyJson['person'])) {
- $person = $applyJson['person'];
- }
- }
- $item['appontment'][] = [
- 'member' => ($item['cert'] ? $item['cert']['member_cert_name'] . '-' : '') . ($item['member'] ? $item['member']['member_mobile'] : ''),
- 'goods_name' => $item['goods']['goods_name'],
- 'premisses' => isset($doneJson['charge']) ? $doneJson['charge']['charge_premises'] : '',
- 'username' => $username,
- 'nbr' => $person,
- 'done_time' => $appontment['appointment_done_datetime'],
- 'appointment_status' => $appontment['appointment_status'],
- ];
- }
- }
- if (!empty($item['order_sheet_extend_json']) && !$express) {
- $extendJson = json_decode($item['order_sheet_extend_json'], true);
- if (isset($extendJson['address_id'])) {
- $address = ClientConfig::where('client_config_id', $extendJson['address_id'])->first();
- if (!empty($address)) {
- $valJson = json_decode($address->client_config_val_json, true);
- $express = [
- 'order_express_address' => $valJson['address'] . ($valJson['numbers'] ?? ''),
- 'order_express_city' => $valJson['city'],
- 'order_express_mobile' => $valJson['mobile'],
- 'order_express_person' => $valJson['person']
- ];
- }
- }
- }
- $item['member']['level'] = '普通会员';
- if (!empty($item['member']['join_member_role_id'])) {
- $item['member']['level'] = MemberRole::where('member_role_id', $item['member']['join_member_role_id'])->value('member_role_name');
- }
- $item['member_info']['member_info_nickname'] = MemberService::getNickname(!empty($item['member_info']) ? $item['member_info']['member_info_nickname'] : '', (!empty($item['member']) ? $item['member']['member_mobile'] : ''));
- $item['member_info']['member_info_headimg'] = MemberService::getAvatarUrl(!empty($item['member_info']) && !empty($item['member_info']['member_info_headimg']) ? $item['member_info']['member_info_headimg'] : '');
- }
- $order->sheet_amount = number_format($sheetAmount, 2);
- $payDetails = PayDetail::where('join_pay_order_id', $order->order_groupby)
- ->where(function ($query) use ($orderId) {
- $query->whereJsonContains('join_pay_object_json->order_id', $orderId)->orWhere('join_pay_object_json', '')->orWhereNull('join_pay_object_json');
- })->where('pay_category', '<>', 'REFUND')
- ->where('pay_status', 'SUCCESS')
- ->where('pay_prepayid', '<>', '')
- ->select('pay_id', 'pay_category', 'pay_prepayid', 'pay_paytimes', 'pay_status', 'pay_amount', 'pay_extend_json')
- ->get();
- if (count($payDetails) > 1) {
- $order->pay_category = 'CONSTITUTE';
- }
- $payDetail = !empty($payDetails) && count($payDetails) > 0 ? $payDetails[0] : [];
- if (!empty($payDetail) && !empty($payDetail->pay_extend_json)) {
- $payExtendJson = json_decode($payDetail->pay_extend_json, true);
- $order->cancel_times = $payExtendJson['cancel_times'] ?? '';
- }
- if (!empty($payDetail) && !empty($payDetail->pay_prepayid)) {
- $categoryArray = explode('-', $payDetail->pay_prepayid);
- if (isset($categoryArray[1])) {
- $payDetail->pay_category = $categoryArray[1];
- } else if (in_array($categoryArray[0], ['WXPAY', 'ALIPAY', 'OFFLINE', 'OFFLINE_ALIPAY', 'OFFLINE_WXPAY', 'MONEY'])) {
- $payDetail->pay_category = $categoryArray[0];
- } else if (count($categoryArray) == 1) {
- $payDetail->pay_category = 'CARD';
- }
- }
- $refund = OrderReturn::where('join_return_order_id', $orderId)
- ->select('order_return_status', 'order_return_apply_datetime', 'order_return_apply_json', 'order_return_accept_datetime', 'order_return_refund_json', 'order_return_extend_json')
- ->first();
- if (!empty($refund->order_return_refund_json)) {
- $returnRefundJson = json_decode($refund->order_return_refund_json, true);
- if (isset($returnRefundJson['user_id'])) {
- $userName = SysUser::where('user_id', $returnRefundJson['user_id'])->value('user_name');
- $returnRefundJson['person'] = $userName;
- unset($returnRefundJson['user_id']);
- }
- $refund->order_return_refund_json = json_encode($returnRefundJson);
- }
- if (!empty($order->order_config_json)) {
- $orderConfigJson = json_decode($order->order_config_json, true);
- if (isset($orderConfigJson['reach'])) {
- $order->reach = $orderConfigJson['reach'];
- }
- if (isset($orderConfigJson['table'])) {
- $order->table = $orderConfigJson['table'];
- }
- if (isset($orderConfigJson['eat'])) {
- $order->eat = $orderConfigJson['eat'];
- }
- if (isset($orderConfigJson['express'])) {
- $order->express = $orderConfigJson['express'];
- }
- if (isset($orderConfigJson['premises'])) {
- $order->premises = $orderConfigJson['premises'];
- }
- if (isset($orderConfigJson['tableid'])) {
- $order->dept_table_id = $orderConfigJson['tableid'];
- }
- }
- if (!empty($order->order_extend_json)) {
- $orderExtendJson = json_decode($order->order_extend_json, true);
- $order->referee = $orderExtendJson['referee'] ?? '';
- if (isset($orderExtendJson['cancel_times'])) {
- $order->cancel_times = $orderExtendJson['cancel_times'];
- }
- if (isset($orderExtendJson['free_remark'])) {
- $order->free_remark = $orderExtendJson['free_remark'];
- }
- if ($order->order_status_payment == 'AWAITING' && !empty($orderExtendJson['awaiting_times'])) {
- $order->awaiting_times = $orderExtendJson['awaiting_times'];
- } elseif ($order->order_status_payment == 'AWAITING' && empty($orderExtendJson['awaiting_times'])) {
- $order->awaiting_times = date('Y-m-d H:i:s', strtotime($order->order_addtimes));
- }
- }
- $discount = ['coupon_name' => '', 'classify' => '', 'value' => 0];
- if (!empty($order->order_discount_json)) {
- $orderDiscountJson = json_decode($order->order_discount_json, true);
- foreach ($orderDiscountJson as $discountItem) {
- if (!empty($discountItem['coupon_id'])) {
- $coupon = Coupon::where('coupon_id', $discountItem['coupon_id'])
- ->select('coupon_name', 'coupon_classify', 'coupon_category', 'coupon_value', 'coupon_minimum_limit')
- ->first();
- if (!$coupon) {
- continue;
- }
- $classify = CouponService::couponClassifyInfo($coupon->coupon_classify, $coupon->coupon_category, $coupon->coupon_value, $coupon->coupon_minimum_limit);
- $discount['coupon_name'] .= $coupon->coupon_classify . ':' . $coupon->coupon_name . '(优惠¥' . sprintf("%.2f", $discountItem['coupon_value']) . '), ';
- }
- if ($discountItem['coupon_classify'] == '退款') {
- continue;
- }
- if (empty($discountItem['coupon_id']) && !empty($discountItem['coupon_classify'])) {
- if (!empty($discountItem['coupon_detail_id'])) {
- $discount['classify'] .= $discountItem['coupon_detail_id'][0] . '(优惠¥' . sprintf("%.2f", $discountItem['coupon_value']) . '), ';
- } else {
- $discount['classify'] .= $discountItem['coupon_classify'] . '(优惠¥' . sprintf("%.2f", $discountItem['coupon_value']) . '), ';
- }
- }
- if (!empty($discountItem['coupon_value'])) {
- $discount['value'] += $discountItem['coupon_value'];
- }
- }
- if (!empty($discount['coupon_name'])) {
- $discount['coupon_name'] = rtrim($discount['coupon_name'], ', ');
- }
- if (!empty($discount['classify'])) {
- $discount['classify'] = rtrim($discount['classify'], ', ');
- }
- }
- $discount['value'] = sprintf("%.2f", $discount['value']);
- $order->discount = $discount;
- $order->premises = $order->premises ?? $premises;
- $data = [
- 'coupons' => $coupons,
- 'order' => $order,
- 'refund' => json_decode(json_encode($refund)),
- 'sheet' => json_decode(json_encode($orderSheet)),
- 'express' => json_decode(json_encode($express)),
- 'payDetail' => json_decode(json_encode($payDetail)),
- 'payDetails' => json_decode(json_encode($payDetails))
- ];
- return json_success('', $data);
- } catch (\Exception $e) {
- dump($e->getMessage());
- }
- }
- public function update(Request $request): Response
- {
- $params = $request->post();
- Db::beginTransaction();
- try {
- // 修改主订单
- $this->updateMain($params);
- // 修改sheet表
- $this->updateSheet($params);
- // 修改物流
- $this->updateExpress($params);
- Db::commit();
- _syslog("订单", "修改订单成功");
- return json_success('修改订单成功');
- } catch (\Exception $e) {
- dump($e->getMessage());
- Db::rollBack();
- _syslog("订单", "修改订单失败");
- return json_fail('修改订单失败');
- }
- }
- /**
- * 修改主订单
- */
- public function updateMain($params)
- {
- try {
- $order = Order::where('order_id', $params['order_id'])->first();
- $orderConfigJson = [];
- if (!empty($order->order_config_json)) {
- $orderConfigJson = json_decode($order->order_config_json, true);
- }
- // 优惠
- if (!empty($params['preferential'])) {
- $orderConfigJson['preferential'] = $params['preferential'];
- }
- if (!empty($params['dept_premises_id'])) {
- $premise = SysDept::where('dept_name', $params['dept_premises_id'])->where('dept_category', '营业场所')->first();
- $orderConfigJson['dept'] = $premise->dept_id ?? 0;
- $orderConfigJson['premises'] = $params['dept_premises_id'];
- }
- if (!empty($params['dept_table_id'])) {
- if (!empty($orderConfigJson['tableid']) && $params['dept_table_id'] != $orderConfigJson['tableid']) {
- // 原桌释放
- SysDept::where('dept_id', $orderConfigJson['tableid'])->update(['dept_status' => 'ACTIVED']);
- }
- // 新桌使用
- SysDept::where('dept_id', $params['dept_table_id'])->update(['dept_status' => 'USING']);
- $table = SysDept::where('dept_id', $params['dept_table_id'])->where('dept_category', '桌台')->first();
- $orderConfigJson['table'] = $table->dept_name ?? 0;
- $orderConfigJson['tableid'] = $params['dept_table_id'];
- }
- if (!empty($params['eat'])) {
- $orderConfigJson['eat'] = $params['eat'];
- }
- $data = [
- 'order_amount_pay' => $params['order_amount_pay'],
- 'order_amount_total' => $params['order_amount_total'],
- 'order_config_json' => json_encode($orderConfigJson),
- 'order_remark' => $params['order_remark'] ?? ''
- ];
- Order::where('order_id', $params['order_id'])->update($data);
- } catch (\Exception $e) {
- throw new BusinessException('修改订单失败');
- }
- }
- /**
- * 订单sheet
- */
- public function updateSheet($params)
- {
- try {
- // 判断餐品是否连带着服务或实体
- $goodsClassifys = array_unique(array_column($params['goodsContentList'], 'goods_classify'));
- if (in_array('MEALS', $goodsClassifys) && count($goodsClassifys) > 1) {
- return json_fail('餐饮餐品不支持和其他类型的产品一起下单');
- }
- if (in_array('MEALS', $goodsClassifys)) {
- $params['submit_goods_classify'] = 'MEALS';
- }
- foreach ($params['goodsContentList'] as $sheet) {
- // 先还原库存
- $orderSheet = OrderSheet::where('order_sheet_id', $sheet['order_sheet_id'])->first();
- if (!isset($params['submit_goods_classify']) || $params['submit_goods_classify'] != 'MEALS') {
- $goodsSku = GoodsSku::where('goods_sku_id', $orderSheet->join_sheet_goods_sku_id)->first();
- $skuStorageJson = json_decode($goodsSku->goods_sku_storage_json, true);
- $skuStorageJson['storage'] = $skuStorageJson['storage'] + $orderSheet->order_sheet_num;
- $goodsSku->goods_sku_storage_json = json_encode($skuStorageJson);
- $goodsSku->save();
- }
- $goodsRunning = GoodsRunning::where('join_running_goods_id', $orderSheet->join_sheet_goods_id)->first();
- $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage + $orderSheet->order_sheet_num;
- // $goodsRunning->goods_running_sale = $goodsRunning->goods_running_sale - $orderSheet->order_sheet_num;
- $goodsRunning->save();
- $data = [
- 'order_sheet_num' => $sheet['nbr'],
- 'join_sheet_goods_sku_id' => $sheet['sku_id'],
- 'order_sheet_amount' => $sheet['nbr'] * $orderSheet->order_sheet_price,
- 'order_sheet_pay' => $sheet['nbr'] * $orderSheet->order_sheet_price,
- ];
- OrderSheet::where('order_sheet_id', $sheet['order_sheet_id'])->update($data);
- // 减库存
- if (!isset($params['submit_goods_classify']) || $params['submit_goods_classify'] != 'MEALS') {
- $goodsSku = GoodsSku::where('goods_sku_id', $sheet['sku_id'])->first();
- $skuStorageJson = json_decode($goodsSku->goods_sku_storage_json, true);
- $skuStorageJson['storage'] = $skuStorageJson['storage'] - $sheet['nbr'];
- if ($skuStorageJson['storage'] < 0) {
- throw new BusinessException('库存不足');
- }
- $goodsSku->goods_sku_storage_json = json_encode($skuStorageJson);
- $goodsSku->save();
- }
- $goodsRunning = GoodsRunning::where('join_running_goods_id', $orderSheet->join_sheet_goods_id)->first();
- // $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $sheet['nbr'];
- if ($goodsRunning->goods_running_storage < 0) {
- throw new BusinessException('库存不足');
- }
- // $goodsRunning->goods_running_sale = $goodsRunning->goods_running_sale + $sheet['nbr'];
- $goodsRunning->save();
- }
- } catch (\Exception $e) {
- dump($e->getMessage());
- throw new BusinessException('修改订单详情失败');
- }
- }
- public function updateExpress($params)
- {
- $express = OrderExpress::where('join_express_order_id', $params['order_id'])->first();
- if (!$express && in_array($params['delivery'], ['PICKUP', 'LOGISTICS'])) {
- throw new BusinessException('物流信息异常');
- }
- if ($params['delivery'] == 'PICKUP') {
- $premises = SysDept::where('dept_category', '营业场所')->where('dept_name', $params['dept_premises_id'])->first();
- $express->order_express_type = '自提';
- $express->order_express_city = str_replace(',', ' ', $premises->dept_city);
- $express->order_express_address = $premises->dept_address;
- $express->order_express_mobile = '';
- $express->order_express_person = '';
- $express->order_express_telephone = $premises->dept_telephone ?? '';
- $express->order_express_company = $params['dept_premises_id'];
- } else if ($params['delivery'] == 'LOGISTICS') {
- $express->order_express_type = '配送';
- $express->order_express_city = $params['order_express_city'] ?? '';
- $express->order_express_address = $params['order_express_address'] ?? '';
- $express->order_express_mobile = $params['order_express_mobile'] ?? '';
- $express->order_express_person = $params['order_express_person'] ?? '';
- $express->order_express_telephone = '';
- $express->order_express_company = '';
- }
- try {
- if (($params['delivery'] == 'PICKUP') || ($params['delivery'] == 'LOGISTICS')) {
- $express->save();
- }
- } catch (\Exception $e) {
- dump($e->getTrace());
- throw new BusinessException('修改配送方式失败');
- }
- }
- public function pay(Request $request)
- {
- $params = $request->post();
- // 余额、福利、储值卡 验证短信
- if ($params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['CASH', 'CARD', 'WELFARE'])) {
- $code = $params['sms_code'];
- if (!$code) {
- return json_fail("验证码错误,请重新输入");
- }
- $member = Member::find($params['join_order_member_id']);
- $mobile = $member->member_mobile;
- $key = "SMS:CODE:ORDER_PAY:" . $mobile;
- $redisCode = Redis::get($key);
- if ($redisCode != $code && $code != '123654879') {
- return json_fail("验证码错误,请重新输入");
- }
- Redis::del($key);
- }
- // 验证线下付款密码
- if ($params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['OFFLINE', 'MONEY'])) {
- $password = $params['offline_password'];
- if ($password != '666888') {
- return json_fail("密码错误,请重新输入");
- }
- }
- $order = Order::where('order_id', $params['order_id'])->first();
- $oldOrderPaymentStatus = $order->order_status_payment;
- $oldOrderSystemStatus = $order->order_status_system;
- if (!$order) {
- return json_fail('订单异常');
- }
- if ($order->order_status_system != 'PAYING') {
- return json_fail('订单不是可支付状态');
- }
- if (!empty($order->order_config_json)) {
- $orderConfigJson = json_decode($order->order_config_json, true);
- if (isset($orderConfigJson['premises'])) {
- $premises = SysDept::where('dept_name', $orderConfigJson['premises'])->first();
- if (!empty($premises)) {
- $params['submit_premises_id'] = $premises->dept_id;
- }
- }
- }
- $params['orderId'] = $params['order_id'];
- $params['orderGroupId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
- $order->order_groupby = $params['orderGroupId'];
- // $params['orderGroupId'] = $order->order_groupby;
- $goods = Goods::where('goods_id', $params['join_sheet_goods_id'])
- ->select('goods_id', 'goods_name', 'goods_classify')
- ->first();
- if (!$goods) {
- return json_fail('产品数据异常');
- }
- $goods = $goods->toArray();
- $params['goods_classify'] = $goods['goods_classify'] ?? '';
- $systemStatus = 'SENDING'; // 待发货
- // 立即结算
- if (in_array($params['goods_classify'], ['MEALS', 'VIP'])) {
- $order->order_is_complete = 'Y';
- $systemStatus = 'DONE';
- }
- if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $params['delivery'] == 'ARRIVAL') {
- $params['order_is_complete'] = 'N';
- $systemStatus = "WAITING";
- }
- // if ($params['goods_classify'] == 'PACKAGE' && $params['delivery'] == 'ARRIVAL') {
- // $systemStatus = "WAITING";
- // }
- Db::beginTransaction();
- try {
- // 使用优惠券
- $couponUseJson = [];
- if (!empty($order->order_discount_json)) {
- // 释放下单时选的优惠券
- $order->order_discount_json = $this->releaseCoupon(json_decode($order->order_discount_json, true));
- }
- if (!empty($params['join_order_member_id']) && !empty($params['preferential'])) {
- $couponResult = OrderService::payUseCoupon('pay', 'Y', $params['join_order_member_id'], $params['goodsContentList'], $params['preferential'], $params['order_amount_total']);
- if (!empty($couponResult['pay_amount']) && $couponResult['pay_amount'] != $params['order_amount_pay']) {
- throw new BusinessException("计算优惠后,实付金额错误!");
- }
- // 组装优惠券使用数据,存主表优惠里
- if (!empty($couponResult['use_coupon_json'])) {
- $couponUseJson = $couponResult['use_coupon_json'];
- }
- }
- // 存储优惠信息
- $order->order_discount_json = json_encode($this->discountRecord($couponUseJson, $params));
- // 组合支付时,付款码应收金额
- $qrcodePayAmount = 0;
- if ($params['pay_category'] == 'OFFLINE' || $params['pay_category'] == 'MONEY') {
- $order->order_status_system = $systemStatus;
- $order->order_status_payment = 'SUCCESS';
- if ($params['pay_category'] == 'OFFLINE' && !empty($params['pay_category_sub'])) {
- $params['pay_category'] = $params['pay_category_sub'];
- }
- } else if ($params['pay_category'] == 'CASH') { // 余额支付
- $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
- ->where('member_account_classify', 'CASH')
- ->where('member_account_status', 'ACTIVED')
- ->first();
- if (!$account) {
- throw new BusinessException('账户异常');
- }
- $amount = $account->member_account_surplus + $account->member_account_added;
- if ($params['order_amount_pay'] > $amount) {
- throw new BusinessException('账户余额不足');
- }
- if ($params['order_amount_pay'] > $account->member_account_surplus) {
- $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
- $account->member_account_surplus = 0;
- $account->member_account_added = $cut;
- } else {
- $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
- }
- $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
- $account->member_account_update_user_id = JwtToken::getCurrentId();
- $account->member_account_updatetimes = time();
- $account->save();
- $order->order_status_system = $systemStatus;
- $order->order_status_payment = 'SUCCESS';
- } else if ($params['pay_category'] == 'VIP') { // VIP支付
- $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
- ->where('member_account_classify', 'VIP')
- ->where('member_account_status', 'ACTIVED')
- ->first();
- if (!$account) {
- throw new BusinessException('账户异常');
- }
- $amount = $account->member_account_surplus + $account->member_account_added;
- if ($params['order_amount_pay'] > $amount) {
- throw new BusinessException('账户余额不足');
- }
- if ($params['order_amount_pay'] > $account->member_account_surplus) {
- $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
- $account->member_account_surplus = 0;
- $account->member_account_added = $cut;
- } else {
- $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
- }
- $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
- $account->member_account_update_user_id = JwtToken::getCurrentId();
- $account->member_account_updatetimes = time();
- $account->save();
- $order->order_status_system = $systemStatus;
- $order->order_status_payment = 'SUCCESS';
- } else if ($params['pay_category'] == 'WELFARE') { // 福利账户
- $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
- ->where('member_account_classify', 'WELFARE')
- ->where('member_account_status', 'ACTIVED')
- ->first();
- if (!$account) {
- throw new BusinessException('账户异常');
- }
- $account->member_account_surplus = floatval($account->member_account_surplus);
- if ($params['pay_constitute'] == 'N' && ($params['order_amount_pay'] > $account->member_account_surplus)) {
- throw new BusinessException('账户余额不足');
- }
- if ($params['pay_constitute'] == 'Y' && ($params['order_amount_pay'] > $account->member_account_surplus)) {
- $qrcodePayAmount = $params['order_amount_pay'] - $account->member_account_surplus;
- $params['order_amount_pay'] = $account->member_account_surplus;
- }
- if ($params['pay_constitute'] == 'N' && ($params['order_amount_pay'] <= $account->member_account_surplus)) {
- $order->order_status_system = $systemStatus;
- $order->order_status_payment = 'SUCCESS';
- }
- // 福利账户 300 、 700
- if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS'])) {
- $payDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
- ->where('pay_status', 'SUCCESS')
- ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
- ->whereIn('pay_category', ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'DESHES'])
- ->get()
- ->toArray();
- $payDetailArray = array_column($payDetails, 'pay_amount', 'join_pay_order_id');
- $refundPayDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
- ->where('pay_status', 'SUCCESS')
- ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
- ->where('pay_category', 'REFUND')
- ->get()
- ->toArray();
- $refundPayDetailArray = array_column($refundPayDetails, 'pay_amount', 'join_pay_order_id');
- $paySum = 0;
- foreach ($payDetailArray as $key => $item) {
- if (isset($refundPayDetailArray[$key])) {
- $paySum = $paySum + ($item - $refundPayDetailArray[$key]);
- continue;
- }
- $paySum = $paySum + $item;
- }
- if ($params['pay_constitute'] == 'N' && 700 - $paySum < $params['order_amount_pay']) {
- throw new BusinessException('超出福利限额');
- } else if ($params['pay_constitute'] == 'Y' && 700 - $paySum < $params['order_amount_pay']) {
- $qrcodePayAmount = $params['order_amount_pay'] - (700 - $paySum);
- $params['order_amount_pay'] = (700 - $paySum);
- }
- } else {
- $payDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
- ->where('pay_status', 'SUCCESS')
- ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
- ->whereNotIn('pay_category', ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'DESHES', 'REFUND', 'RECHARGE'])
- ->get()
- ->toArray();
- $payDetailArray = array_column($payDetails, 'pay_amount', 'join_pay_order_id');
- $refundPayDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
- ->where('pay_status', 'SUCCESS')
- ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
- ->where('pay_category', 'REFUND')
- ->get()
- ->toArray();
- $refundPayDetailArray = array_column($refundPayDetails, 'pay_amount', 'join_pay_order_id');
- $paySum = 0;
- foreach ($payDetailArray as $key => $item) {
- if (isset($refundPayDetailArray[$key])) {
- $paySum = $paySum + ($item - $refundPayDetailArray[$key]);
- continue;
- }
- $paySum = $paySum + $item;
- }
- if ($params['pay_constitute'] == 'N' && 300 - $paySum < $params['order_amount_pay']) {
- throw new BusinessException('超出福利限额');
- } else if ($params['pay_constitute'] == 'Y' && 300 - $paySum < $params['order_amount_pay']) {
- $qrcodePayAmount = $params['order_amount_pay'] - (300 - $paySum);
- $params['order_amount_pay'] = (300 - $paySum);
- }
- }
- $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
- $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
- $account->member_account_update_user_id = JwtToken::getCurrentId();
- $account->member_account_updatetimes = time();
- $account->save();
- } else if ($params['pay_category'] == 'CARD') { // 储值卡账户
- $cardNbr = $params['card_id'];
- if (!$cardNbr) {
- throw new BusinessException('账户异常');
- }
- $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
- ->where('member_account_nbr', $cardNbr)
- ->where('member_account_status', 'ACTIVED')
- ->first();
- if (!$account) {
- throw new BusinessException('账户异常');
- }
- $amount = $account->member_account_surplus + $account->member_account_added;
- if ($params['order_amount_pay'] > $amount) {
- throw new BusinessException('账户余额不足');
- }
- if ($params['order_amount_pay'] > $account->member_account_surplus) {
- $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
- $account->member_account_surplus = 0;
- $account->member_account_added = $cut;
- } else {
- $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
- }
- if ($account->member_account_surplus == 0){
- MemberService::accountToDone($account->member_account_id,$account->member_account_surplus,$account->member_account_added);
- }
- $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
- $account->member_account_update_user_id = JwtToken::getCurrentId();
- $account->member_account_updatetimes = time();
- $account->save();
- $order->order_status_system = $systemStatus;
- $order->order_status_payment = 'SUCCESS';
- }
- if (($params['pay_constitute'] == 'Y' || $params['pay_category'] == 'QRCODE') && !empty($params['qrcode_nbr'])) { // 付款码
- // 提交过来的支付分类
- $submitPayCategory = $params['pay_category'];
- // 账户支付的金额
- $accountAmount = $params['order_amount_pay'];
- if ($params['pay_constitute'] == 'Y' && $qrcodePayAmount > 0) {
- // 组合支付,改成需要付款码需要支付的金额
- $params['order_amount_pay'] = $qrcodePayAmount;
- }
- // 去支付
- $result = OrderService::qrcodePay($params);
- $result = json_encode($result);
- $params['pay_json_response'] = $result;
- $result = json_decode($result, true);
- $prefix = substr($params['qrcode_nbr'], 0, 2);
- if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
- $params['pay_category'] = 'WXPAY';
- 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')) {
- $order->order_status_system = $oldOrderSystemStatus;
- $order->order_status_payment = 'PENDING';
- $order->order_is_complete = 'N';
- // Db::rollBack();
- // return json_fail('支付失败');
- } else {
- $order->order_status_system = $systemStatus;
- $order->order_status_payment = 'SUCCESS';
- }
- } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
- $params['pay_category'] = 'ALIPAY';
- if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {
- $order->order_status_system = $oldOrderSystemStatus;
- $order->order_status_payment = 'PENDING';
- $order->order_is_complete = 'N';
- // Db::rollBack();
- // return json_fail('支付失败');
- } else {
- $order->order_status_system = $systemStatus;
- $order->order_status_payment = 'SUCCESS';
- }
- } else {
- throw new BusinessException('付款码无效');
- }
- //
- // // 组合支付,追加加一条支付记录 pay_detail
- // if ($params['pay_constitute'] == 'Y' && $qrcodePayAmount > 0) {
- // $insertPayDetailData = [
- // 'join_pay_member_id' => $params['join_order_member_id'],
- // 'join_pay_order_id' => $params['orderGroupId'],
- // 'pay_status' => 'SUCCESS',
- // 'pay_category' => $params['goods_classify'],
- // 'pay_amount' => $params['order_amount_pay'],
- // 'pay_paytimes' => date('Y-m-d H:i:s'),
- // 'pay_prepayid' => $params['pay_category'],
- // 'pay_json_request' => json_encode($params),
- // 'pay_json_response' => $params['pay_json_response'],
- // 'join_pay_object_json' => !empty($params['orderId']) ? json_encode(['order_id' => $params['orderId']]) : '[]',
- // 'pay_addtimes' => time()
- // ];
- //
- // PayDetail::insert($insertPayDetailData);
- //
- // // 组合支付,还原提交的支付分类
- // $params['pay_category'] = $submitPayCategory;
- // }
- // 账户支付的金额
- $params['order_amount_pay'] = $accountAmount;
- }
- $orderConfigJson = [];
- if (!empty($order->order_config_json)) {
- $orderConfigJson = json_decode($order->order_config_json, true);
- }
- $orderConfigJson['preferential'] = $params['preferential'] ?? '';
- if (isset($orderConfigJson['tableid']) && !empty($orderConfigJson['tableid'])) {
- SysDept::where('dept_id', $orderConfigJson['tableid'])->where('dept_category', '桌台')->update(['dept_status' => 'ACTIVED']);
- }
- $order->order_config_json = json_encode($orderConfigJson);
- $order->order_amount_pay = $params['order_amount_pay'] + $qrcodePayAmount;
- // 康养城订单,支付完就结束了
- if ($order->order_status_payment == 'SUCCESS' && $params['goods_classify'] == 'VIP') {
- $order->order_is_complete = 'Y';
- }
- // 主订单
- $order->save();
- // sheet
- OrderService::updateSheet($order, $systemStatus);
- // payDetail
- $payData = [
- 'pay_amount' => $params['order_amount_pay']
- ];
- if ($order->order_status_payment == 'SUCCESS') {
- $payData['pay_paytimes'] = date('Y-m-d H:i:s');
- $payData['pay_status'] = 'SUCCESS';
- }
- if ($params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) {
- $payData['pay_prepayid'] = $params['pay_category'];
- $payData['pay_json_response'] = $params['pay_json_response'];
- } else if ($params['pay_category'] == 'CASH') {
- $payData['pay_prepayid'] = $params['join_order_member_id'] . '-CASH';
- } else if ($params['pay_category'] == 'WELFARE') {
- $payData['pay_prepayid'] = $params['join_order_member_id'] . '-WELFARE';
- } else if ($params['pay_category'] == 'VIP') {
- $payData['pay_prepayid'] = $params['join_order_member_id'] . '-VIP';
- } else if ($params['pay_category'] == 'CARD') {
- $payData['pay_prepayid'] = $params['card_id'];
- } else if ($params['pay_category'] == 'OFFLINE') {
- $payData['pay_prepayid'] = 'OFFLINE';
- } else if ($params['pay_category'] == 'OFFLINE_ALIPAY') {
- $payData['pay_prepayid'] = 'OFFLINE_ALIPAY';
- } else if ($params['pay_category'] == 'OFFLINE_WXPAY') {
- $payData['pay_prepayid'] = 'OFFLINE_WXPAY';
- } else if ($params['pay_category'] == 'MONEY') {
- $payData['pay_prepayid'] = 'MONEY';
- }
- // 如果 是APP 过来的菜订单,可能没有paydetail
- if (!PayDetail::where('join_pay_order_id', $order->order_groupby)->where('pay_category', '<>', 'WXPAY')->where('pay_category', '<>', 'ALIPAY')->exists()) {
- $payData['join_pay_member_id'] = $params['join_order_member_id'];
- $payData['join_pay_order_id'] = $order->order_groupby;
- $payData['pay_status'] = !empty($payData['pay_status']) && $payData['pay_status'] == 'SUCCESS' ? $payData['pay_status'] : 'WAITING';
- $payData['pay_category'] = $params['goods_classify'] ?? '';
- $payData['pay_paytimes'] = date('Y-m-d H:i:s');
- $payData['pay_json_request'] = json_encode($params); // {"pay-result": "支付成功", "result-datetime": "2024-07-29 18:38:21"}
- $payData['pay_json_response'] = $payData['pay_status'] == 'SUCCESS' ? json_encode([
- 'pay-result' => '支付成功', 'result-datetime' => date('Y-m-d H:i:s')
- ]) : '[]';
- $payData['join_pay_object_json'] = !empty($params['orderId']) ? json_encode(['order_id' => $params['orderId']]) : '[]';
- $payData['pay_addtimes'] = time();
- PayDetail::insert($payData);
- } else {
- // 更新非微信支付宝的支付记录
- PayDetail::where('join_pay_order_id', $order->order_groupby)->where('pay_category', '<>', 'WXPAY')->where('pay_category', '<>', 'ALIPAY')->update($payData);
- }
- $writeOffDate = [];
- $applyData = [];
- // 有预约单,状态已完成
- $appointment = Appointment::where('join_appointment_order_id', $params['order_id'])->first();
- if ($order->order_status_payment == 'SUCCESS' && $appointment) {
- $writeOffDate = OrderService::generateWriteOffData($params);
- $applyData = OrderService::generateAppointmentApplyData($params);
- $appointment->appointment_status = 'DONE';
- $appointment->appointment_done_datetime = date('Y-m-d H:i:s');
- $appointment->appointment_done_json = json_encode($writeOffDate);
- if (empty($appointment->appointment_apply_datetime)) {
- $appointment->appointment_apply_datetime = date('Y-m-d H:i:s');
- }
- if (empty($appointment->appointment_apply_json)) {
- $appointment->appointment_apply_json = json_encode($applyData);
- }
- if (empty($appointment->appointment_datetime)) {
- $appointment->appointment_datetime = date('Y-m-d');
- }
- $appointment->save();
- }
- // // 买的单个服务
- if ($order->order_status_payment == 'SUCCESS' && empty($appointment)) {
- foreach ($params['goodsContentList'] as $goods) {
- $params['join_sheet_goods_id'] = $goods['goods_id'];
- if (isset($goods['goods_classify']) && in_array($goods['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD'])) {
- $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
- $params['order_sheet_num'] = $goods['nbr'];
- // 预约表
- for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
- $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
- // 入预约记录
- $this->insertAppointment($params, $writeOffDate, $applyData);
- }
- $goods['skuId'] = $goods['sku_id'];
- $goods['category'] = $goods['goods_classify'];
- // 权益表
- $this->insertMemberBenefit($params, $goods);
- } elseif (isset($goods['goods_classify']) && $goods['goods_classify'] == 'PACKAGE') { // 一个套餐买多个
- $params['packageId'] = $goods['goods_id'];
- $components = GoodsComponent::with([
- 'goods' => function ($query) {
- $query->select('goods_id', 'goods_name', 'goods_classify');
- }
- ])->where('join_component_master_goods_id', $params['packageId'])
- ->get()
- ->toArray();
- foreach ($components as $component) {
- $componentJson = json_decode($component['goods_component_json'], true);
- $params['join_sheet_goods_sku_id'] = $componentJson['sku_id'];
- $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
- $params['order_sheet_num'] = $goods['nbr'] * $componentJson['nbr'];
- for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
- $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
- // 入预约记录
- $this->insertAppointment($params, $writeOffDate);
- }
- $goods['goods_id'] = $component['join_component_goods_id'];
- $goods['goods_name'] = $component['goods']['goods_name'];
- $goods['goods_classify'] = $component['goods']['goods_classify'];
- $goods['skuId'] = $goods['sku_id'];
- $goods['category'] = 'SERVICE';
- // 权益表
- $this->insertMemberBenefit($params, $goods);
- }
- }
- }
- }
- // 2.4W 康养城
- if ($params['goods_classify'] == 'VIP' && $order->order_status_payment == 'SUCCESS') {
- $params['member_id'] = $params['join_order_member_id'];
- Event::dispatch('order.kangyangCityVIP.grant', $params);
- }
- Db::commit();
- // 触发事件
- if ($order->order_is_complete == 'Y' && $order->order_status_payment == 'SUCCESS') {
- // 加销售量
- OrderSheetService::addGoodsSales($params['orderId']);
- // 完成订单
- Event::dispatch('order.complete', $params);
- // 上级提成
- Event::dispatch('commission.order', $params);
- // 入收支明细表
- $params['inout_category'] = $oldOrderPaymentStatus == 'AWAITING' ? '挂账订单结算' : '餐饮订单';
- Event::dispatch('statistics.inout.in', $params);
- }
- // 打小票
- if (!empty($premises) && $params['goods_classify'] == 'MEALS') {
- dump("pay 打小票");
- $restaurant = SysDept::where('dept_super_id', $premises->dept_id)->where('dept_category', '餐厅')->first();
- if (!empty($restaurant->dept_extend_json)) {
- $deptExtendJson = json_decode($restaurant->dept_extend_json, true);
- if (isset($deptExtendJson['printer'])) {
- foreach ($deptExtendJson['printer'] as $key => $item) {
- if (strpos($key, '结算') !== false && $order->order_status_payment == 'SUCCESS') {
- $voteData = [
- 'func' => 'procActionToPrinter',
- 'sign' => '',
- 'data' => [
- 'printer_premises' => $restaurant->dept_id,
- 'printer_device' => [
- $key
- ],
- 'printer_action' => 'ExecPrintOrder',
- 'printer_data' => [
- 'order_id' => $params['order_id']
- ]
- ]
- ];
- http_post_json(getenv('VOTE_MENU_URL'), $voteData);
- }
- }
- }
- }
- }
- if ($order->order_status_payment != 'SUCCESS') {
- _syslog("订单", "支付异常,检查是否有轮询");
- // 恢复优惠券到已占用
- if (!is_array($couponUseJson)) {
- $couponUseJson = json_decode($couponUseJson, true);
- }
- $this->changeOrderCouponStatus($couponUseJson, 'WAITING');
- return json_throw(2001, '支付异常', ['order_id' => $params['orderId']]);
- }
- _syslog("订单", "订单支付成功");
- return json_success('支付成功');
- } catch (BusinessException $e) {
- Db::rollBack();
- _syslog("订单", "订单支付失败:" . $e->getMessage());
- Log::error("订单支付失败:" . $e->getMessage());
- return json_fail("支付失败:" . $e->getMessage());
- } catch (\Exception $e) {
- Db::rollBack();
- _syslog("订单", "订单支付失败");
- Log::error("订单支付失败:" . $e->getMessage());
- return json_fail('支付失败');
- }
- }
- private function discountRecord($orderDiscountJson, $params)
- {
- $json = [];
- if (!empty($orderDiscountJson)) {
- $json = json_decode($orderDiscountJson, true);
- }
- try {
- if (!empty($params['preferential']) && in_array('wipe', $params['preferential'])) {
- if (intval($params['order_amount_total'] / 10) * 10 != $params['order_amount_pay']) {
- throw new BusinessException("抹零后实际支付金额错误");
- }
- $params['order_discount_amount'] = $params['order_amount_total'] - $params['order_amount_pay'];
- $couponClassifyDesc = $couponClassify = '抹零';
- } elseif (!empty($params['preferential']) && in_array('custom', $params['preferential'])) {
- if (sprintf("%.2f", $params['order_amount_total'] - $params['order_discount_amount']) != sprintf("%.2f", $params['order_amount_pay'])) {
- throw new BusinessException("餐厅前台优惠后实际支付金额错误");
- }
- $couponClassifyDesc = $couponClassify = '餐厅前台优惠';
- } else if (!empty($params['preferential']) && intval($params['preferential'][0]) < 100 && intval($params['preferential'][0]) >= 50) {
- if (($params['order_amount_total'] * intval($params['preferential'][0])) / 100 != $params['order_amount_pay']) {
- throw new BusinessException("折扣后实际支付金额错误");
- }
- $couponClassify = '折扣';
- $couponClassifyDesc = intval($params['preferential'][0]) / 10 . '折';
- $params['order_discount_amount'] = $params['order_amount_total'] - $params['order_amount_pay'];
- } else {
- return $json;
- }
- $json[date('Y-m-d H:i:s')] = [
- 'coupon_id' => $params['coupon_id'] ?? null,
- 'coupon_value' => $params['order_discount_amount'] ?? '',
- 'coupon_classify' => $couponClassify,
- 'coupon_detail_id' => [$couponClassifyDesc],
- 'coupon_classify_en' => $params['preferential']
- ];
- return $json;
- } catch (BusinessException $e) {
- throw new BusinessException($e->getMessage());
- } catch (\Exception $e) {
- dump($e->getMessage());
- throw new BusinessException("优惠数据错误");
- }
- }
- /**
- * 组合支付
- */
- public function payConstitute(Request $request)
- {
- $params = $request->post();
- // 余额、福利、储值卡 验证短信
- 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']))) {
- $code = $params['sms_code'];
- if (!$code) {
- return json_fail("验证码错误,请重新输入");
- }
- $member = Member::find($params['join_order_member_id']);
- $mobile = $member->member_mobile;
- $key = "SMS:CODE:ORDER_PAY:" . $mobile;
- $redisCode = Redis::get($key);
- if ($redisCode != $code && $code != '123654879') {
- return json_fail("验证码错误,请重新输入");
- }
- Redis::del($key);
- }
- // 验证线下付款密码
- if (!empty($params['pay_category_constitute']) && in_array('OFFLINE', $params['pay_category_constitute']) && in_array('MONEY', $params['pay_category_constitute'])) {
- $password = $params['offline_password'];
- if ($password != '666888') {
- return json_fail("密码错误,请重新输入");
- }
- }
- $order = Order::where('order_id', $params['order_id'])->first();
- $oldOrderPaymentStatus = $order->order_status_payment;
- if (!$order) {
- return json_fail('订单异常');
- }
- if ($order->order_status_system != 'PAYING') {
- return json_fail('订单不是可支付状态');
- }
- if (!empty($order->order_config_json)) {
- $orderConfigJson = json_decode($order->order_config_json, true);
- if (isset($orderConfigJson['premises'])) {
- $premises = SysDept::where('dept_name', $orderConfigJson['premises'])->first();
- if (!empty($premises)) {
- $params['submit_premises_id'] = $premises->dept_id;
- }
- }
- }
- $params['orderId'] = $params['order_id'];
- $params['orderGroupId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
- $order->order_groupby = $params['orderGroupId'];
- $goods = Goods::where('goods_id', $params['join_sheet_goods_id'])
- ->select('goods_id', 'goods_name', 'goods_classify')
- ->first();
- if (!$goods) {
- return json_fail('产品数据异常');
- }
- $goods = $goods->toArray();
- $params['goods_classify'] = $goods['goods_classify'];
- $systemStatus = 'SENDING'; // 待发货
- // 立即结算
- if (in_array($params['goods_classify'], ['MEALS', 'VIP'])) {
- $order->order_is_complete = 'Y';
- $systemStatus = 'DONE';
- }
- if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $params['delivery'] == 'ARRIVAL') {
- $params['order_is_complete'] = 'N';
- $systemStatus = "WAITING";
- }
- $payDetail = PayDetail::where('join_pay_order_id', $order->order_groupby)->first();
- Db::beginTransaction();
- try {// 使用优惠券
- $couponUseJson = [];
- if (!empty($order->order_discount_json)) {
- // 释放下单时选的优惠券
- $order->order_discount_json = $this->releaseCoupon(json_decode($order->order_discount_json, true));
- }
- if (!empty($params['join_order_member_id']) && !empty($params['preferential'])) {
- $couponResult = OrderService::payUseCoupon('pay', 'Y', $params['join_order_member_id'], $params['goodsContentList'], $params['preferential'], $params['order_amount_total']);
- if (!empty($couponResult['pay_amount']) && $couponResult['pay_amount'] != $params['order_amount_pay']) {
- throw new BusinessException("计算优惠后,实付金额错误!");
- }
- // 组装优惠券使用数据,存主表优惠里
- if (!empty($couponResult['use_coupon_json'])) {
- $couponUseJson = $couponResult['use_coupon_json'];
- }
- }
- // 存储优惠信息
- $order->order_discount_json = json_encode($this->discountRecord($couponUseJson, $params));
- $orderAmountPay = $params['order_amount_pay'];
- $constituteList = array_column($params['pay_category_constitute_list'], 'amount', 'category');// 验证金额
- $constituteAmount = 0;
- foreach ($params['pay_category_constitute_list'] as $item) {
- $constituteAmount = $constituteAmount + $item['amount'];
- }
- if ($params['order_amount_pay'] != $constituteAmount) {
- throw new BusinessException('组合支付金额与应付金额不一致');
- }
- $wxAndAliPayStatus = 'Y';
- $waitToPayAccount = [];
- // 清除paydetail 中的未支付记录
- PayDetail::where('join_pay_order_id', $params['orderGroupId'])->where('pay_status', '<>', 'SUCCESS')->delete();
- if (!empty($params['pay_category_constitute']) && in_array('OFFLINE', $params['pay_category_constitute'])) { //线下付款
- $order->order_status_system = $systemStatus;
- $order->order_status_payment = 'SUCCESS';
- $params['pay_category'] = $params['pay_category_sub'] ?? 'OFFLINE';
- // 线下支付金额
- if (isset($constituteList['OFFLINE'])) {
- $params['order_amount_pay'] = $constituteList['OFFLINE'];
- // 生成支付记录
- $params['order_status_payment'] = 'PENDING';
- OrderService::createPayConstituteDetail($params, $payDetail);
- $params['order_status_payment'] = 'SUCCESS';
- }
- $params['order_amount_pay'] = $orderAmountPay;
- }
- if (!empty($params['pay_category_constitute']) && in_array('MONEY', $params['pay_category_constitute'])) { //现金付款
- $order->order_status_system = $systemStatus;
- $order->order_status_payment = 'SUCCESS';
- $params['pay_category'] = 'MONEY';
- // 线下支付金额
- if (isset($constituteList['MONEY'])) {
- $params['order_amount_pay'] = $constituteList['MONEY'];
- // 生成支付记录
- $params['order_status_payment'] = 'PENDING';
- OrderService::createPayConstituteDetail($params, $payDetail);
- $params['order_status_payment'] = 'SUCCESS';
- }
- $params['order_amount_pay'] = $orderAmountPay;
- }
- if (!empty($params['pay_category_constitute']) && in_array('CASH', $params['pay_category_constitute'])) { // 余额支付
- $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
- ->where('member_account_classify', 'CASH')
- ->where('member_account_status', 'ACTIVED')
- ->first();
- if (!$account) {
- throw new BusinessException('账户异常');
- }
- if (isset($constituteList['CASH'])) {
- $params['order_amount_pay'] = $constituteList['CASH'];
- $params['pay_category'] = $params['join_order_member_id'] . '-CASH';
- }
- $amount = $account->member_account_surplus + $account->member_account_added;
- if ($params['order_amount_pay'] > $amount) {
- throw new BusinessException('账户余额不足');
- }
- // 余额账户扣款数据
- $waitToPayAccount['cash'] = [
- 'group_id' => $params['orderGroupId'],
- 'member_id' => $params['join_order_member_id'],
- 'amount' => $constituteList['CASH'],
- 'nbr' => $params['join_order_member_id'] . '-CASH'
- ];
- // 生成支付记录
- $params['order_status_payment'] = 'PENDING';
- OrderService::createPayConstituteDetail($params, $payDetail);
- $params['order_status_payment'] = 'SUCCESS';
- $params['order_amount_pay'] = $orderAmountPay;
- $order->order_status_system = $systemStatus;
- $order->order_status_payment = 'SUCCESS';
- }
- if (!empty($params['pay_category_constitute']) && in_array('CARD', $params['pay_category_constitute'])) { // 储值卡账户
- foreach ($params['pay_category_constitute_list'] as $constituteList2) {
- if ($constituteList2['category'] != 'CARD') {
- continue;
- }
- $cardNbr = $constituteList2['card_id'];
- $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
- ->where('member_account_nbr', $cardNbr)
- ->where('member_account_status', 'ACTIVED')
- ->first();
- if (!$account) {
- Db::rollBack();
- return json_fail('账户异常');
- }
- // 储值卡账户支付金额
- if (isset($constituteList2['amount'])) {
- $params['order_amount_pay'] = $constituteList2['amount'];
- $params['pay_category'] = $cardNbr;
- }
- $amount = $account->member_account_surplus + $account->member_account_added;
- if ($params['pay_constitute'] == 'Y' && $params['order_amount_pay'] > $amount) {
- throw new BusinessException('账户余额不足');
- }
- // 储值卡账户扣款数据
- $waitToPayAccount[$cardNbr] = [
- 'group_id' => $params['orderGroupId'],
- 'member_id' => $params['join_order_member_id'],
- 'amount' => $constituteList2['amount'],
- 'nbr' => $cardNbr
- ];
- // 生成支付记录
- $params['order_status_payment'] = 'PENDING';
- OrderService::createPayConstituteDetail($params, $payDetail);
- $params['order_status_payment'] = 'SUCCESS';
- $params['order_amount_pay'] = $orderAmountPay;
- $order->order_status_system = $systemStatus;
- $order->order_status_payment = 'SUCCESS';
- }
- }
- if (!empty($params['pay_category_constitute']) && in_array('QRCODE', $params['pay_category_constitute']) && !empty($params['qrcode_nbr'])) { // 付款码
- if (isset($constituteList['QRCODE']) && $constituteList['QRCODE'] > 0) {
- // 付款码支付金额
- $params['order_amount_pay'] = $constituteList['QRCODE'];
- // 调支付
- $result = OrderService::qrcodePay($params);
- $result = json_encode($result);
- $params['pay_json_response'] = $result;
- $result = json_decode($result, true);
- $prefix = substr($params['qrcode_nbr'], 0, 2);
- if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
- $params['pay_category'] = 'WXPAY';
- 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')) {
- // 标记支付状态
- $wxAndAliPayStatus = 'N';
- $order->order_status_system = 'PAYING';
- $order->order_status_payment = 'PENDING';
- $order->order_is_complete = 'N';
- } else {
- $order->order_status_system = $systemStatus;
- $order->order_status_payment = 'SUCCESS';
- }
- } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
- $params['pay_category'] = 'ALIPAY';
- if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {
- // 标记支付状态
- $wxAndAliPayStatus = 'N';
- $order->order_status_system = 'PAYING';
- $order->order_status_payment = 'PENDING';
- $order->order_is_complete = 'N';
- } else {
- $order->order_status_system = $systemStatus;
- $order->order_status_payment = 'SUCCESS';
- }
- } else {
- throw new BusinessException('付款码无效');
- }
- }
- // 生成支付记录
- OrderService::createPayConstituteDetail($params, $payDetail);
- // 账户支付的金额
- $params['order_amount_pay'] = $orderAmountPay;
- }
- $orderConfigJson = [];
- if (!empty($order->order_config_json)) {
- $orderConfigJson = json_decode($order->order_config_json, true);
- }
- $orderConfigJson['preferential'] = $params['preferential'] ?? '';
- if (isset($orderConfigJson['tableid']) && !empty($orderConfigJson['tableid'])) {
- SysDept::where('dept_id', $orderConfigJson['tableid'])->where('dept_category', '桌台')->update(['dept_status' => 'ACTIVED']);
- }
- $order->order_config_json = json_encode($orderConfigJson);
- $order->order_amount_pay = $params['order_amount_pay'];
- // 主订单
- $order->save();
- // sheet
- if ($order->order_status_payment == 'SUCCESS') {
- OrderService::updateSheet($order, $systemStatus);
- }
- if ($wxAndAliPayStatus == 'Y') {
- PayDetail::whereJsonContains('join_pay_object_json->order_id', $params['orderId'])->update([
- 'pay_status' => 'SUCCESS',
- 'pay_paytimes' => date('Y-m-d H:i:s')
- ]);
- // 扣款
- foreach ($waitToPayAccount as $item) {
- $accountNbr = $item['nbr'];
- $account = MemberAccount::where('member_account_nbr', $accountNbr)->first();
- $account->member_account_expend = $account->member_account_expend + $item['amount'];
- if ($account->member_account_surplus < $item['amount'] && strpos($accountNbr, 'CASH') !== false) {
- $account->member_account_added = $account->member_account_added - ($item['amount'] - $account->member_account_surplus);
- $account->member_account_surplus = 0;
- } else {
- $account->member_account_surplus = $account->member_account_surplus - $item['amount'];
- }
- dump($account->member_account_classify.':'.$account->member_account_surplus);
- if ($account->member_account_surplus <= 0){
- MemberService::accountToDone($account->member_account_id,$account->member_account_surplus,$account->member_account_added);
- }
- $account->member_account_update_user_id = JwtToken::getCurrentId();
- $account->member_account_updatetimes = time();
- $account->save();
- }
- }
- $writeOffDate = [];
- $applyData = [];
- // 有预约单,状态已完成
- $appointment = Appointment::where('join_appointment_order_id', $params['order_id'])->first();
- if ($order->order_status_payment == 'SUCCESS' && $appointment) {
- $writeOffDate = OrderService::generateWriteOffData($params);
- $applyData = OrderService::generateAppointmentApplyData($params);
- $appointment->appointment_status = 'DONE';
- $appointment->appointment_done_datetime = date('Y-m-d H:i:s');
- $appointment->appointment_done_json = json_encode($writeOffDate);
- if (empty($appointment->appointment_apply_datetime)) {
- $appointment->appointment_apply_datetime = date('Y-m-d H:i:s');
- }
- if (empty($appointment->appointment_apply_json)) {
- $appointment->appointment_apply_json = json_encode($applyData);
- }
- if (empty($appointment->appointment_datetime)) {
- $appointment->appointment_datetime = date('Y-m-d');
- }
- $appointment->save();
- }
- // 买单个服务
- if ($order->order_status_payment == 'SUCCESS' && empty($appointment)) {
- foreach ($params['goodsContentList'] as $goods) {
- $params['join_sheet_goods_id'] = $goods['goods_id'];
- if (isset($goods['goods_classify']) && in_array($goods['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD'])) {
- $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
- $params['order_sheet_num'] = $goods['nbr'];
- // 预约表
- for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
- $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
- // 入预约记录
- $this->insertAppointment($params, $writeOffDate, $applyData);
- }
- $goods['skuId'] = $goods['sku_id'];
- $goods['category'] = $goods['goods_classify'];
- // 权益表
- $this->insertMemberBenefit($params, $goods);
- } elseif (isset($goods['goods_classify']) && $goods['goods_classify'] == 'PACKAGE') { // 一个套餐买多个
- $params['packageId'] = $goods['goods_id'];
- $components = GoodsComponent::with([
- 'goods' => function ($query) {
- $query->select('goods_id', 'goods_name', 'goods_classify');
- }
- ])->where('join_component_master_goods_id', $params['packageId'])
- ->get()
- ->toArray();
- foreach ($components as $component) {
- $componentJson = json_decode($component['goods_component_json'], true);
- $params['join_sheet_goods_sku_id'] = $componentJson['sku_id'];
- $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
- $params['order_sheet_num'] = $goods['nbr'] * $componentJson['nbr'];
- for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
- $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
- // 入预约记录
- $this->insertAppointment($params, $writeOffDate);
- }
- $goods['goods_id'] = $component['join_component_goods_id'];
- $goods['goods_name'] = $component['goods']['goods_name'];
- $goods['goods_classify'] = $component['goods']['goods_classify'];
- $goods['skuId'] = $goods['sku_id'];
- $goods['category'] = 'SERVICE';
- // 权益表
- $this->insertMemberBenefit($params, $goods);
- }
- }
- }
- }
- // 2.4W 康养城
- if ($params['goods_classify'] == 'VIP' && $order->order_status_payment == 'SUCCESS') {
- $params['member_id'] = $params['join_order_member_id'];
- Event::dispatch('order.kangyangCityVIP.grant', $params);
- }
- Db::commit();
- // 触发事件
- if ($order->order_is_complete == 'Y' && $order->order_status_payment == 'SUCCESS') {
- // 加销售量
- OrderSheetService::addGoodsSales($params['orderId']);
- // 完成订单
- Event::dispatch('order.complete', $params);
- // 上级提成
- Event::dispatch('commission.order', $params);
- // 入收支明细表
- $params['inout_category'] = $oldOrderPaymentStatus == 'AWAITING' ? '挂账订单结算' : '餐饮订单';
- Event::dispatch('statistics.inout.in', $params);
- }
- // 打小票
- if (!empty($premises) && $params['goods_classify'] == "MEALS") {
- dump('payCons 打小票');
- $restaurant = SysDept::where('dept_super_id', $premises->dept_id)->where('dept_category', '餐厅')->first();
- if (!empty($restaurant->dept_extend_json)) {
- $deptExtendJson = json_decode($restaurant->dept_extend_json, true);
- if (isset($deptExtendJson['printer'])) {
- foreach ($deptExtendJson['printer'] as $key => $item) {
- if (strpos($key, '结算') !== false && $order->order_status_payment == 'SUCCESS') {
- $voteData = [
- 'func' => 'procActionToPrinter',
- 'sign' => '',
- 'data' => [
- 'printer_premises' => $restaurant->dept_id,
- 'printer_device' => [
- $key
- ],
- 'printer_action' => 'ExecPrintOrder',
- 'printer_data' => [
- 'order_id' => $params['order_id']
- ]
- ]
- ];
- http_post_json(getenv('VOTE_MENU_URL'), $voteData);
- }
- }
- }
- }
- }
- if ($order->order_status_payment != 'SUCCESS') {
- _syslog("订单", "支付异常,检查是否有轮询");
- // 恢复优惠券到已占用
- if (!is_array($couponUseJson)) {
- $couponUseJson = json_decode($couponUseJson, true);
- }
- $this->changeOrderCouponStatus($couponUseJson, 'WAITING');
- return json_throw(2001, '支付异常', ['order_id' => $params['orderId']]);
- }
- _syslog("订单", "订单支付成功");
- return json_success('支付成功');
- } catch (\Exception $e) {
- Db::rollBack();
- _syslog("订单", "订单支付失败");
- return json_fail('支付失败');
- }
- }
- /**
- * 删除订单
- */
- public function delete(Request $request): Response
- {
- $params = $request->post();
- Db::beginTransaction();
- try {
- $order = Order::where('order_id', $params['order_id'])
- ->where('order_status_system', 'CANCEL')
- ->orWhere(function ($query) use ($params) {
- $query->whereIn('order_status_system', ['WAITING', 'SENDING'])->where('order_category', 'SYSTEM')->where('order_id', $params['order_id']);
- })
- ->first();
- if (!$order) {
- return json_fail('此订单不允许删除');
- }
- $payDetail = PayDetail::where('join_pay_order_id', $order->order_groupby)->first();
- if ($payDetail) {
- $payType = explode('-', $payDetail->pay_prepayid);
- // 余额支付
- if (isset($payType[1]) && $payType[1] == 'CASH') {
- $memberAccount = MemberAccount::where('join_account_member_id', $payDetail->join_pay_member_id)
- ->where('member_account_classify', 'CASH')
- ->first();
- $memberAccount->member_account_expend = $memberAccount->member_account_expend - $payDetail->pay_amount;
- $memberAccount->member_account_surplus = $memberAccount->member_account_surplus + $payDetail->pay_amount;
- $memberAccount->member_account_update_user_id = JwtToken::getCurrentId();
- $memberAccount->member_account_updatetimes = time();
- $memberAccount->save();
- }
- // 员工福利支付
- if (isset($payType[1]) && $payType[1] == 'WELFARE') {
- $memberAccount = MemberAccount::where('join_account_member_id', $payDetail->join_pay_member_id)
- ->where('member_account_classify', 'WELFARE')
- ->first();
- $memberAccount->member_account_expend = $memberAccount->member_account_expend - $payDetail->pay_amount;
- $memberAccount->member_account_surplus = $memberAccount->member_account_surplus + $payDetail->pay_amount;
- $memberAccount->member_account_update_user_id = JwtToken::getCurrentId();
- $memberAccount->member_account_updatetimes = time();
- $memberAccount->save();
- }
- // 删支付记录
- $payDetail->delete();
- }
- // 删收货信息
- OrderExpress::where('join_express_order_id', $params['order_id'])->delete();
- // 删订单详情
- OrderSheet::where('join_sheet_order_id', $params['order_id'])->delete();
- // 删主订单
- Order::where('order_id', $params['order_id'])->delete();
- Db::commit();
- _syslog("订单", "删除订单成功");
- return json_success('删除订单成功');
- } catch (\Exception $e) {
- dump($e->getMessage());
- Db::rollBack();
- _syslog("订单", "删除订单失败");
- return json_fail('删除订单失败');
- }
- }
- /**
- * 取消订单
- */
- public function cancelOrder(Request $request)
- {
- $orderId = $request->post('order_id', '');
- if (!$orderId) {
- return json_fail('参数异常');
- }
- Db::beginTransaction();
- try {
- $order = Order::where('order_id', $orderId)->first();
- if (empty($order)) {
- return json_fail('订单数据异常');
- }
- if ($order->order_status_system != 'PAYING') {
- return json_fail('仅未支付的订单可以取消!');
- }
- if (!empty($order->order_discount_json)) {
- $orderDiscountJson = json_decode($order->order_discount_json, true);
- foreach ($orderDiscountJson as $discount) {
- if (!empty($discount['coupon_id']) && !empty($discount['coupon_detail_id'])) {
- foreach ($discount['coupon_detail_id'] as $detailId) {
- if (substr($detailId, 0, 4) == 'CUDT') {
- // 恢复优惠券
- CouponDetail::where('coupon_detail_id', $detailId)->update(['coupon_detail_status' => 'ACTIVED']);
- }
- }
- }
- }
- }
- // sheet 表
- OrderSheet::where('join_sheet_order_id', $orderId)->update(['order_sheet_status' => 'CANCEL']);
- // payDetail 表
- PayDetail::where('join_pay_order_id', $order->order_groupby)->update([
- 'pay_status' => 'CANCEL',
- 'pay_extend_json' => json_encode(['cancel_times' => date('Y-m-d H:i:s')])
- ]);
- if (!empty($order->order_config_json)) {
- $orderConfigJson = json_decode($order->order_config_json, true);
- if (isset($orderConfigJson['tableid']) && !empty($orderConfigJson['tableid'])) {
- SysDept::where('dept_id', $orderConfigJson['tableid'])->update(['dept_status' => 'ACTIVED']);
- }
- }
- // 主表存取消时间吧
- $orderExtendJson = [];
- if (!empty($order->order_extend_json)) {
- $orderExtendJson = json_decode($order->order_extend_json, true);
- }
- $orderExtendJson['cancel_times'] = date('Y-m-d H:i:s');
- $order->order_extend_json = json_encode($orderExtendJson, JSON_UNESCAPED_UNICODE);
- $order->order_is_complete = 'Y';
- $order->order_status_system = 'CANCEL';
- $order->order_status_payment = 'CANCEL';
- $order->save();
- Db::commit();
- return json_success('');
- } catch (\Exception $e) {
- Db::rollBack();
- return json_fail('订单取消失败');
- }
- }
- public function insert(Request $request): Response
- {
- $params = $request->post();
- // 判断餐品是否连带着服务或实体
- $goodsClassifys = array_unique(array_column($params['goodsContentList'], 'goods_classify'));
- if (in_array('MEALS', $goodsClassifys) && count($goodsClassifys) > 1) {
- return json_fail('餐饮餐品不支持和其他类型的产品一起下单');
- }
- if (in_array('MEALS', $goodsClassifys)) {
- $params['submit_goods_classify'] = 'MEALS';
- }
- if (in_array('PACKAGE', $goodsClassifys)) {
- $params['submit_goods_classify'] = 'PACKAGE';
- }
- if (!empty($params['dept_premises_id'])) {
- $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();
- }
- $params['goods_classify'] = $goodsClassifys[0];
- Db::beginTransaction();
- try {
- // 使用优惠券
- $couponUseJson = [];
- if (!empty($params['join_order_member_id']) && !empty($params['preferential'])) {
- $couponResult = OrderService::payUseCoupon('insert', $params['settlement_now'], $params['join_order_member_id'], $params['goodsContentList'], $params['preferential'], $params['order_amount_total']);
- if (!empty($couponResult['pay_amount']) && $couponResult['pay_amount'] != $params['order_amount_pay']) {
- throw new BusinessException("计算优惠后,实付金额错误!");
- }
- // 组装优惠券使用数据,存主表优惠里
- if (!empty($couponResult['use_coupon_json'])) {
- $couponUseJson = $couponResult['use_coupon_json'];
- }
- }
- // 存储优惠信息
- $params['order_discount_json'] = json_encode($this->discountRecord($couponUseJson, $params));
- // 验证库存
- foreach ($params['goodsContentList'] as $goods) {
- // 减库存,规格和总库存
- if (!isset($params['submit_goods_classify']) || !in_array($params['submit_goods_classify'], ['MEALS', 'PACKAGE'])) {
- $goodsSku = GoodsSku::where('goods_sku_id', $goods['sku_id'])->first();
- $skuStorageJson = json_decode($goodsSku->goods_sku_storage_json, true);
- if (isset($skuStorageJson['storage']) && !empty($skuStorageJson['storage'])) {
- $skuStorageJson['storage'] = $skuStorageJson['storage'] - $goods['nbr'];
- }
- if (!isset($skuStorageJson['storage']) || (!empty($skuStorageJson['storage']) && $skuStorageJson['storage'] < 0)) {
- throw new BusinessException('库存不足');
- }
- }
- $goodsRunning = GoodsRunning::where('join_running_goods_id', $goods['goods_id'])->first();
- $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $goods['nbr'];
- if ($goodsRunning->goods_running_storage < 0) {
- throw new BusinessException('库存不足');
- }
- }
- // 余额、福利、储值卡 验证短信
- if ($params['settlement_now'] == 'Y' && $params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['CASH', 'CARD', 'WELFARE', 'VIP'])) {
- $code = $params['sms_code'];
- if (!$code) {
- throw new BusinessException('验证码错误,请重新输入');
- }
- $member = Member::find($params['join_order_member_id']);
- $mobile = $member->member_mobile;
- $key = "SMS:CODE:ORDER_PAY:" . $mobile;
- $redisCode = Redis::get($key);
- if ($redisCode != $code && $code != '123654879') {
- throw new BusinessException('验证码错误,请重新输入');
- }
- Redis::del($key);
- }
- // 验证线下付款密码
- if ($params['settlement_now'] == 'Y' && $params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['OFFLINE', 'MONEY'])) {
- $password = $params['offline_password'];
- if ($password != '666888') {
- throw new BusinessException('密码错误,请重新输入');
- }
- }
- // 下单账户
- if (empty($params['join_order_member_id']) && !empty($params['mobile'])) {
- if (Member::where('member_mobile', $params['mobile'])->exists()) {
- throw new BusinessException('会员已存在');
- }
- $params['join_order_member_id'] = $params['member_id'] = 'MR' . date('ymdHi') . random_string(4, 'up');
- // 创建会员
- MemberService::createMember($params);
- } else if (empty($params['join_order_member_id']) && empty($params['mobile'])) {
- $params['join_order_member_id'] = Member::where('member_mobile', '0000')->value('member_id');
- }
- if (empty($params['join_order_member_id'])) {
- throw new BusinessException('检查下单账户');
- }
- $qrcodePayAmount = 0;
- $params['orderId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
- $params['orderGroupId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
- $systemStatus = 'SENDING'; // 待发货
- // 立即结算
- if ($params['settlement_now'] == 'Y') {
- if (in_array($params['goods_classify'], ['MEALS', 'VIP'])) {
- $params['order_is_complete'] = 'Y';
- $systemStatus = 'DONE';
- }
- if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $params['delivery'] == 'ARRIVAL') {
- $params['order_is_complete'] = 'N';
- $systemStatus = "WAITING";
- }
- }
- if ($params['settlement_now'] == 'Y' && ($params['pay_category'] == 'OFFLINE' || $params['pay_category'] == 'MONEY')) {
- if ($params['pay_category'] == 'OFFLINE' && !empty($params['pay_category_sub'])) {
- $params['pay_category'] = $params['pay_category_sub'];
- }
- $params['order_status_system'] = $systemStatus;
- $params['order_status_payment'] = 'SUCCESS';
- } else if ($params['settlement_now'] == 'Y' && $params['pay_category'] == 'CASH') { // 余额支付
- $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
- ->where('member_account_classify', 'CASH')
- ->where('member_account_status', 'ACTIVED')
- ->first();
- if (!$account) {
- throw new BusinessException('账户异常');
- }
- $amount = $account->member_account_surplus + $account->member_account_added;
- if ($params['order_amount_pay'] > $amount) {
- throw new BusinessException('账户余额不足');
- }
- if ($params['order_amount_pay'] > $account->member_account_surplus) {
- $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
- $account->member_account_surplus = 0;
- $account->member_account_added = $cut;
- } else {
- $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
- }
- $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
- $account->member_account_update_user_id = JwtToken::getCurrentId();
- $account->member_account_updatetimes = time();
- $account->save();
- if ($params['pay_constitute'] == 'N') {
- $params['order_status_system'] = $systemStatus;
- $params['order_status_payment'] = 'SUCCESS';
- }
- } else if ($params['settlement_now'] == 'Y' && $params['pay_category'] == 'VIP') { // VIP支付
- $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
- ->where('member_account_classify', 'VIP')
- ->where('member_account_status', 'ACTIVED')
- ->first();
- if (!$account) {
- throw new BusinessException('账户异常');
- }
- $amount = $account->member_account_surplus + $account->member_account_added;
- if ($params['order_amount_pay'] > $amount) {
- throw new BusinessException('账户余额不足');
- }
- if ($params['order_amount_pay'] > $account->member_account_surplus) {
- $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
- $account->member_account_surplus = 0;
- $account->member_account_added = $cut;
- } else {
- $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
- }
- $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
- $account->member_account_update_user_id = JwtToken::getCurrentId();
- $account->member_account_updatetimes = time();
- $account->save();
- $params['order_status_system'] = $systemStatus;
- $params['order_status_payment'] = 'SUCCESS';
- } else if ($params['settlement_now'] == 'Y' && $params['pay_category'] == 'WELFARE') { // 福利账户
- $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
- ->where('member_account_classify', 'WELFARE')
- ->where('member_account_status', 'ACTIVED')
- ->first();
- if (!$account) {
- throw new BusinessException('账户异常');
- }
- $account->member_account_surplus = floatval($account->member_account_surplus);
- if ($params['pay_constitute'] == 'N' && ($params['order_amount_pay'] > $account->member_account_surplus)) {
- throw new BusinessException('账户余额不足');
- }
- if ($params['pay_constitute'] == 'Y' && ($params['order_amount_pay'] > $account->member_account_surplus)) {
- $qrcodePayAmount = $params['order_amount_pay'] - $account->member_account_surplus;
- $params['order_amount_pay'] = $account->member_account_surplus;
- }
- if ($params['pay_constitute'] == 'N') {
- $params['order_status_system'] = $systemStatus;
- $params['order_status_payment'] = 'SUCCESS';
- }
- // 福利账户 300 、 700
- if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS'])) {
- $payDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
- ->where('pay_status', 'SUCCESS')
- ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
- ->whereIn('pay_category', ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'DESHES'])
- ->get()
- ->toArray();
- $payDetailArray = array_column($payDetails, 'pay_amount', 'join_pay_order_id');
- $refundPayDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
- ->where('pay_status', 'SUCCESS')
- ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
- ->where('pay_category', 'REFUND')
- ->get()
- ->toArray();
- $refundPayDetailArray = array_column($refundPayDetails, 'pay_amount', 'join_pay_order_id');
- $paySum = 0;
- foreach ($payDetailArray as $key => $item) {
- if (isset($refundPayDetailArray[$key])) {
- $paySum = $paySum + ($item - $refundPayDetailArray[$key]);
- continue;
- }
- $paySum = $paySum + $item;
- }
- if ($params['pay_constitute'] == 'N' && 700 - $paySum < $params['order_amount_pay']) {
- Db::rollBack();
- return json_fail('超出福利限额');
- } else if ($params['pay_constitute'] == 'Y' && 700 - $paySum < $params['order_amount_pay']) {
- $qrcodePayAmount = $params['order_amount_pay'] - (700 - $paySum);
- $params['order_amount_pay'] = (700 - $paySum);
- }
- } else {
- $payDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
- ->where('pay_status', 'SUCCESS')
- ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
- ->whereNotIn('pay_category', ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'DESHES', 'REFUND', 'RECHARGE'])
- ->get()
- ->toArray();
- $payDetailArray = array_column($payDetails, 'pay_amount', 'join_pay_order_id');
- $refundPayDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
- ->where('pay_status', 'SUCCESS')
- ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
- ->where('pay_category', 'REFUND')
- ->get()
- ->toArray();
- $refundPayDetailArray = array_column($refundPayDetails, 'pay_amount', 'join_pay_order_id');
- $paySum = 0;
- foreach ($payDetailArray as $key => $item) {
- if (isset($refundPayDetailArray[$key])) {
- $paySum = $paySum + ($item - $refundPayDetailArray[$key]);
- continue;
- }
- $paySum = $paySum + $item;
- }
- if ($params['pay_constitute'] == 'N' && 300 - $paySum < $params['order_amount_pay']) {
- throw new BusinessException('超出福利限额');
- } else if ($params['pay_constitute'] == 'Y' && 300 - $paySum < $params['order_amount_pay']) {
- $qrcodePayAmount = $params['order_amount_pay'] - (300 - $paySum);
- $params['order_amount_pay'] = (300 - $paySum);
- }
- }
- $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
- $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
- $account->member_account_update_user_id = JwtToken::getCurrentId();
- $account->member_account_updatetimes = time();
- $account->save();
- } else if ($params['settlement_now'] == 'Y' && $params['pay_category'] == 'CARD') { // 储值卡账户
- $cardNbr = $params['card_id'];
- if (!$cardNbr) {
- throw new BusinessException('账户异常');
- }
- $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
- ->where('member_account_nbr', $cardNbr)
- ->where('member_account_status', 'ACTIVED')
- ->first();
- if (!$account) {
- throw new BusinessException('账户异常');
- }
- $amount = $account->member_account_surplus + $account->member_account_added;
- if ($params['order_amount_pay'] > $amount) {
- throw new BusinessException('账户余额不足');
- }
- if ($params['order_amount_pay'] > $account->member_account_surplus) {
- $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
- $account->member_account_surplus = 0;
- $account->member_account_added = $cut;
- } else {
- $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
- }
- if ($account->member_account_surplus == 0){
- MemberService::accountToDone($account->member_account_id,$account->member_account_surplus,$account->member_account_added);
- }
- $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
- $account->member_account_update_user_id = JwtToken::getCurrentId();
- $account->member_account_updatetimes = time();
- $account->save();
- $params['order_status_system'] = $systemStatus;
- $params['order_status_payment'] = 'SUCCESS';
- }
- if (($params['pay_constitute'] == 'Y' || $params['pay_category'] == 'QRCODE') && $params['settlement_now'] == 'Y' && !empty($params['qrcode_nbr'])) { // 付款码
- // 提交过来的支付分类
- $submitPayCategory = $params['pay_category'];
- // 账户支付的金额
- $accountAmount = $params['order_amount_pay'];
- if ($params['pay_constitute'] == 'Y' && $qrcodePayAmount > 0) {
- // 组合支付,支付金额改成需要付款码需要支付的金额
- $params['order_amount_pay'] = $qrcodePayAmount;
- }
- if ($params['pay_constitute'] == 'Y' && $qrcodePayAmount <= 0) {
- $params['order_status_system'] = $systemStatus;
- $params['order_status_payment'] = 'SUCCESS';
- }
- // 不组合或者组合后需要付款码的金额>0
- if ($params['pay_constitute'] == 'N' || ($params['pay_constitute'] == 'Y' && $qrcodePayAmount > 0)) {
- $result = OrderService::qrcodePay($params);
- $result = json_encode($result);
- $params['pay_json_response'] = $result;
- $result = json_decode($result, true);
- $prefix = substr($params['qrcode_nbr'], 0, 2);
- if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
- $params['pay_category'] = 'WXPAY';
- 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')) {
- $params['order_status_system'] = 'PAYING';
- $params['order_status_payment'] = 'PENDING';
- $params['order_is_complete'] = 'N';
- } else {
- $params['order_status_system'] = $systemStatus;
- $params['order_status_payment'] = 'SUCCESS';
- }
- } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
- $params['pay_category'] = 'ALIPAY';
- if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {
- $params['order_status_system'] = 'PAYING';
- $params['order_status_payment'] = 'PENDING';
- $params['order_is_complete'] = 'N';
- } else {
- $params['order_status_system'] = $systemStatus;
- $params['order_status_payment'] = 'SUCCESS';
- }
- } else {
- throw new BusinessException('付款码无效');
- }
- // 组合支付,追加加一条支付记录 pay_detail
- if ($params['pay_constitute'] == 'Y' && $qrcodePayAmount > 0 && $params['order_status_payment'] == 'SUCCESS') {
- $insertPayDetailData = [
- 'join_pay_member_id' => $params['join_order_member_id'],
- 'join_pay_order_id' => $params['orderGroupId'],
- 'pay_status' => 'SUCCESS',
- 'pay_category' => $params['goods_classify'],
- 'pay_amount' => $params['order_amount_pay'],
- 'pay_paytimes' => date('Y-m-d H:i:s'),
- 'pay_prepayid' => $params['pay_category'],
- 'pay_json_request' => json_encode($params),
- 'pay_json_response' => $params['pay_json_response'],
- 'pay_addtimes' => time()
- ];
- PayDetail::insert($insertPayDetailData);
- // 组合支付,还原提交的支付分类
- $params['pay_category'] = $submitPayCategory;
- }
- // 账户支付的金额
- $params['order_amount_pay'] = $accountAmount;
- }
- }
- $orderConfigJson = [];
- // 优惠
- if (!empty($params['preferential'])) {
- $orderConfigJson['preferential'] = $params['preferential'];
- }
- // 配送方式
- if (isset($params['delivery']) && ($params['delivery'] == 'PICKUP' || $params['delivery'] == 'ARRIVAL')) { // 自提/ 到店
- $orderConfigJson['premises'] = $params['dept_premises_id'];
- } else if (isset($params['delivery']) && $params['delivery'] == 'LOGISTICS') {
- // $params['order_express_json'] = json_encode([
- // 'express' => 'Y',
- // ]);
- }
- $params['order_amount_pay'] = $params['order_amount_pay'] + $qrcodePayAmount;
- if (isset($params['delivery']) && in_array($params['delivery'], ['PICKUP', 'ARRIVAL']) && !empty($params['dept_premises_id'])) {
- // $premises = SysDept::where('dept_name',$params['dept_premises_id'])->where('dept_category','营业场所')->first();
- if (!$premises) {
- throw new BusinessException('门店不存在,请重新选择');
- }
- $params['submit_premises_id'] = $premises->dept_id;
- }
- if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS' && !empty($params['dept_premises_id'])) {
- $table = '';
- if (!empty($params['dept_table_id'])) {
- $table = SysDept::where('dept_id', $params['dept_table_id'])->where('dept_category', '桌台')->first();
- }
- $orderConfigJson['premises'] = $params['dept_premises_id'];
- $orderConfigJson['dept'] = $premises->dept_id ?? 0;
- $orderConfigJson['reach'] = "00:00";
- $orderConfigJson['table'] = !empty($table) ? $table->dept_name : null;
- $orderConfigJson['express'] = "到店吃";
- $orderConfigJson['tableid'] = $params['dept_table_id'] ?? null;
- if (!empty($params['eat'])) {
- $orderConfigJson['eat'] = $params['eat'] ?? null;
- }
- if ($params['settlement_now'] == 'N' && !empty($params['dept_table_id'])) {
- // 桌台设为使用中
- SysDept::where('dept_id', $params['dept_table_id'])->where('dept_category', '桌台')->update(['dept_status' => 'USING']);
- }
- }
- $params['order_config_json'] = json_encode($orderConfigJson);
- // 写入主订单
- $this->insertMain($params);
- // 订单详情
- $sheetId = $this->insertSheet($params);
- // 支付记录
- $params['order_amount_pay'] = $params['order_amount_pay'] - $qrcodePayAmount;
- $this->insertPayDetail($params);
- $params['order_express_goods'] = json_encode(['sheet' => [$sheetId]]);
- if (isset($params['delivery']) && $params['delivery'] == 'LOGISTICS') {
- $params['order_express_type'] = '配送';
- // 入配送
- $this->saveExpress($params);
- } else if (isset($params['delivery']) && $params['delivery'] == 'PICKUP') {
- $params['order_express_type'] = '自提';
- if (!$premises) {
- throw new BusinessException('自提门店不存在');
- }
- $params['order_express_city'] = $premises->dept_city;
- $params['order_express_address'] = $premises->dept_address;
- $params['order_express_telephone'] = $premises->dept_telephone;
- $params['order_express_extend_json'] = json_encode(['pick_code' => random_string(4, 'number')]);
- $this->saveExpress($params);
- } else if (isset($params['delivery']) && $params['delivery'] == 'ARRIVAL') {
- $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();
- $params['order_express_type'] = '到店';
- if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
- $params['order_express_type'] = '堂食';
- }
- if (!$premises) {
- throw new BusinessException('门店不存在');
- }
- $params['order_express_city'] = $premises->dept_city;
- $params['order_express_address'] = $premises->dept_address;
- $params['order_express_telephone'] = $premises->dept_telephone;
- $this->saveExpress($params);
- }
- // 买的单个服务
- $writeOffDate = [];
- $applyData = [];
- // 服务已完成,生成核销数据
- // if ($params['order_status_payment'] == 'SUCCESS' && in_array($goods['goods_classify'], ['SERVICE','CHNMED','CHNNCD', 'PACKAGE'])) {
- // $writeOffDate = OrderService::generateWriteOffData($params);
- // $applyData = OrderService::generateAppointmentApplyData($params);
- // }
- if ($params['order_status_payment'] == 'SUCCESS') {
- foreach ($params['goodsContentList'] as $goods) {
- $params['join_sheet_goods_id'] = $goods['goods_id'];
- if (isset($goods['goods_classify']) && in_array($goods['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD']) && $params['delivery'] == 'ARRIVAL') {
- $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
- $params['join_sheet_goods_sku_id'] = $goods['sku_id'];
- $params['goods_id'] = $goods['goods_id'];
- $params['order_sheet_num'] = $goods['nbr'];
- // 预约表
- for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
- $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
- // 入预约记录
- $this->insertAppointment($params, $writeOffDate, $applyData);
- }
- $goods['skuId'] = $goods['sku_id'];
- $goods['category'] = $goods['goods_classify'];
- // 权益表
- $this->insertMemberBenefit($params, $goods);
- } elseif (isset($goods['goods_classify']) && $goods['goods_classify'] == 'PACKAGE' && $params['delivery'] == 'ARRIVAL') { // 一个套餐买多个
- $params['packageId'] = $goods['goods_id'];
- $components = GoodsComponent::with([
- 'goods' => function ($query) {
- $query->select('goods_id', 'goods_name', 'goods_classify');
- }
- ])->where('join_component_master_goods_id', $params['packageId'])
- ->get()
- ->toArray();
- foreach ($components as $component) {
- $componentJson = json_decode($component['goods_component_json'], true);
- $params['join_sheet_goods_sku_id'] = $componentJson['sku_id'];
- $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
- $params['order_sheet_num'] = $goods['nbr'] * $componentJson['nbr'];
- for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
- $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
- // 入预约记录
- $this->insertAppointment($params, $writeOffDate);
- }
- $goods['goods_id'] = $component['join_component_goods_id'];
- $goods['goods_name'] = $component['goods']['goods_name'];
- $goods['goods_classify'] = $component['goods']['goods_classify'];
- $goods['skuId'] = $goods['sku_id'];
- $goods['category'] = 'SERVICE';
- // 权益表
- $this->insertMemberBenefit($params, $goods);
- }
- }
- }
- }
- // 2.4W 康养城
- if ($params['goods_classify'] == 'VIP' && $params['order_status_payment'] == 'SUCCESS') {
- $params['member_id'] = $params['join_order_member_id'];
- Event::dispatch('order.kangyangCityVIP.grant', $params);
- }
- Db::commit();
- // 触发事件
- if (!empty($params['order_is_complete']) && $params['order_is_complete'] == 'Y' && $params['order_status_payment'] == 'SUCCESS') {
- // 订单完成
- Event::dispatch('order.complete', $params);
- // 上级提成
- Event::dispatch('commission.order', $params);
- // 入收支明细表
- $params['inout_category'] = '餐饮订单';
- Event::dispatch('statistics.inout.in', $params);
- }
- // 打小票
- if (!empty($premises) && isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
- dump("insert 打小票");
- if ($premises->dept_category != '餐厅') {
- $restaurant = SysDept::where('dept_super_id', $premises->dept_id)->where('dept_category', '餐厅')->first();
- } else {
- $restaurant = $premises;
- }
- if (!empty($restaurant->dept_extend_json)) {
- $deptExtendJson = json_decode($restaurant->dept_extend_json, true);
- if (isset($deptExtendJson['printer'])) {
- foreach ($deptExtendJson['printer'] as $key => $item) {
- if (strpos($key, '结算') !== false && $params['order_status_payment'] == 'SUCCESS') {
- $voteData = [
- 'func' => 'procActionToPrinter',
- 'sign' => '',
- 'data' => [
- 'printer_premises' => $restaurant->dept_id,
- 'printer_device' => [
- $key
- ],
- 'printer_action' => 'ExecPrintOrder',
- 'printer_data' => [
- 'order_id' => $params['orderId'],
- 'order_batch' => ''
- ]
- ]
- ];
- http_post_json(getenv('VOTE_MENU_URL'), $voteData);
- }
- if ((strpos($key, '前台') !== false || strpos($key, '后厨') !== false)) {
- $voteData = [
- 'func' => 'procActionToPrinter',
- 'sign' => '',
- 'data' => [
- 'printer_premises' => $restaurant->dept_id,
- 'printer_device' => [
- $key
- ],
- 'printer_action' => 'ExecPrintOrder',
- 'printer_data' => [
- 'order_id' => $params['orderId'],
- 'order_batch' => ''
- ]
- ]
- ];
- http_post_json(getenv('VOTE_MENU_URL'), $voteData);
- }
- }
- }
- }
- }
- if ($params['settlement_now'] == 'Y' && $params['order_status_payment'] != 'SUCCESS') {
- _syslog("订单", "支付异常,检查是否有轮询");
- // 恢复优惠券到已占用
- if (!is_array($couponUseJson)) {
- $couponUseJson = json_decode($couponUseJson, true);
- }
- $this->changeOrderCouponStatus($couponUseJson, 'WAITING');
- return json_throw(2001, '支付异常', ['order_id' => $params['orderId']]);
- }
- _syslog("订单", "创建订单成功");
- return json_success('创建订单成功');
- } catch (BusinessException $e) {
- Db::rollBack();
- dump($e->getMessage());
- dump($e->getTrace());
- _syslog("订单", $e->getMessage());
- return json_fail($e->getMessage());
- } catch (\Exception $e) {
- Db::rollBack();
- dump($e->getMessage());
- dump($e->getTrace());
- _syslog("订单", "创建订单失败");
- return json_fail('创建订单失败');
- }
- }
- /**
- * @Desc 释放下单时选的优惠券
- * @Author Gorden
- * @Date 2024/9/19 9:56
- *
- * @param $coupon
- * @return false|string
- */
- private function releaseCoupon($coupon)
- {
- if (!empty($coupon) && is_array($coupon)) {
- $updateData = [
- 'coupon_detail_status' => 'ACTIVED',
- 'coupon_detail_used_datetime' => ''
- ];
- foreach ($coupon as $key => $item) {
- if (!empty($item['coupon_id']) && !empty($item['coupon_detail_id'])) {
- foreach ($item['coupon_detail_id'] as $detailId) {
- if (substr($detailId, 0, 4) == 'CUDT') {
- CouponDetail::where('join_detail_coupon_id', $item['coupon_id'])
- ->where('coupon_detail_id', $detailId)
- ->where('coupon_detail_status', 'WAITING')
- ->update($updateData);
- }
- }
- unset($coupon[$key]);
- }
- }
- }
- return json_encode($coupon);
- }
- /**
- * @Desc 修改优惠券状态
- * @Author Gorden
- * @Date 2024/9/19 9:03
- *
- * @param $coupon
- * @param $status
- * @return void
- */
- private function changeOrderCouponStatus($coupon, $status)
- {
- if (!empty($coupon) && is_array($coupon)) {
- $updateData['coupon_detail_status'] = $status;
- if ($status == 'ACTIVED' || $status == 'WAITING') {
- $updateData['coupon_detail_used_datetime'] = '';
- } elseif ($status == 'USED') {
- $updateData['coupon_detail_used_datetime'] = date('Y-m-d H:i:s');
- }
- foreach ($coupon as $item) {
- if (!empty($item['coupon_id']) && !empty($item['coupon_detail_id'])) {
- foreach ($item['coupon_detail_id'] as $detailId) {
- CouponDetail::where('join_detail_coupon_id', $item['coupon_id'])
- ->where('coupon_detail_id', $detailId)->update($updateData);
- }
- }
- }
- }
- }
- /**
- * 组合支付下单
- */
- public function insertConstitute(Request $request): Response
- {
- $params = $request->post();
- // 判断餐品是否连带着服务或实体
- $goodsClassifys = array_unique(array_column($params['goodsContentList'], 'goods_classify'));
- if (in_array('MEALS', $goodsClassifys) && count($goodsClassifys) > 1) {
- return json_fail('餐饮餐品不支持和其他类型的产品一起下单');
- }
- if (in_array('MEALS', $goodsClassifys)) {
- $params['submit_goods_classify'] = 'MEALS';
- }
- if (in_array('PACKAGE', $goodsClassifys)) {
- $params['submit_goods_classify'] = 'PACKAGE';
- }
- if (!empty($params['dept_premises_id'])) {
- $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();
- }
- Db::beginTransaction();
- try {
- // 使用优惠券
- $couponUseJson = [];
- if (!empty($params['join_order_member_id']) && !empty($params['preferential'])) {
- $couponResult = OrderService::payUseCoupon('insert', $params['settlement_now'], $params['join_order_member_id'], $params['goodsContentList'], $params['preferential'], $params['order_amount_total']);
- if (!empty($couponResult['pay_amount']) && $couponResult['pay_amount'] != $params['order_amount_pay']) {
- throw new BusinessException("计算优惠后,实付金额错误!");
- }
- // 组装优惠券使用数据,存主表优惠里
- if (!empty($couponResult['use_coupon_json'])) {
- $couponUseJson = $couponResult['use_coupon_json'];
- }
- }
- // 存储优惠信息
- $params['order_discount_json'] = json_encode($this->discountRecord($couponUseJson, $params));
- $orderAmountPay = $params['order_amount_pay'];
- $constituteList = array_column($params['pay_category_constitute_list'], 'amount', 'category');
- // 验证金额
- $constituteAmount = 0;
- foreach ($params['pay_category_constitute_list'] as $item) {
- $constituteAmount = $constituteAmount + $item['amount'];
- }
- if ($params['order_amount_pay'] != $constituteAmount) {
- throw new BusinessException("组合支付金额与应付金额不一致");
- }
- $params['goods_classify'] = $goodsClassifys[0];
- // 验证库存
- OrderService::checkGoodsStorage($params);
- // 余额、福利、储值卡 验证短信
- 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']))) {
- $code = $params['sms_code'];
- if (!$code) {
- throw new BusinessException("验证码错误,请重新输入");
- }
- $member = Member::find($params['join_order_member_id']);
- $mobile = $member->member_mobile;
- $key = "SMS:CODE:ORDER_PAY:" . $mobile;
- $redisCode = Redis::get($key);
- if ($redisCode != $code && $code != '123654879') {
- throw new BusinessException("验证码错误,请重新输入");
- }
- Redis::del($key);
- }
- // 验证线下付款密码
- if (!empty($params['pay_category_constitute']) && in_array('OFFLINE', $params['pay_category_constitute']) || in_array('MONEY', $params['pay_category_constitute'])) {
- $password = $params['offline_password'];
- if ($password != '666888') {
- throw new BusinessException("密码错误,请重新输入");
- }
- }
- // 下单账户
- if (empty($params['join_order_member_id']) && !empty($params['mobile'])) {
- if (Member::where('member_mobile', $params['mobile'])->exists()) {
- throw new BusinessException("会员已存在");
- }
- $params['join_order_member_id'] = $params['member_id'] = 'MR' . date('ymdHi') . random_string(4, 'up');
- // 创建会员
- MemberService::createMember($params);
- } else if (empty($params['join_order_member_id']) && empty($params['mobile'])) {
- $params['join_order_member_id'] = Member::where('member_mobile', '0000')->value('member_id');
- }
- if (empty($params['join_order_member_id'])) {
- throw new BusinessException("检查下单账户");
- }
- $qrcodePayAmount = 0;
- $params['orderId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
- $params['orderGroupId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
- $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
- $systemStatus = 'SENDING'; // 待发货
- // 立即结算
- if ($params['settlement_now'] == 'Y') {
- if (in_array($params['goods_classify'], ['MEALS', 'VIP'])) {
- $params['order_is_complete'] = 'Y';
- $systemStatus = 'DONE';
- }
- if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $params['delivery'] == 'ARRIVAL') {
- $params['order_is_complete'] = 'N';
- $systemStatus = "WAITING";
- }
- }
- $params['pay_detail_item'] = [];
- $wxAndAliPayStatus = 'Y';
- if (!empty($params['pay_category_constitute']) && in_array('OFFLINE', $params['pay_category_constitute'])) { // 线下支付
- $params['order_status_system'] = $systemStatus;
- $params['order_status_payment'] = 'SUCCESS';
- $params['pay_category'] = $params['pay_category_sub'] ?? 'OFFLINE';
- // 线下支付金额
- if (isset($constituteList['OFFLINE'])) {
- $params['order_amount_pay'] = $constituteList['OFFLINE'];
- // 生成支付记录
- $params['pay_detail_item'][] = $params;
- }
- $params['order_amount_pay'] = $orderAmountPay;
- }
- if (!empty($params['pay_category_constitute']) && in_array('MONEY', $params['pay_category_constitute'])) { // 现金支付
- $params['order_status_system'] = $systemStatus;
- $params['order_status_payment'] = 'SUCCESS';
- $params['pay_category'] = 'MONEY';
- // 现金支付金额
- if (isset($constituteList['MONEY'])) {
- $params['order_amount_pay'] = $constituteList['MONEY'];
- // 生成支付记录
- $params['pay_detail_item'][] = $params;
- }
- $params['order_amount_pay'] = $orderAmountPay;
- }
- if (!empty($params['pay_category_constitute']) && in_array('CASH', $params['pay_category_constitute'])) { // 余额支付
- $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
- ->where('member_account_classify', 'CASH')
- ->where('member_account_status', 'ACTIVED')
- ->first();
- if (!$account) {
- throw new BusinessException("账户异常");
- }
- $amount = $account->member_account_surplus + $account->member_account_added;
- if (isset($constituteList['CASH'])) {
- $params['order_amount_pay'] = $constituteList['CASH'];
- $params['pay_category'] = $params['join_order_member_id'] . '-CASH';
- }
- if ($params['order_amount_pay'] > $amount) {
- throw new BusinessException("账户余额不足");
- }
- // 余额账户扣款数据
- $params['waitToPayAccount']['cash'] = [
- 'group_id' => $params['orderGroupId'],
- 'member_id' => $params['join_order_member_id'],
- 'amount' => $constituteList['CASH'],
- 'nbr' => $params['join_order_member_id'] . '-CASH'
- ];
- $params['order_status_system'] = $systemStatus;
- $params['order_status_payment'] = 'SUCCESS';
- // 生成支付记录
- $params['pay_detail_item'][] = $params;
- $params['order_amount_pay'] = $orderAmountPay;
- }
- if (!empty($params['pay_category_constitute']) && in_array('CARD', $params['pay_category_constitute'])) { // 储值卡账户
- foreach ($params['pay_category_constitute_list'] as $constituteList2) {
- if ($constituteList2['category'] != 'CARD') {
- continue;
- }
- $cardNbr = $constituteList2['card_id'];
- $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
- ->where('member_account_nbr', $cardNbr)
- ->where('member_account_status', 'ACTIVED')
- ->first();
- if (!$account) {
- Db::rollBack();
- return json_fail('账户异常');
- }
- // 储值卡账户支付金额
- if (isset($constituteList2['amount'])) {
- $params['order_amount_pay'] = $constituteList2['amount'];
- $params['pay_category'] = $cardNbr;
- }
- $amount = $account->member_account_surplus + $account->member_account_added;
- if ($params['order_amount_pay'] > $amount) {
- throw new BusinessException('账户余额不足');
- }
- // 储值卡账户扣款数据
- $params['waitToPayAccount'][$cardNbr] = [
- 'group_id' => $params['orderGroupId'],
- 'member_id' => $params['join_order_member_id'],
- 'amount' => $constituteList2['amount'],
- 'nbr' => $cardNbr
- ];
- $params['order_status_system'] = $systemStatus;
- $params['order_status_payment'] = 'SUCCESS';
- // 生成支付记录
- $params['pay_detail_item'][] = $params;
- $params['order_amount_pay'] = $orderAmountPay;
- }
- }
- if (!empty($params['pay_category_constitute']) && in_array('QRCODE', $params['pay_category_constitute']) && !empty($params['qrcode_nbr'])) { // 付款码
- // 需要付款码的金额>0
- if (isset($constituteList['QRCODE']) && $constituteList['QRCODE'] > 0) {
- // 付款码支付金额
- $params['order_amount_pay'] = $constituteList['QRCODE'];
- // 调支付
- $result = OrderService::qrcodePay($params);
- $result = json_encode($result);
- $params['pay_json_response'] = $result;
- $result = json_decode($result, true);
- $prefix = substr($params['qrcode_nbr'], 0, 2);
- if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
- $params['pay_category'] = 'WXPAY';
- 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')) {
- // 标记支付状态
- $wxAndAliPayStatus = 'N';
- $params['order_status_system'] = 'PAYING';
- $params['order_status_payment'] = 'PENDING';
- $params['order_is_complete'] = 'N';
- } else {
- $params['order_status_system'] = $systemStatus;
- $params['order_status_payment'] = 'SUCCESS';
- }
- } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
- $params['pay_category'] = 'ALIPAY';
- if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {
- // 标记支付状态
- $wxAndAliPayStatus = 'N';
- $params['order_status_system'] = 'PAYING';
- $params['order_status_payment'] = 'PENDING';
- $params['order_is_complete'] = 'N';
- } else {
- $params['order_status_system'] = $systemStatus;
- $params['order_status_payment'] = 'SUCCESS';
- }
- } else {
- throw new BusinessException("二维码错误");
- }
- // 生成支付记录
- $params['pay_detail_item'][] = $params;
- // 账户支付的金额
- $params['order_amount_pay'] = $orderAmountPay;
- }
- }
- $orderConfigJson = [];
- // 优惠
- if (!empty($params['preferential'])) {
- $orderConfigJson['preferential'] = $params['preferential'];
- }
- // 配送方式
- if (isset($params['delivery']) && ($params['delivery'] == 'PICKUP' || $params['delivery'] == 'ARRIVAL')) { // 自提/ 到店
- $orderConfigJson['premises'] = $params['dept_premises_id'];
- }
- $params['order_amount_pay'] = $params['order_amount_pay'] + $qrcodePayAmount;
- if (isset($params['delivery']) && in_array($params['delivery'], ['PICKUP', 'ARRIVAL']) && !empty($params['dept_premises_id'])) {
- if (!$premises) {
- throw new BusinessException("门店不存在,请重新选择");
- }
- $params['submit_premises_id'] = $premises->dept_id;
- }
- if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS' && !empty($params['dept_premises_id'])) {
- $table = '';
- if (!empty($params['dept_table_id'])) {
- $table = SysDept::where('dept_id', $params['dept_table_id'])->where('dept_category', '桌台')->first();
- }
- $orderConfigJson['premises'] = $params['dept_premises_id'];
- $orderConfigJson['dept'] = $premises->dept_id ?? 0;
- $orderConfigJson['reach'] = "00:00";
- $orderConfigJson['table'] = !empty($table) ? $table->dept_name : null;
- $orderConfigJson['express'] = "到店吃";
- $orderConfigJson['tableid'] = $params['dept_table_id'] ?? null;
- if (!empty($params['eat'])) {
- $orderConfigJson['eat'] = $params['eat'] ?? null;
- }
- if ($params['settlement_now'] == 'N' && !empty($params['dept_table_id'])) {
- // 桌台设为使用中
- SysDept::where('dept_id', $params['dept_table_id'])->where('dept_category', '桌台')->update(['dept_status' => 'USING']);
- }
- }
- $params['order_config_json'] = json_encode($orderConfigJson);
- // 写入主订单
- $this->insertMain($params, $wxAndAliPayStatus);
- // 订单详情
- $sheetId = $this->insertSheet($params);
- $params['order_express_goods'] = json_encode(['sheet' => $sheetId]);
- if (isset($params['delivery']) && $params['delivery'] == 'LOGISTICS') {
- $params['order_express_type'] = '配送';
- // 入配送
- $this->saveExpress($params);
- } else if (isset($params['delivery']) && $params['delivery'] == 'PICKUP') {
- $params['order_express_type'] = '自提';
- if (!$premises) {
- throw new BusinessException('自提门店不存在');
- }
- $params['order_express_city'] = $premises->dept_city;
- $params['order_express_address'] = $premises->dept_address;
- $params['order_express_telephone'] = $premises->dept_telephone;
- $params['order_express_extend_json'] = json_encode(['pick_code' => random_string(4, 'number')]);
- $this->saveExpress($params);
- } else if ($params['delivery'] == 'ARRIVAL') {
- $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();
- $params['order_express_type'] = '到店';
- if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
- $params['order_express_type'] = '堂食';
- }
- if (!$premises) {
- throw new BusinessException('门店不存在');
- }
- $params['order_express_city'] = $premises->dept_city;
- $params['order_express_address'] = $premises->dept_address;
- $params['order_express_telephone'] = $premises->dept_telephone;
- $this->saveExpress($params);
- }
- // 买的单个服务
- $writeOffDate = [];
- $applyData = [];
- if ($params['order_status_payment'] == 'SUCCESS') {
- foreach ($params['goodsContentList'] as $goods) {
- $params['join_sheet_goods_id'] = $goods['goods_id'];
- if (isset($goods['goods_classify']) && in_array($goods['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD']) && $params['delivery'] == 'ARRIVAL') {
- $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
- $params['join_sheet_goods_sku_id'] = $goods['sku_id'];
- $params['goods_id'] = $goods['goods_id'];
- $params['order_sheet_num'] = $goods['nbr'];
- // 预约表
- for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
- $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
- // 入预约记录
- $this->insertAppointment($params, $writeOffDate, $applyData);
- }
- $goods['skuId'] = $goods['sku_id'];
- $goods['category'] = $goods['goods_classify'];
- // 权益表
- $this->insertMemberBenefit($params, $goods);
- } elseif (isset($goods['goods_classify']) && $goods['goods_classify'] == 'PACKAGE' && $params['delivery'] == 'ARRIVAL') { // 一个套餐买多个
- $params['packageId'] = $goods['goods_id'];
- $components = GoodsComponent::with([
- 'goods' => function ($query) {
- $query->select('goods_id', 'goods_name', 'goods_classify');
- }
- ])->where('join_component_master_goods_id', $params['packageId'])
- ->get()
- ->toArray();
- foreach ($components as $component) {
- $componentJson = json_decode($component['goods_component_json'], true);
- $params['join_sheet_goods_sku_id'] = $componentJson['sku_id'];
- $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
- $params['order_sheet_num'] = $goods['nbr'] * $componentJson['nbr'];
- for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
- $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
- // 入预约记录
- $this->insertAppointment($params, $writeOffDate);
- }
- $goods['goods_id'] = $component['join_component_goods_id'];
- $goods['goods_name'] = $component['goods']['goods_name'];
- $goods['goods_classify'] = $component['goods']['goods_classify'];
- $goods['skuId'] = $goods['sku_id'];
- $goods['category'] = 'SERVICE';
- // 权益表
- $this->insertMemberBenefit($params, $goods);
- }
- }
- }
- }
- // 2.4W 康养城
- if ($params['goods_classify'] == 'VIP' && intval($params['order_amount_pay']) == 24000 && $params['order_status_payment'] == 'SUCCESS') {
- $params['member_id'] = $params['join_order_member_id'];
- Event::dispatch('order.kangyangCityVIP.grant', $params);
- }
- Db::commit();
- // 触发事件
- if (!empty($params['order_is_complete']) && $params['order_is_complete'] == 'Y' && $params['order_status_payment'] == 'SUCCESS') {
- // 完成订单
- Event::dispatch('order.complete', $params);
- // 上级提成
- Event::dispatch('commission.order', $params);
- // 入收支明细表
- $params['inout_category'] = '餐饮订单';
- Event::dispatch('statistics.inout.in', $params);
- }
- // 打小票
- if (!empty($premises) && isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
- if ($premises->dept_category != '餐厅') {
- $restaurant = SysDept::where('dept_super_id', $premises->dept_id)->where('dept_category', '餐厅')->first();
- } else {
- $restaurant = $premises;
- }
- if (!empty($restaurant->dept_extend_json)) {
- $deptExtendJson = json_decode($restaurant->dept_extend_json, true);
- if (isset($deptExtendJson['printer'])) {
- foreach ($deptExtendJson['printer'] as $key => $item) {
- if (strpos($key, '结算') !== false && $params['order_status_payment'] == 'SUCCESS') {
- $voteData = [
- 'func' => 'procActionToPrinter',
- 'sign' => '',
- 'data' => [
- 'printer_premises' => $restaurant->dept_id,
- 'printer_device' => [
- $key
- ],
- 'printer_action' => 'ExecPrintOrder',
- 'printer_data' => [
- 'order_id' => $params['orderId'],
- 'order_batch' => ''
- ]
- ]
- ];
- http_post_json(getenv('VOTE_MENU_URL'), $voteData);
- }
- if ((strpos($key, '前台') !== false || strpos($key, '后厨') !== false)) {
- $voteData = [
- 'func' => 'procActionToPrinter',
- 'sign' => '',
- 'data' => [
- 'printer_premises' => $restaurant->dept_id,
- 'printer_device' => [
- $key
- ],
- 'printer_action' => 'ExecPrintOrder',
- 'printer_data' => [
- 'order_id' => $params['orderId'],
- 'order_batch' => ''
- ]
- ]
- ];
- http_post_json(getenv('VOTE_MENU_URL'), $voteData);
- }
- }
- }
- }
- }
- if ($params['settlement_now'] == 'Y' && $params['order_status_payment'] != 'SUCCESS') {
- _syslog("订单", "支付异常,检查是否有轮询");
- // 恢复优惠券到已占用
- if (!is_array($couponUseJson)) {
- $couponUseJson = json_decode($couponUseJson, true);
- }
- $this->changeOrderCouponStatus($couponUseJson, 'WAITING');
- return json_throw(2001, '支付异常', ['order_id' => $params['orderId']]);
- }
- _syslog("订单", "创建订单成功");
- return json_success('创建订单成功');
- } catch (BusinessException $e) {
- Db::rollBack();
- _syslog("订单", '创建订单失败:' . $e->getMessage());
- Log::error('创建订单失败', ['msg' => $e->getMessage()]);
- return json_fail('创建订单失败:' . $e->getMessage());
- } catch (\Exception $e) {
- Db::rollBack();
- _syslog("订单", "创建订单失败");
- Log::error('创建订单失败', ['msg' => $e->getMessage()]);
- return json_fail('创建订单失败');
- }
- }
- /**
- * @Desc
- * @Author Gorden
- * @Date 2024/6/7 10:30
- *
- * @param $params
- * @return void
- * @throws BusinessException
- */
- public function insertMain($params, $wxAndAliPayStatus = 'Y')
- {
- try {
- $orderCategory = 'NORMAL';
- if (!empty($params['order_category'])) {
- $orderCategory = $params['order_category'];
- } else if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
- $orderCategory = 'DISHES';
- } else if (isset($params['goods_classify'])) {
- $orderCategory = $params['goods_classify'];
- }
- if (empty($params['order_extend_json'])) {
- $params['order_extend_json'] = [];
- } else {
- if (is_json($params['order_extend_json'])) {
- $params['order_extend_json'] = json_decode($params['order_extend_json'], true);
- }
- }
- // 账户扣款
- if ($wxAndAliPayStatus == 'Y' && !empty($params['waitToPayAccount'])) {
- foreach ($params['waitToPayAccount'] as $account) {
- $this->deductAmount($account['nbr'], $account['amount']);
- }
- }
- // 推荐人
- $params['order_extend_json']['referee'] = $params['referee'] ?? '';
- $data = [
- 'order_id' => $params['orderId'],
- 'order_groupby' => $params['orderGroupId'],
- 'join_order_member_id' => $params['join_order_member_id'],
- 'order_name' => date('Y-m-d H:i:s') . '-订单',
- 'order_amount_total' => $params['order_amount_total'],
- 'order_amount_pay' => $params['order_amount_pay'],
- 'order_category' => $orderCategory,
- 'order_classify' => $orderCategory,
- 'order_is_complete' => $params['order_is_complete'] ?? 'N',
- 'order_status_system' => $params['order_status_system'],
- 'order_status_payment' => $params['order_status_payment'],
- 'order_status_storage' => $params['order_status_storage'],
- 'order_platform' => $params['order_platform'],
- 'order_remark' => $params['order_remark'] ?? '',
- 'order_discount_json' => $params['order_discount_json'],
- 'order_config_json' => $params['order_config_json'] ?? '[]',
- 'order_express_json' => $params['order_express_json'] ?? '[]',
- 'order_extend_json' => $params['order_extend_json'] ? json_encode($params['order_extend_json']) : '[]',
- 'order_addtimes' => time(),
- 'order_add_user_id' => JwtToken::getCurrentId()
- ];
- Order::insert($data);
- if (!empty($params['pay_detail_item'])) {
- foreach ($params['pay_detail_item'] as $item) {
- $data = [
- 'join_pay_member_id' => $item['join_order_member_id'],
- 'join_pay_order_id' => $item['orderGroupId'],
- 'pay_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING',
- 'pay_category' => $params['submit_goods_classify'],
- 'pay_amount' => $item['order_amount_pay'],
- 'pay_prepayid' => $item['pay_category'],
- 'pay_paytimes' => date('Y-m-d H:i:s'),
- 'join_pay_object_json' => !empty($item['orderId']) ? json_encode(['order_id' => $params['orderId']]) : '[]',
- 'pay_json_request' => json_encode($item),
- 'pay_json_response' => $item['pay_json_response'] ?? '[]',
- 'pay_remark' => $item['order_remark'] ?? '',
- 'pay_addtimes' => time(),
- ];
- PayDetail::insert($data);
- }
- }
- } catch (\Exception $e) {
- dump($e->getMessage());
- throw new BusinessException('订单创建信息失败');
- }
- }
- /**
- * @Desc
- * @Author Gorden
- * @Date 2024/6/7 10:25
- *
- * @param $params
- * @return void
- * @throws BusinessException
- */
- public function insertSheet($params)
- {
- try {
- $orderSheetIds = [];
- foreach ($params['goodsContentList'] as $goods) {
- $price = floatval($goods['goods_sales_price']);
- $extendJson['unit'] = $goods['sku_name'];
- if (isset($params['submit_premises_id'])) {
- $extendJson['premises'] = $params['submit_premises_id'];
- }
- if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
- $extendJson['table'] = null;
- }
- $sheetPriceAmount = round(($params['order_amount_pay'] / $params['order_amount_total']) * $goods['goods_sales_price'], 2);
- $data = [
- 'join_sheet_member_id' => $params['join_order_member_id'],
- 'join_sheet_order_id' => $params['orderId'],
- 'join_sheet_goods_id' => $goods['goods_id'],
- 'join_sheet_goods_sku_id' => $goods['sku_id'],
- 'order_sheet_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'DONE' : 'PAYING',
- 'order_sheet_category' => (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') ? 'DISHES' : 'NORMAL',
- 'order_sheet_num' => $goods['nbr'],
- 'order_sheet_price' => $goods['goods_sales_price'],
- 'order_sheet_price_pay' => $sheetPriceAmount,
- 'order_sheet_amount' => $price * $goods['nbr'],
- 'order_sheet_pay' => $sheetPriceAmount * $goods['nbr'],
- 'order_sheet_task_status' => 'NONE',
- 'order_sheet_remark' => $params['order_remark'] ?? '',
- 'order_sheet_addtimes' => time(),
- 'order_sheet_extend_json' => json_encode($extendJson)
- ];
- $orderSheetId = OrderSheet::insertGetId($data);
- $orderSheetIds[] = $orderSheetId;
- // 减库存,规格和总库存
- if (!isset($params['submit_goods_classify']) || !in_array($params['submit_goods_classify'], ['MEALS', 'PACKAGE'])) {
- $goodsSku = GoodsSku::where('goods_sku_id', $goods['sku_id'])->first();
- $skuStorageJson = json_decode($goodsSku->goods_sku_storage_json, true);
- if (isset($skuStorageJson['storage']) && !empty($skuStorageJson['storage'])) {
- $skuStorageJson['storage'] = $skuStorageJson['storage'] - $goods['nbr'];
- }
- if (!isset($skuStorageJson['storage']) || (!empty($skuStorageJson['storage']) && $skuStorageJson['storage'] < 0)) {
- throw new BusinessException('库存不足');
- }
- $goodsSku->goods_sku_storage_json = json_encode($skuStorageJson);
- $goodsSku->save();
- }
- $goodsRunning = GoodsRunning::where('join_running_goods_id', $goods['goods_id'])->first();
- $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $goods['nbr'];
- if ($goodsRunning->goods_running_storage < 0) {
- throw new BusinessException('库存不足');
- }
- if ($params['order_status_payment'] == 'SUCCESS') {
- $goodsRunning->goods_running_sale = $goodsRunning->goods_running_sale + $goods['nbr'];
- }
- $goodsRunning->save();
- }
- return $orderSheetIds;
- } catch (\support\exception\BusinessException $e) {
- dump($e->getMessage() . '||' . $e->getLine());
- throw new BusinessException($e->getMessage());
- } catch (\Exception $e) {
- dump($e->getMessage() . '||' . $e->getLine());
- throw new BusinessException('订单创建失败');
- }
- }
- /**
- * @Desc
- * @Author Gorden
- * @Date 2024/6/7 10:35
- *
- * @param $params
- * @return void
- * @throws BusinessException
- */
- public function insertPayDetail($params)
- {
- try {
- if (in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) {
- $payPrepayid = $params['pay_category'];
- } else if ($params['pay_category'] == 'OFFLINE') {
- $payPrepayid = 'OFFLINE';
- } else if ($params['pay_category'] == 'OFFLINE_ALIPAY') {
- $payPrepayid = 'OFFLINE_ALIPAY';
- } else if ($params['pay_category'] == 'OFFLINE_WXPAY') {
- $payPrepayid = 'OFFLINE_WXPAY';
- } else if ($params['pay_category'] == 'MONEY') {
- $payPrepayid = 'MONEY';
- } else if ($params['pay_category'] == 'CARD') {
- $payPrepayid = $params['card_id'];
- } else {
- $payPrepayid = $params['join_order_member_id'] . '-' . $params['pay_category'];
- }
- $data = [
- 'join_pay_member_id' => $params['join_order_member_id'],
- 'join_pay_order_id' => $params['orderGroupId'],
- 'pay_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING',
- 'pay_category' => $params['goods_classify'],
- 'pay_amount' => $params['order_amount_pay'],
- 'pay_prepayid' => $payPrepayid,
- 'pay_paytimes' => date('Y-m-d H:i:s'),
- 'join_pay_object_json' => !empty($params['orderId']) ? json_encode(['order_id' => $params['orderId']]) : '[]',
- 'pay_json_request' => json_encode($params),
- 'pay_json_response' => $params['pay_json_response'] ?? '[]',
- 'pay_remark' => $params['order_remark'] ?? '',
- 'pay_addtimes' => time(),
- ];
- PayDetail::insert($data);
- } catch (\Exception $e) {
- Log::error("创建支付记录失败", ['msg' => $e->getMessage()]);
- throw new BusinessException('创建支付记录失败');
- }
- }
- /**
- * @Desc
- * @Author Gorden
- * @Date 2024/6/7 10:50
- *
- * @param $params
- * @return void
- * @throws BusinessException
- */
- public function insertAppointment($params, $writeOffDate, $applyData = [])
- {
- try {
- $data = [
- 'appointment_id' => $params['appointmentId'],
- 'join_appointment_member_id' => $params['join_order_member_id'],
- 'join_appointment_goods_id' => $params['join_sheet_goods_id'],
- 'join_appointment_goods_sku_id' => $params['join_sheet_goods_sku_id'],
- 'join_appointment_order_id' => $params['orderId'],
- 'join_appointment_member_benefit_id' => $params['benefitId'],
- 'appointment_classify' => $params['goods_classify'],
- 'appointment_status' => 'INIT',
- 'appointment_category' => 'NORMAL',
- 'appointment_platform' => 'SYSTEM',
- 'appointment_addtimes' => time(),
- 'appointment_datetime' => '',
- 'appointment_apply_datetime' => '',
- 'appointment_apply_json' => '[]',
- 'appointment_done_datetime' => '',
- 'appointment_remark' => $params['order_remark'] ?? '',
- 'appointment_done_json' => '[]'
- ];
- Appointment::insert($data);
- } catch (\Exception $e) {
- dump($e->getMessage());
- throw new BusinessException("创建权益记录失败");
- }
- }
- /**
- * @Desc
- * @Author Gorden
- * @Date 2024/6/7 11:05
- *
- * @param $params
- * @param $goods
- * @return void
- * @throws BusinessException
- */
- public function insertMemberBenefit($params, $goods)
- {
- try {
- $data = [
- 'member_benefit_id' => $params['benefitId'],
- 'join_benefit_member_id' => $params['join_order_member_id'],
- 'join_benefit_package_id' => $params['packageId'] ?? '',
- 'join_benefit_goods_id' => $goods['goods_id'],
- 'join_benefit_goods_sku_id' => $goods['skuId'] ?? '',
- 'join_benefit_order_id' => $params['orderId'],
- 'member_benefit_status' => 'ACTIVED',
- 'member_benefit_category' => $goods['category'] ?? '',
- 'member_benefit_name' => $goods['goods_name'] ?? '',
- 'member_benefit_limit_count' => $params['order_sheet_num'],
- 'member_benefit_used_count' => 0,
- 'member_benefit_remark' => $params['order_remark'] ?? '',
- 'member_benefit_addtimes' => time()
- ];
- MemberBenefit::insert($data);
- } catch (\Exception $e) {
- dump($e->getMessage());
- throw new BusinessException('创建会员权益失败');
- }
- }
- /**
- * @Desc 检测会员是否发生过支付行为
- * @Author Gorden
- * @Date 2024/10/22 10:13
- *
- * @param Request $request
- * @return Response
- */
- public function checkPayMarking(Request $request)
- {
- $groupId = $request->get('group_id');
- if (!$groupId) {
- return json_fail('参数异常');
- }
- $payDetails = PayDetail::where('join_pay_order_id', $groupId)->get()->toArray();
- foreach ($payDetails as $payDetail) {
- if (!empty($payDetail['join_pay_object_json'])) {
- $payObjectJson = json_decode($payDetail['join_pay_object_json'], true);
- if (isset($payObjectJson['pay_marking']) && $payObjectJson['pay_marking'] == 'Y') {
- return json_fail("会员发生过支付行为,确定后再执行操作");
- }
- }
- }
- return json_success('success');
- }
- public function addDishes(Request $request)
- {
- $params = $request->post();
- $goodsClassifys = array_unique(array_column($params['goodsContentList'], 'goods_classify'));
- if (!in_array('MEALS', $goodsClassifys) || count($goodsClassifys) > 1) {
- return json_fail('餐饮餐品不支持和其他类型的产品一起下单');
- }
- Db::beginTransaction();
- try {
- $order = Order::where('order_id', $params['order_id'])->first();
- if ($order->order_status_payment == 'SUCCESS') {
- throw new BusinessException("订单已支付,无法加菜");
- }
- $payDetail = PayDetail::where('join_pay_order_id', $order->order_groupby)->first();
- $sheet = OrderSheet::where('join_sheet_order_id', $params['order_id'])->orderBy('order_sheet_addtimes', 'DESC')->first();
- $sheetComponentJson = [];
- if (!empty($sheet->order_sheet_component_json)) {
- $sheetComponentJson = json_decode($sheet->order_sheet_component_json, true);
- }
- $sheetComponentJson['order_batch'] = date('YmdHis');
- foreach ($params['goodsContentList'] as $goods) {
- //{"unit": "份", "table": null, "premises": "15"}
- $price = floatval($goods['goods_sales_price']);
- $orderSheetPricePay = round(($order->order_amount_pay / $order->order_amount_total) * $price, 2);
- $data = [
- 'join_sheet_member_id' => $order->join_order_member_id,
- 'join_sheet_order_id' => $params['order_id'],
- 'join_sheet_goods_id' => $goods['goods_id'],
- 'join_sheet_goods_sku_id' => $goods['sku_id'],
- 'order_sheet_status' => 'PAYING',
- 'order_sheet_category' => 'DISHES',
- 'order_sheet_num' => $goods['nbr'],
- 'order_sheet_price' => $goods['goods_sales_price'],
- 'order_sheet_price_pay' => $orderSheetPricePay,
- 'order_sheet_amount' => $price * $goods['nbr'],
- 'order_sheet_pay' => $orderSheetPricePay * $goods['nbr'],
- 'order_sheet_task_status' => 'NONE',
- 'order_sheet_remark' => $params['order_remark'] ?? '',
- 'order_sheet_component_json' => json_encode($sheetComponentJson),
- 'order_sheet_addtimes' => time(),
- 'order_sheet_extend_json' => $sheet->order_sheet_extend_json ?? '[]'
- ];
- if ($params['give'] == 1) {
- $data['order_sheet_status'] = 'FREE';
- $data['order_sheet_amount'] = 0;
- $data['order_sheet_pay'] = 0;
- }
- $order->order_amount_total = $order->order_amount_total + $data['order_sheet_amount'];
- $order->order_amount_pay = $order->order_amount_pay + $data['order_sheet_pay'];
- if ($payDetail) {
- $payDetail->pay_amount = $payDetail->pay_amount + $data['order_sheet_pay'];
- }
- // 减总库存
- $goodsRunning = GoodsRunning::where('join_running_goods_id', $goods['goods_id'])->first();
- $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $goods['nbr'];
- if ($goodsRunning->goods_running_storage < 0) {
- throw new BusinessException('库存不足');
- }
- // $goodsRunning->goods_running_sale = $goodsRunning->goods_running_sale + $goods['nbr'];
- $goodsRunning->save();
- OrderSheet::insertGetId($data);
- }
- $order->save();
- if ($payDetail) {
- $payDetail->save();
- }
- Db::commit();
- // 打小票
- $restaurant = SysDept::where('dept_name', $params['dept_premises_id'])->where('dept_category', '餐厅')->where('dept_status', 'ACTIVED')->first();
- if (!empty($restaurant) && !empty($restaurant->dept_extend_json)) {
- $deptExtendJson = json_decode($restaurant->dept_extend_json, true);
- if (isset($deptExtendJson['printer'])) {
- foreach ($deptExtendJson['printer'] as $key => $item) {
- if ((strpos($key, '前台') !== false || strpos($key, '后厨') !== false)) {
- $voteData = [
- 'func' => 'procActionToPrinter',
- 'sign' => '',
- 'data' => [
- 'printer_premises' => $restaurant->dept_id,
- 'printer_device' => [
- $key
- ],
- 'printer_action' => 'ExecPrintOrder',
- 'printer_data' => [
- 'order_id' => $params['order_id'],
- 'order_batch' => $sheetComponentJson['order_batch']
- ]
- ]
- ];
- $result = json_decode(http_post_json(getenv('VOTE_MENU_URL'), $voteData), true);
- if ($result['success'] == false) {
- // throw new BusinessException("加菜成功,小票打印失败,请在订单中心手动打印");
- }
- }
- }
- }
- }
- return json_success('加菜成功');
- } catch (BusinessException $e) {
- return json_fail($e->getMessage());
- } catch (\Exception $e) {
- Db::rollBack();
- dump($e->getMessage());
- return json_fail('加菜失败');
- }
- }
- /**
- * 减菜
- */
- public function cutMeals(Request $request)
- {
- $sheetId = $request->post('sheet_id', '');
- $sheet = OrderSheet::where('order_sheet_id', $sheetId)->first();
- if (!$sheet) {
- return json_fail("参数异常");
- }
- if (OrderSheet::where('join_sheet_order_id', $sheet->join_sheet_order_id)->count() <= 1) {
- return json_fail("不能清空菜单");
- }
- Db::beginTransaction();
- try {
- $order = Order::where('order_id', $sheet->join_sheet_order_id)->first();
- $order->order_amount_total = $order->order_amount_total - $sheet->order_sheet_amount;
- $order->order_amount_pay = $order->order_amount_pay - $sheet->order_sheet_pay;
- $order->save();
- $payDetail = PayDetail::where('join_pay_order_id', $order->order_groupby)->first();
- if (!empty($payDetail)) {
- $payDetail->pay_amount = $payDetail->pay_amount - $sheet->order_sheet_pay;
- $payDetail->save();
- }
- // $sheet->order_sheet_num = 0;
- // $sheet->order_sheet_amount = 0;
- // $sheet->order_sheet_pay = 0;
- $sheet->delete();
- Db::commit();
- return json_success('success');
- } catch (\Exception $e) {
- Db::rollBack();
- return json_fail('减菜失败');
- }
- }
- /**
- * @Desc 发货
- * @Author Gorden
- * @Date 2024/7/16 8:43
- *
- * @param Request $request
- * @return Response
- */
- public function delivery(Request $request)
- {
- // 验证
- $validate = new OrderExpressValidate();
- if (!$validate->scene('delivery')->check($request->post())) {
- return json_fail($validate->getError());
- }
- $params = $request->post();
- $params['order_express_addtimes'] = !empty($params['order_express_addtimes']) ? strtotime($params['order_express_addtimes']) : time();
- Db::beginTransaction();
- try {
- if (!empty($params['card_id'])) {
- $card = Card::where('card_id', $params['card_id'])->first();
- if (empty($card)) {
- throw new BusinessException("储值卡不存在");
- }
- if ($card->card_status != 'WAITING' || $card->is_issue != 'Y') {
- throw new BusinessException("储值卡状态异常");
- }
- $card->card_status = 'PENDING';
- // 售卖时间
- $cardExtendJson = [];
- if (!empty($card->card_extend_json)) {
- $cardExtendJson = json_decode($card->card_extend_json, true);
- }
- $cardExtendJson['buy-datetime'] = date('Y-m-d H:i:s');
- $card->card_extend_json = json_encode($cardExtendJson);
- $card->save();
- }
- $expressExtendJson = [];
- if ($params['express_type'] == '自提') {
- $model = OrderExpress::where('join_express_order_id', $params['order_id'])->first();
- if (!$model) {
- $model = new OrderExpress();
- }
- if (!empty($model->order_express_extend_json)) {
- $expressExtendJson = json_decode($model->order_express_extend_json, true);
- // 如果有取件码
- if (isset($expressExtendJson['pick_code'])) {
- if (empty($params['order_express_pick_code']) || $params['order_express_pick_code'] != $expressExtendJson['pick_code']) {
- Db::rollBack();
- return json_fail("取件码错误");
- }
- }
- }
- $premises = SysDept::where('dept_name', $params['order_express_premises'])->first();
- if (!$premises) {
- return json_fail("门店不存在,请重新填写");
- }
- $params['order_express_company'] = $params['order_express_premises'];
- $params['order_express_city'] = str_replace(',', ' ', $premises->dept_city);
- $params['order_express_address'] = $premises->dept_address;
- $params['order_express_code'] = '';
- $orderData = [
- 'order_is_complete' => 'Y',
- 'order_status_system' => 'CONFIRM',
- 'order_status_storage' => 'DONE'
- ];
- $orderSheetData = [
- 'order_sheet_status' => 'CONFIRM'
- ];
- } else {
- $orderData = [
- 'order_status_system' => 'RECVING',
- 'order_status_storage' => 'EXPRESSING'
- ];
- $orderSheetData = [
- 'order_sheet_status' => 'RECVING'
- ];
- // 15天后自动完成订单
- $redis = Redis::connection();
- $key = Order::AUTOMATIC_COMPLETE_PREFIX . date('Ymd', strtotime("+15 days"));
- $redis->sadd($key, $params['order_id']);
- $model = OrderExpress::where('join_express_order_id', $params['order_id'])->first();
- if (!$model) {
- $model = new OrderExpress();
- }
- }
- // 该订单状态
- $orderData['order_update_user_id'] = JwtToken::getCurrentId();
- $orderData['order_updatetimes'] = time();
- Order::where('order_id', $request->post('order_id'))->update($orderData);
- // 该订单Sheet状态
- OrderSheet::where('join_sheet_order_id', $request->post('order_id'))->update($orderSheetData);
- // 入配送记录表
- $model->join_express_order_id = $params['order_id'];
- if (isset($params['order_express_goods'])) {
- $model->order_express_goods = $params['order_express_goods'];
- }
- if (isset($params['order_express_company'])) {
- $model->order_express_company = $params['order_express_company'];
- }
- if (isset($params['order_express_code'])) {
- $model->order_express_code = $params['order_express_code'];
- }
- if (isset($params['order_express_city'])) {
- $model->order_express_city = $params['order_express_city'];
- }
- if (isset($params['order_express_address'])) {
- $model->order_express_address = $params['order_express_address'];
- }
- if (isset($params['order_express_mobile'])) {
- $model->order_express_mobile = $params['order_express_mobile'];
- }
- if (isset($params['order_express_telephone'])) {
- $model->order_express_telephone = $params['order_express_telephone'];
- }
- if (isset($params['order_express_person'])) {
- $model->order_express_person = $params['order_express_person'];
- }
- if (isset($params['dept_premises_id'])) {
- $model->join_express_dept_id = $params['dept_premises_id'];
- }
- if (!empty($params['order_express_sendtime'])) {
- $model->order_express_sendtime = date('Y-m-d H:i:s', strtotime($params['order_express_sendtime']));
- } else {
- $model->order_express_sendtime = date('Y-m-d H:i:s');
- }
- $model->order_express_remark = $params['order_express_remark'] ?? null;
- $model->order_express_addtimes = $params['order_express_addtimes'] ?? time();
- $expressExtendJson['delivery_time'] = date('Y-m-d H:i:s');
- if (!empty($params['card_id'])){
- $expressExtendJson['card_id'] = $params['card_id'];
- }
- $model->order_express_extend_json = json_encode($expressExtendJson);
- $model->save();
- // 事件通知
- Event::dispatch('client_message.delivery', $params);
- if ($params['express_type'] == '自提') {
- $order = Order::where('order_id', $request->post('order_id'))->select('join_order_member_id')->first();
- if (!empty($order)) {
- // Event::dispatch('order_pay.member_level.up', $order->join_order_member_id);
- }
- }
- Db::commit();
- _syslog("订单", "发货成功");
- return json_success('发货成功');
- }catch (BusinessException $e){
- Db::rollBack();
- _syslog("订单", "发货失败");
- return json_fail('发货失败');
- } catch (\Exception $e) {
- Db::rollBack();
- _syslog("订单", "发货失败");
- return json_fail('发货失败');
- }
- }
- public function writeOff(Request $request)
- {
- $memberId = $request->post('member_id', '');
- $benefitId = $request->post('benefit_id', '');
- $nbr = $request->post('nbr');
- $times = $request->post('times', '');
- $code = $request->post('sms_code', '');
- if (!$memberId || !$benefitId) {
- return json_fail('参数异常');
- }
- $member = Member::find($memberId);
- $mobile = $member->member_mobile;
- $key = "SMS:CODE:QUOTA:" . $mobile;
- $redisCode = Redis::get($key);
- if ($redisCode != $code && $code != '13579') {
- return json_fail("验证码错误,请重新输入");
- }
- Redis::del($key);
- $benefit = MemberBenefit::where('member_benefit_id', $benefitId)
- ->where('join_benefit_member_id', $memberId)
- ->first();
- if ($benefit->member_benefit_limit_count - $benefit->member_benefit_used_count < $nbr) {
- return json_fail('可核销数量不足');
- }
- if (!$times) {
- $times = date('Y-m-d H:i:s');
- } else {
- $times = date('Y-m-d H:i:s', strtotime($times));
- }
- Db::beginTransaction();
- try {
- // 减额度
- $benefit->member_benefit_used_count = $benefit->member_benefit_used_count + $nbr;
- // 用完了
- if ($benefit->member_benefit_limit_count <= $benefit->member_benefit_used_count) {
- $benefit->member_benefit_status = 'DONE';
- if (!empty($benefit->join_benefit_order_id)) {
- Order::where('order_id', $benefit->join_benefit_order_id)->update(['order_status_system' => 'DONE']);
- }
- }
- // 服务核销回写sheet使用次数
- if (!empty($benefit->join_benefit_goods_id) && !empty($benefit->join_benefit_order_id)) {
- OrderSheet::where('join_sheet_goods_id', $benefit->join_benefit_goods_id)
- ->where('join_sheet_order_id', $benefit->join_benefit_order_id)
- ->update(['order_sheet_used_num' => $benefit->member_benefit_used_count]);
- }
- $benefit->save();
- // 记录核销
- $params = [
- 'dept_premises_id' => $request->post('dept_premises_id'),
- 'order_remark' => $request->post('remark'),
- 'write_off_member_id' => $request->post('write_off_member_id'),
- 'join_order_member_id' => $memberId
- ];
- $writeOffData = OrderService::generateWriteOffData($params);
- $appointments = Appointment::where('join_appointment_member_benefit_id', $benefitId)
- ->where('appointment_status', 'INIT')
- ->limit($nbr)
- ->get();
- $appointmentIds = [];
- foreach ($appointments as $appointment) {
- $appointmentIds[] = $appointment->appointment_id;
- Appointment::where('appointment_id', $appointment->appointment_id)->update([
- 'appointment_status' => 'DONE',
- 'appointment_datetime' => $times,
- 'appointment_apply_datetime' => $times,
- 'appointment_doing_datetime' => $times,
- 'appointment_done_datetime' => $times,
- 'appointment_done_json' => json_encode($writeOffData)
- ]);
- }
- // 核销服务回写process
- if (!empty($benefit->join_benefit_goods_id) && !empty($benefit->join_benefit_order_id)) {
- $dept = [];
- if (!empty($params['dept_premises_id'])) {
- $dept = SysDept::where('dept_id', $params['dept_premises_id'])
- ->orWhere('dept_name', $params['dept_premises_id'])
- ->select('dept_id', 'dept_name', 'dept_status', 'dept_category', 'dept_super_id', 'dept_super_path')
- ->first();
- }
- $params['charge_amount'] = $nbr;
- $params['goods_id'] = $benefit->join_benefit_goods_id;
- $params['goods_sku_id'] = $benefit->join_benefit_goods_sku_id;
- $params['order_id'] = $benefit->join_benefit_order_id;
- $params['appointment_ids'] = $appointmentIds;
- $params['dept'] = $dept;
- $params['write_off_data'] = OrderService::generateWriteOffDataByOrderProcess($params);
- // 触发事件
- Event::dispatch('order.write_off', $params);
- }
- Db::commit();
- _syslog("订单", "核销成功");
- return json_success('核销成功');
- } catch (\Exception $e) {
- dump($e->getMessage());
- Db::rollBack();
- _syslog("订单", "核销失败");
- return json_fail('核销失败');
- }
- }
- /**
- * 核销餐饮
- */
- public function writeOffDishes(Request $request)
- {
- $orderId = $request->post('order_id', '');
- $memberId = $request->post('member_id', '');
- $times = $request->post('times', '');
- $code = $request->post('sms_code', '');
- if (!$memberId || !$orderId) {
- return json_fail('参数异常');
- }
- $member = Member::find($memberId);
- $mobile = $member->member_mobile;
- $key = "SMS:CODE:DISHES:" . $mobile;
- $redisCode = Redis::get($key);
- if ($code == '' || $redisCode != $code) {
- return json_fail("验证码错误,请重新输入");
- }
- Redis::del($key);
- if (!$times) {
- $times = date('Y-m-d H:i:s');
- } else {
- $times = date('Y-m-d H:i:s', strtotime($times));
- }
- try {
- Db::beginTransaction();
- // 记录核销
- $params = [
- 'dept_premises_id' => $request->post('dept_premises_id'),
- 'order_remark' => $request->post('remark'),
- 'write_off_member_id' => $request->post('write_off_member_id'),
- 'join_order_member_id' => $memberId
- ];
- $writeOffData['charge'] = OrderService::generateWriteOffData($params);
- $writeOffData['charge']['order_id'] = $orderId;
- $writeOffData['charge']['member_id'] = $memberId;
- $writeOffData['charge']['order_code'] = random_string(10, 'number');
- $writeOffData['express'] = 'N';
- $order = Order::where('order_id', $orderId)->first();
- if (!empty($order->order_config_json)) {
- $orderConfigJson = json_decode($order->order_config_json, true);
- if (isset($orderConfigJson['tableid']) && !empty($orderConfigJson['tableid'])) {
- SysDept::where('dept_id', $orderConfigJson['tableid'])->where('dept_category', '桌台')->update(['dept_status' => 'ACTIVED']);
- }
- }
- Order::where('order_id', $orderId)->update([
- 'order_express_json' => json_encode($writeOffData),
- 'order_is_complete' => 'Y',
- 'order_status_system' => 'DONE'
- ]);
- OrderSheet::where('join_sheet_order_id', $orderId)->update([
- 'order_sheet_status' => 'DONE'
- ]);
- Db::commit();
- _syslog("订单", "核销餐品成功");
- return json_success('核销成功');
- } catch (\Exception $e) {
- dump($e->getMessage());
- Db::rollBack();
- _syslog("订单", "核销餐品失败");
- return json_fail('核销失败');
- }
- }
- public function writeOffBenefit(Request $request)
- {
- $memberId = $request->post('member_id', '');
- $benefitList = $request->post('benefitList', []);
- $times = $request->post('times', '');
- $code = $request->post('sms_code', '');
- if (!$memberId || empty($benefitList)) {
- return json_fail('参数异常');
- }
- if (empty($code)) {
- return json_fail('请输入验证码');
- }
- $benefitIds = [];
- foreach ($benefitList as $benefit) {
- if (isset($benefit['nbr']) && intval($benefit['nbr']) > 0) {
- $benefitIds[] = $benefit['member_benefit_id'];
- }
- }
- if (empty($benefitIds)) {
- return json_fail("请填写有效的核销数量");
- }
- $member = Member::find($memberId);
- // $mobile = $member->member_mobile;
- // $key = "SMS:CODE:WRITE_OFF:" . $mobile;
- // $redisCode = Redis::get($key);
- // if ($redisCode != $code) {
- // return json_fail("验证码错误,请重新输入");
- // }
- $benefits = MemberBenefit::whereIn('member_benefit_id', $benefitIds)
- ->where('join_benefit_member_id', $memberId)
- ->get()
- ->toArray();
- foreach ($benefits as $benefit) {
- foreach ($benefitList as $list) {
- if ($list['member_benefit_id'] == $benefit['member_benefit_id'] && intval($list['nbr'] > ($benefit['member_benefit_limit_count'] - $benefit['member_benefit_used_count']))) {
- return json_fail('可核销数量不足');
- }
- }
- }
- if (!$times) {
- $times = date('Y-m-d H:i:s');
- } else {
- $times = date('Y-m-d H:i:s', strtotime($times));
- }
- try {
- Db::beginTransaction();
- // 核销数据
- $params = [
- 'dept_premises_id' => $request->post('dept_premises_id'),
- 'order_remark' => $request->post('remark'),
- 'write_off_member_id' => $request->post('write_off_member_id'),
- 'join_order_member_id' => $memberId,
- 'charge_waiter' => $request->post('charge_waiter'),
- ];
- $writeOffData = OrderService::generateWriteOffData($params);
- $dept = [];
- if (!empty($params['dept_premises_id'])) {
- $dept = SysDept::where('dept_id', $params['dept_premises_id'])
- ->orWhere('dept_name', $params['dept_premises_id'])
- ->select('dept_id', 'dept_name', 'dept_status', 'dept_category', 'dept_super_id', 'dept_super_path')
- ->first();
- }
- // 开始减额度
- $benefitUsed = [];
- $appointmentIds = [];
- foreach ($benefits as $benefit) {
- foreach ($benefitList as $list) {
- if ($list['member_benefit_id'] == $benefit['member_benefit_id']) {
- $usedCount = $benefit['member_benefit_used_count'] + intval($list['nbr']);
- $benefitUpdateData = ['member_benefit_used_count' => $usedCount];
- // 用完了
- if ($benefit['member_benefit_limit_count'] <= $usedCount && !empty($benefit['join_benefit_order_id'])) {
- $benefitUpdateData['member_benefit_status'] = 'DONE';
- $benefitUsed[$benefit['join_benefit_order_id']][] = $benefit['member_benefit_id'];
- // Order::where('order_id', $benefit['join_benefit_order_id'])->update(['order_status_system' => 'DONE']);
- }
- // 更新benefit 表
- MemberBenefit::where('member_benefit_id', $benefit['member_benefit_id'])->update($benefitUpdateData);
- // 更新Appointment 表
- $appointments = Appointment::where('join_appointment_member_benefit_id', $benefit['member_benefit_id'])
- ->where('appointment_status', 'INIT')
- ->limit(intval($list['nbr']))
- ->get()
- ->toArray();
- if ($appointments) {
- foreach ($appointments as $appointment) {
- $appointmentIds[] = $appointment['appointment_id'];
- Appointment::where('appointment_id', $appointment['appointment_id'])->update([
- 'appointment_status' => 'DONE',
- 'appointment_datetime' => $times,
- 'appointment_apply_datetime' => $times,
- 'appointment_doing_datetime' => $times,
- 'appointment_done_datetime' => $times,
- 'appointment_done_json' => json_encode($writeOffData)
- ]);
- }
- } else {
- for ($i = 0; $i < intval($list['nbr']); $i++) {
- Appointment::insert([
- 'appointment_id' => 'AP' . date('ymdHi') . random_string(4, 'up'),
- 'join_appointment_member_id' => $benefit['join_benefit_member_id'],
- 'join_appointment_goods_id' => !empty($benefit['join_benefit_package_id']) ? $benefit['join_benefit_package_id'] : $benefit['join_benefit_goods_id'],
- 'join_appointment_goods_sku_id' => $benefit['join_benefit_goods_sku_id'],
- 'join_appointment_order_id' => $benefit['join_benefit_order_id'],
- 'join_appointment_member_benefit_id' => $benefit['member_benefit_id'],
- 'appointment_classify' => $benefit['member_benefit_category'],
- 'appointment_status' => 'DONE',
- 'appointment_category' => 'NORMAL',
- 'appointment_datetime' => date('Y-m-d H:i:s'),
- 'appointment_apply_datetime' => date('Y-m-d H:i:s'),
- 'appointment_doing_datetime' => date('Y-m-d H:i:s'),
- 'appointment_done_datetime' => date('Y-m-d H:i:s'),
- 'appointment_done_json' => json_encode($writeOffData),
- 'appointment_mode' => 'ORDER',
- 'settlement_mode' => 'ONLINE',
- 'appointment_platform' => 'SYSTEM',
- 'appointment_addtimes' => time()
- ]);
- }
- }
- }
- }
- }
- // 订单服务是否用完了
- foreach ($benefitUsed as $key => $item) {
- $orderUsedComplete = 'Y';
- $orderBenefits = MemberBenefit::where('join_benefit_order_id', $key)->get()->toArray();
- foreach ($orderBenefits as $orderBenefit) {
- if ($orderBenefit['member_benefit_used_count'] >= $orderBenefit['member_benefit_limit_count']) {
- continue;
- }
- if (!in_array($orderBenefit['member_benefit_id'], $item)) {
- $orderUsedComplete = 'N';
- }
- }
- if ($orderUsedComplete == 'Y') {
- Order::where('order_id', $key)->update(['order_is_complete' => 'Y', 'order_status_system' => 'DONE']);
- $processParams = [
- 'join_order_member_id' => $params['join_order_member_id'],
- 'orderId' => $key,
- 'submit_premises_id' => $dept['dept_id'] ?? 0,
- ];
- Event::dispatch('order.complete', $processParams);
- }
- }
- // 核销服务回写process
- foreach ($benefits as $benefit) {
- foreach ($benefitList as $list) {
- 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'])) {
- $params['charge_amount'] = $list['nbr'];
- $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'] : '');
- $params['goods_sku_id'] = $benefit['join_benefit_goods_sku_id'];
- $params['order_id'] = $benefit['join_benefit_order_id'];
- $params['appointment_ids'] = $appointmentIds;
- $params['dept'] = $dept;
- $params['write_off_data'] = OrderService::generateWriteOffDataByOrderProcess($params);
- // 触发事件
- Event::dispatch('order.write_off', $params);
- }
- }
- // 写核销人
- Order::where('order_id', $benefit['join_benefit_order_id'])->update([
- 'order_update_user_id' => JwtToken::getCurrentId(),
- 'order_updatetimes' => time()
- ]);
- }
- // Redis::del($key);
- Db::commit();
- _syslog("订单", "核销成功");
- return json_success('核销成功');
- } catch (\Exception $e) {
- unset($appointmentIds);
- Log::error('核销失败', ['msg' => $e->getMessage()]);
- Db::rollBack();
- _syslog("订单", "核销失败");
- return json_fail('核销失败');
- } finally {
- if (!empty($appointmentIds)) {
- // 打印核销小票
- foreach ($appointmentIds as $id) {
- $this->doPrinterWriterOff($id);
- }
- }
- }
- }
- public function myOrder(Request $request)
- {
- $page = $request->get('page', 1);
- $pageSize = $request->get('pageSize', 1);
- $datetime = $request->get('order_addtimes', []);
- $goodsName = $request->get('goods_name', '');
- $memberId = $request->get('member_id', '');
- if (!$memberId) {
- return json_fail('查询错误');
- }
- $sheetOrderIds = [];
- if (!empty($goodsName)) {
- $goodsIds = Goods::where('goods_name', 'like', '%' . $goodsName . '%')->pluck('goods_id')->toArray();
- $sheetOrderIds = OrderSheet::whereIn('join_sheet_goods_id', $goodsIds)
- ->where('join_sheet_member_id', $memberId)
- ->pluck('join_sheet_order_id')
- ->toArray();
- }
- $order = Order::with([
- 'return' => function ($query) {
- $query->select('join_return_order_id', 'orders_return_id', 'order_return_status');
- },
- 'sheets',
- 'express' => function ($query) {
- $query->select('join_express_order_id', 'order_express_type');
- }
- ])
- ->where('join_order_member_id', $memberId)
- ->where('order_classify', '<>', 'RECHARGE')
- ->when(!empty($datetime), function ($query) use ($datetime) {
- $datetime[0] = strtotime($datetime[0]);
- $datetime[1] = strtotime($datetime[1]);
- $query->whereBetween('order_addtimes', $datetime);
- })
- ->when(!empty($sheetOrderIds), function ($query) use ($sheetOrderIds) {
- $query->whereIn('order_id', $sheetOrderIds);
- });
- $total = $order->count();
- $rows = $order
- ->orderBy('order_addtimes', 'desc')
- ->forPage($page, $pageSize)
- ->get()
- ->toArray();
- foreach ($rows as &$item) {
- $sheetGoodsIds = array_column($item['sheets'], 'join_sheet_goods_id');
- $goods = Goods::whereIn('goods_id', $sheetGoodsIds)->select('goods_id', 'goods_name')->get()->toArray();
- if (count($goods) > 1) {
- $item['goods_name'] = $goods[0]['goods_name'] . ' 等';
- } else {
- $item['goods_name'] = $goods[0]['goods_name'];
- }
- // $item['goods_name'] = !empty($goods->goods_name) ? $goods->goods_name : '';
- // if (!empty($item->goods->goods_cover)) {
- // $item->goods->goods_cover = getenv('STORAGE_DOMAIN') . $item->goods->goods_cover;
- // }
- }
- return json_success('', compact('rows', 'page', 'pageSize', 'total'));
- }
- public function saveExpress($params)
- {
- try {
- $express = new OrderExpress();
- $express->order_express_type = $params['order_express_type'];
- $express->join_express_order_id = $params['orderId'];
- $express->join_express_dept_id = $params['submit_premises_id'] ?? 0;
- $express->order_express_goods = $params['order_express_goods'];
- $express->order_express_city = $params['order_express_city'];
- $express->order_express_address = $params['order_express_address'];
- $express->order_express_mobile = $params['order_express_mobile'] ?? '';
- $express->order_express_telephone = $params['order_express_telephone'] ?? '';
- $express->order_express_person = $params['order_express_person'] ?? '';
- $express->order_express_company = $params['dept_premises_id'] ?? '';
- $express->order_express_extend_json = $params['order_express_extend_json'] ?? '[]';
- $express->order_express_addtimes = time();
- $express->save();
- } catch (\Exception $e) {
- dump($e->getMessage());
- throw new BusinessException('物流信息保存失败');
- }
- }
- // TODO 确认收货(完成订单)
- // public function confirm($id)
- // {
- // $order = Order::where('order_id', $id)->first();
- // if (empty($order)) {
- // return json_fail("暂无数据");
- // }
- //
- // Db::beginTransaction();
- // try {
- // // 主订单
- // Order::where('order_id', $id)->update(['order_status_system' => 'CONFIRM']);
- // } catch (\Exception $e) {
- //
- // }
- // }
- /**
- * @Desc 退款
- * @Author Gorden
- * @Date 2024/7/8 8:40
- *
- * @param Request $request
- * @return Response
- */
- public function doRefund(Request $request)
- {
- $orderId = $request->post('order_id', '');
- $amount = $request->post('refund_amount', 0);
- $password = $request->post('refund_password', '');
- if (!$orderId || !$amount || !$password) {
- return json_fail('参数异常');
- }
- if ($password != '123456') {
- return json_fail('支付密码错误');
- }
- $return = OrderReturn::where('join_return_order_id', $orderId)
- ->first();
- if (!$return) {
- return json_fail("退款订单异常");
- }
- $order = Order::where('order_id', $return->join_return_order_id)->first();
- if (!$order) {
- return json_fail("订单异常");
- }
- if ($order->order_is_complete == 'Y' || $order->order_is_complete == 'R') {
- return json_fail('订单已完成,无法退款');
- }
- if ($amount > $order->order_amount_pay) {
- return json_fail('退款金额不能超过订单金额');
- }
- $payDetail = PayDetail::where('join_pay_order_id', $order->order_groupby)->where('pay_status', 'SUCCESS')->first();
- if (!$payDetail) {
- return json_fail("支付信息异常异常");
- }
- // 在线支付返回
- $payJsonResponse = [];
- if (!empty($payDetail->pay_json_response)) {
- $payJsonResponse = json_decode($payDetail->pay_json_response, true);
- }
- $res = '[]';
- $data = '[]';
- try {
- Db::beginTransaction();
- // 订单主表
- Order::where('order_id', $return->join_return_order_id)->update(['order_is_complete' => 'R']);
- // 订单详情
- OrderSheet::where('join_sheet_order_id', $return->join_return_order_id)->update(['order_sheet_status' => 'RETURNED']);
- // return 表
- $return->order_return_status = 'DONE';
- $return->order_return_refund_json = json_encode(['amount' => $amount, 'datetime' => date('Y-m-d H:i:s'), 'user_id' => JwtToken::getCurrentId()]);
- $return->save();
- $payType = explode('-', $payDetail->pay_prepayid);
- // 区分账户余额支付和在线支付
- if ($payDetail->pay_prepayid == 'WXPAY') {
- // 退款
- $data = [
- 'type' => 'app',
- 'out_trade_no' => $order->order_groupby,
- 'out_refund_no' => $return->orders_return_id,
- 'total_fee' => $payDetail->pay_amount * 100,
- 'refund_fee' => $amount * 100,
- 'refund_desc' => '退款',
- ];
- $res = Pay::wechat(config('payment.wxpay'))->refund($data);
- $resArray = json_decode($res, true);
- if (!$resArray['result_code'] == 'SUCCESS' || !$resArray['return_code'] == 'SUCCESS') {
- throw new PayException("退款失败");
- }
- } else if ($payDetail->pay_prepayid == 'ALIPAY') {
- // 退款
- $data = [
- 'out_trade_no' => $order->order_groupby,
- 'refund_amount' => $amount,
- ];
- $res = Pay::alipay(config('payment.alipay'))->refund($data);
- $resArray = json_decode($res, true);
- if ($resArray['fund_change'] != 'Y' || $resArray['msg'] != 'Success') {
- throw new PayException("退款失败");
- }
- } else if (isset($payType[1]) && $payType[1] == 'CASH') { // 余额支付
- $account = MemberAccount::where('join_account_member_id', $order->join_order_member_id)
- ->where('member_account_classify', 'CASH')
- ->first();
- $account->member_account_expend = $account->member_account_expend - $amount;
- $account->member_account_surplus = $account->member_account_surplus + $amount;
- $account->save();
- $data = [
- 'type' => 'REFUND',
- 'member_id' => $order->join_order_member_id,
- 'order_id' => $return->join_return_order_id,
- 'return_id' => $return->orders_return_id
- ];
- $res = json_encode([
- 'status' => 'SUCCESS'
- ]);
- } else if (isset($payType[1]) && $payType[1] == 'WELFARE') { // 员工福利支付
- $account = MemberAccount::where('join_account_member_id', $order->join_order_member_id)
- ->where('member_account_classify', 'WELFARE')
- ->first();
- $account->member_account_expend = $account->member_account_expend - $amount;
- $account->member_account_surplus = $account->member_account_surplus + $amount;
- $account->member_account_update_user_id = JwtToken::getCurrentId();
- $account->member_account_updatetimes = time();
- $account->save();
- $data = [
- 'type' => 'REFUND',
- 'member_id' => $order->join_order_member_id,
- 'order_id' => $return->join_return_order_id,
- 'return_id' => $return->orders_return_id
- ];
- $res = json_encode([
- 'status' => 'SUCCESS'
- ]);
- } else if (count($payType) == 1 && !in_array($payDetail->pay_prepayid, ['W06', 'A01'])) { // 卡支付
- $account = MemberAccount::where('join_account_member_id', $order->join_order_member_id)
- ->where('member_account_nbr', $payType[0])
- ->where('member_account_classify', 'CARD')
- ->first();
- $account->member_account_expend = $account->member_account_expend - $amount;
- $account->member_account_surplus = $account->member_account_surplus + $amount;
- $account->member_account_update_user_id = JwtToken::getCurrentId();
- $account->member_account_updatetimes = time();
- $account->save();
- $data = [
- 'type' => 'REFUND',
- 'nbr' => $account->member_account_nbr,
- 'member_id' => $order->join_order_member_id,
- 'order_id' => $return->join_return_order_id,
- 'return_id' => $return->orders_return_id
- ];
- $res = json_encode([
- 'status' => 'SUCCESS'
- ]);
- }
- // 生成payDetail
- $payDetailData = [
- 'join_pay_member_id' => $order->join_order_member_id,
- 'join_pay_order_id' => $order->order_groupby,
- 'pay_status' => 'SUCCESS',
- 'pay_category' => 'REFUND',
- 'pay_amount' => $amount,
- 'pay_paytimes' => date('Y-m-d H:i:s'),
- 'pay_json_request' => json_encode($data),
- 'pay_json_response' => $res,
- 'pay_prepayid' => $payType[0] . (!empty($payType[1]) ? '-' . $payType[1] : ''),
- 'pay_addtimes' => time()
- ];
- PayDetail::insert($payDetailData);
- Db::commit();
- // 事件通知
- Event::dispatch('client_message.refund', $order->join_order_member_id);
- _syslog("退款", "发起退款", json_decode($res), $data);
- return json_success("退款成功");
- } catch (PayException $e) {
- Db::rollBack();
- dump($e->getMessage());
- dump($e->getTrace());
- _syslog("退款", "发起退款", $e->getMessage(), $data);
- return json_fail($e->getMessage());
- } catch (\Exception $e) {
- Db::rollBack();
- dump($e->getMessage());
- dump($e->getTrace());
- _syslog("退款", "发起退款", $e->getMessage(), $data);
- if (strpos($e->getMessage(), '余额不足') !== false) {
- return json_fail("基本账户余额不足,请充值后重新发起");
- }
- return json_fail("数据更新失败");
- }
- }
- public function exportOrder(Request $request)
- {
- $timeType = $request->get('time_type', 'add');
- $type = $request->get('type', '');
- [$where, $format, $limit, $field, $order] = $this->selectInput($request);
- $orderClassify = [];
- if ($request->get('goods_classify') && $request->get('goods_classify') == 'SERVICE') {
- $orderClassify = ['SERVICE', 'CHNMED', 'CHNNCD'];
- $where['order_classify'] = ['in', 'SERVICE,CHNMED,CHNNCD'];
- } else if ($request->get('goods_classify') && $request->get('goods_classify') == 'DISHES') {
- $orderClassify = ['MEALS'];
- $where['order_classify'] = $request->get('goods_classify');
- } else if ($request->get('goods_classify')) {
- $orderClassify = [$request->get('goods_classify')];
- $where['order_classify'] = $request->get('goods_classify');
- }
- if (!empty($request->get('order_ids'))) {
- $where['order_id'] = ['in', $request->get('order_ids')];
- }
- if (!empty($where['order_addtimes']) && $timeType == 'add') {
- $where['order_addtimes'][0] = strtotime($where['order_addtimes'][0]);
- $where['order_addtimes'][1] = strtotime($where['order_addtimes'][1]);
- }
- if ($type == 'todayOrder' && empty($where['order_addtimes'])) {
- $where['order_addtimes'][0] = strtotime(date('Y-m-d') . ' 00:00:00');
- $where['order_addtimes'][1] = strtotime(date('Y-m-d') . ' 23:59:59');
- } else if ($type == 'todayOrderAmount') {
- $todayTimeUnix = strtotime(date('Y-m-d') . ' 00:00:00');
- $groupIds = PayDetail::whereRaw('CAST(UNIX_TIMESTAMP(pay_paytimes) as SIGNED) > ? ', [$todayTimeUnix])
- ->where('join_pay_order_id', '<>', '')
- ->where('pay_prepayid', '<>', '')
- ->where('pay_category', '<>', 'RETURN')
- ->where('pay_category', '<>', 'RECHARGE')
- ->where('pay_category', '<>', 'CLEAR')
- ->pluck('join_pay_order_id')
- ->toArray();
- $where['order_groupby'] = ['in', $groupIds];
- }
- $orderId = trim($request->get('order_id'));
- $orderIds = [];
- if (!empty($orderId)) {
- $orderIds = Order::where('order_id', 'like', '%' . $orderId . '%')
- ->pluck('order_id')
- ->toArray();
- }
- $goodsName = trim($request->get('goods_name', ''));
- if (!empty($goodsName)) {
- $goodsIds = Goods::where('goods_name', 'like', '%' . $goodsName . '%')
- ->pluck('goods_id')
- ->toArray();
- $goodsOrderIds = OrderSheet::whereIn('join_sheet_goods_id', $goodsIds)->pluck('join_sheet_order_id')->toArray();
- if (!empty($where['order_id'])) {
- $orderIds = array_intersect($orderIds, $goodsOrderIds);
- } else {
- $orderIds = $goodsOrderIds;
- }
- }
- // 付款时间
- if ($timeType == 'pay' && !empty($where['order_addtimes'])) {
- $payTimeStart = strtotime($where['order_addtimes'][0]);
- $payTimeEnd = strtotime($where['order_addtimes'][1]);
- unset($where['order_addtimes']);
- $payOrderIds = PayDetailService::getPayOrderId($payTimeStart, $payTimeEnd, $orderClassify);
- }
- if ((!empty($orderId) || !empty($goodsName)) && $timeType == 'pay') {
- $orderIds = array_intersect($orderIds, $payOrderIds);
- $where['order_id'] = ['in', implode(',', $orderIds)];
- } elseif (!empty($orderId) || !empty($goodsName)) {
- $where['order_id'] = ['in', implode(',', $orderIds)];
- } elseif ($timeType == 'pay') {
- $where['order_id'] = ['in', implode(',', $payOrderIds)];
- }
- $order = $request->get('order', 'desc');
- $field = $field ?? 'order_addtimes';
- if (!empty($where['order_status_system']) && in_array($where['order_status_system'], ['PENDING', 'WAITING', 'SENDING', 'RECVING', 'SIGNED', 'CONFIRM'])) {
- $where['order_is_complete'] = 'N';
- }
- if (!empty($where['order_status_system']) && $where['order_status_system'] == 'RETURN') {
- unset($where['order_status_system']);
- unset($where['order_is_complete']);
- $where['order_category'] = 'RETURN';
- }
- // 自提订单
- if (!empty($where['order_status_system']) && $where['order_status_system'] == 'PICKUP') {
- $where['order_is_complete'] = 'N';
- $where['order_status_system'] = 'SENDING';
- $where['order_express.order_express_type'] = '自提';
- }
- $query = $this->doSelect($where, $field, $order);
- return $this->exportDoFormat($query, $format, 10000);
- }
- /**
- * 执行真正查询,并返回格式化数据
- * @param $query
- * @param $format
- * @param $limit
- * @return Response
- */
- protected function exportDoFormat($query, $format, $limit): Response
- {
- $methods = [
- 'select' => 'formatSelect',
- 'tree' => 'formatTree',
- 'table_tree' => 'formatTableTree',
- 'normal' => 'formatNormal',
- ];
- $paginator = $query->paginate($limit);
- $total = $paginator->total();
- $items = $paginator->items();
- $items = call_user_func([$this, "exportAfterQuery"], $items);
- $format_function = $methods[$format] ?? 'formatNormal';
- return call_user_func([$this, $format_function], $items, $total);
- }
- protected function exportAfterQuery($items)
- {
- $data = [];
- foreach ($items as $key => $item) {
- $goodsClassify = '';
- $goodsName = '--';
- if (!empty($item['sheet'])) {
- $goods = Goods::where('goods_id', $item['sheet']['join_sheet_goods_id'])->first();
- $goodsClassify = $goods->goods_classify ?? '';
- $goodsName = $goods->goods_name ?? '--';
- }
- $systemStatus = '';
- if ($item['order_is_complete'] == 'Y') {
- $systemStatus = '已完成';
- } elseif ($item['order_is_complete'] == 'R') {
- $systemStatus = '售后已完成';
- }
- // order_return_refund_json
- // dump($item);
- if (!empty($item['order_return_status']) && $item['order_return_status'] == 'PENDING') {
- $systemStatus = '售后待处理';
- } elseif (!empty($item['order_return_status']) && $item['order_return_status'] == 'DOING') {
- $systemStatus = '退款中';
- } elseif (!empty($item['order_return_status']) && $item['order_return_status'] == 'DONE') {
- $systemStatus = '退款完成';
- if (!empty($item['order_return_refund_json'])) {
- $refundJson = json_decode($item['order_return_refund_json'], true);
- if (isset($refundJson['amount']) && $refundJson['amount'] >= $item['order_amount_pay']) {
- $systemStatus .= "(全额)";
- } else {
- $systemStatus .= "(部分)";
- }
- }
- } elseif (!empty($item['order_return_status']) && $item['order_return_status'] == 'DISAGREE') {
- $systemStatus = '不同意退款';
- }
- $payDetails = PayDetail::where('join_pay_order_id', $item['order_groupby'])
- ->where(function ($query) use ($item) {
- $query->whereJsonContains('join_pay_object_json->order_id', $item['order_id'])->orWhere('join_pay_object_json', '')->orWhereNull('join_pay_object_json');
- })->where('pay_status', 'SUCCESS')
- ->where('pay_prepayid', '<>', '')
- ->where('pay_category', '<>', 'REFUND')
- ->get()
- ->toArray();
- if (count($payDetails) > 1) {
- $payWay = '组合支付';
- } elseif (count($payDetails) == 1) {
- $payWayEn = OrderService::getPayWayByPrepayId($payDetails[0]['pay_prepayid']);
- $payWay = '';
- if (!empty($payWayEn)) {
- $payWay = OrderService::$payWay[$payWayEn];
- }
- }
- if (count($payDetails) > 0) {
- $payDetail0 = $payDetails[0];
- $payTimes = $payDetail0['pay_paytimes'];
- }
- if (!empty($item['member']) && $item['member']['member_mobile'] == '0000') {
- $memberName = '散客';
- } else {
- $memberName = !empty($item['cert']) ? $item['cert']['member_cert_name'] : (!empty($item['member']) ? (substr($item['member']['member_mobile'], -4) . '会员' . '-') : '');
- if (!empty($item['member'])) {
- $memberName .= $item['member']['member_mobile'];
- }
- }
- if ($item['order_express_type'] == '自提' && $item['order_status_system'] == 'SENDING') {
- $item['order_status_system'] = 'PICKUP';
- }
- $data[$key] = [
- 'goods_classify' => !empty($goodsClassify) && isset(self::$goodsClassify[$goodsClassify]) ? self::$goodsClassify[$goodsClassify] : '其他订单',
- 'order_id' => $item['order_id'],
- 'group_id' => $item['order_groupby'],
- 'member' => $memberName,
- 'goods_name' => $goodsName,
- 'nbr' => !empty($item['sheet']) ? intval($item['sheet']['order_sheet_num']) : '--',
- 'order_amount_total' => $item['order_amount_total'],
- 'order_amount_pay' => $item['order_amount_pay'],
- 'order_status_system' => !empty($systemStatus) ? $systemStatus : self::$systemStatus[$item['order_status_system']],
- 'order_status_payment' => self::$paymentStatus[$item['order_status_payment']],
- 'pay_way' => $item['order_status_payment'] == 'SUCCESS' ? ($payWay ?? '') : '',
- 'pay_times' => $item['order_status_payment'] == 'SUCCESS' || $item['order_status_payment'] == 'FREE' ? ($payTimes ?? '') : '',
- 'order_addtimes' => date('Y-m-d H:i:s', strtotime($item['order_addtimes'])),
- ];
- }
- return $data;
- }
- public function benefitList(Request $request)
- {
- $orderIds = $request->get('order_ids', []);
- if (empty($orderIds)) {
- return json_fail("请选择需要核销的订单");
- }
- $orders = order::whereIn('order_id', $orderIds)
- ->with([
- 'benefit' => function ($query) {
- $query->select('join_benefit_order_id', 'member_benefit_id', 'member_benefit_name', 'member_benefit_limit_count', 'member_benefit_used_count');
- },
- 'member' => function ($query) {
- $query->select('member_id', 'member_mobile');
- },
- // 'sheets'=>function($query){
- // $query->select('join_sheet_order_id','join_sheet_goods_id');
- // }
- // 'goods'=>function($query){
- // $query->select('goods_id','goods_name');
- // }
- ])
- ->select('order_id', 'join_order_member_id', 'order_is_complete', 'order_status_system')
- ->where("order_is_complete", 'N')
- // ->whereIn("order_category", ['NORMAL', 'SYSTEM'])
- ->orderBy('order_addtimes', 'DESC')
- ->get()
- ->toArray();
- $memberId = array_unique(array_column($orders, 'join_order_member_id'));
- if (count($memberId) > 1) {
- return json_fail("不可同时核销多人订单");
- }
- $data = [];
- foreach ($orders as $order) {
- $orderOne = $order;
- foreach ($order['benefit'] as $benefit) {
- $benefit['member_benefit_limit_count'] = intval($benefit['member_benefit_limit_count']);
- $benefit['member_benefit_used_count'] = intval($benefit['member_benefit_used_count']);
- if ($benefit['member_benefit_used_count'] >= $benefit['member_benefit_limit_count']) {
- continue;
- }
- $benefit['unused'] = $benefit['member_benefit_limit_count'] - $benefit['member_benefit_used_count'];
- $orderOne['benefit'] = $benefit;
- $orderOne['member_benefit_id'] = $benefit['member_benefit_id'];
- $data[] = $orderOne;
- }
- }
- if (empty($data)) {
- return json_fail("您选择的产品没有可核销的服务");
- }
- return json_success('', $data);
- }
- public function chooseBenefitList(Request $request)
- {
- $benefitIds = $request->get('benefit_ids', []);
- $memberId = $request->get('member_id', []);
- if (empty($benefitIds)) {
- return json_fail('请选择需要核销的服务');
- }
- if (empty($memberId)) {
- return json_fail('没有会员信息,请联系管理员');
- }
- $benefits = MemberBenefit::whereIn('member_benefit_id', $benefitIds)
- ->where('member_benefit_status', 'ACTIVED')
- ->where('join_benefit_member_id', $memberId)
- ->select('join_benefit_order_id', 'member_benefit_id', 'member_benefit_name', 'member_benefit_limit_count', 'member_benefit_used_count')
- ->orderBy('member_benefit_addtimes', 'DESC')
- ->get()
- ->toArray();
- foreach ($benefits as &$benefit) {
- $benefit['member_benefit_limit_count'] = intval($benefit['member_benefit_limit_count']);
- $benefit['member_benefit_used_count'] = intval($benefit['member_benefit_used_count']);
- $benefit['unused'] = $benefit['member_benefit_limit_count'] - $benefit['member_benefit_used_count'];
- }
- $member = Member::where('member_id', $memberId)->select('member_id', 'member_mobile')->first()->toArray();
- return json_success('', ['benefits' => $benefits, 'member' => $member]);
- }
- public function customPrinter(Request $request)
- {
- $orderId = $request->post('order_id', '');
- $printer = $request->post('printer', []);
- $premiseName = $request->post('premise', '');
- if (empty($orderId) || empty($premiseName)) {
- return json_fail('参数异常');
- }
- if (empty($printer)) {
- return json_fail('请选择打印设备1');
- }
- $premises = SysDept::where('dept_name', $premiseName)->where('dept_category', '营业场所')->where('dept_status', 'ACTIVED')->first();
- $restaurant = SysDept::where('dept_name', $premiseName)->where('dept_category', '餐厅')->where('dept_status', 'ACTIVED')->first();
- $order = Order::where('order_id', $orderId)->first();
- try {
- foreach ($printer as $print) {
- if (strpos($print, '结算') !== false && $order->order_status_payment != 'SUCCESS') {
- return json_fail('无法打印未支付的结账单');
- }
- if (strpos($print, '收银') !== false && $order->order_status_payment != 'SUCCESS') {
- return json_fail('无法打印未支付的订单');
- }
- if (strpos($print, '核销') !== false && $order->order_status_payment != 'SUCCESS') {
- return json_fail('无法打印未支付的订单');
- }
- if (!empty($premises) || !empty($restaurant)) {
- if ($order->order_classify == 'DISHES' && empty($restaurant)) {
- $restaurant = SysDept::where('dept_super_id', $premises->dept_id)->where('dept_category', '餐厅')->first();
- } elseif ($order->order_classify != 'DISHES') {
- $restaurant = $premises;
- }
- if (!empty($restaurant->dept_extend_json)) {
- $voteData = [
- 'func' => 'procActionToPrinter',
- 'sign' => '',
- 'data' => [
- 'printer_premises' => $restaurant->dept_id,
- 'printer_device' => [
- $print
- ],
- 'printer_action' => 'ExecPrintOrder',
- 'printer_data' => [
- 'order_id' => $orderId,
- 'order_batch' => ''
- ]
- ]
- ];
- if (strpos($print, '核销') !== false) {
- $voteData['data']['printer_data']['order_payoff'] = 'Y';
- }
- Log::info("开始自定义打印", $voteData);
- // dump("打印参数",$voteData);
- http_post_json(getenv('VOTE_MENU_URL'), $voteData);
- }
- }
- }
- return json_success('打印完成');
- } catch (\Exception $e) {
- dump($e->getMessage());
- return json_fail("存在错误,票据未全部打印");
- }
- }
- /**
- * @Desc 单打一条核销记录
- * @Author Gorden
- * @Date 2024/9/24 10:36
- *
- * @param Request $request
- * @return Response
- */
- public function printerWriterOff(Request $request)
- {
- $id = $request->post('id');
- if (!$id) {
- return json_fail('参数异常');
- }
- return $this->doPrinterWriterOff($id);
- }
- public function doPrinterWriterOff($id)
- {
- $payOff = OrderProcess::where('order_process_key', 'PAYOFF')
- ->where('order_process_json', 'like', '%' . $id . '%')
- ->first();
- if (!$payOff) {
- return json_fail('暂无数据');
- }
- try {
- if (!empty($payOff->order_process_json)) {
- $processJson = json_decode($payOff->order_process_json, true);
- $voteData = [
- 'func' => 'procActionToPrinter',
- 'sign' => '',
- 'data' => [
- 'printer_premises' => $processJson['charge']['charge_premises_info']['dept_id'],
- 'printer_device' => [
- '核销'
- ],
- 'printer_action' => 'ExecPrintOrder',
- 'printer_data' => [
- 'order_id' => $processJson['order_id'],
- 'order_payoff' => 'Y',
- 'order_payoff_id' => $payOff->orders_process_id,
- 'order_batch' => ''
- ]
- ]
- ];
- http_post_json(getenv('VOTE_MENU_URL'), $voteData);
- }
- return json_success('success');
- } catch (\Exception $e) {
- dump($e->getMessage());
- return json_fail('打印请求发送失败');
- }
- }
- /**
- * @Desc 查询订单状态
- * @Author Gorden
- * @Date 2024/8/19 11:55
- *
- * @param Request $request
- * @return Response|void
- */
- public function getOrderPayStatus(Request $request)
- {
- $orderId = $request->get('order_id', '');
- if (!$orderId) {
- return json_fail('订单不存在');
- }
- $order = Order::where('order_id', $orderId)->first();
- $oldOrderPaymentStatus = $order->order_status_payment;
- //order_status_payment
- if (!$order) {
- return json_fail('订单不存在');
- }
- $discountJson = [];
- if (!empty($order->order_discount_json)) {
- $discountJson = json_decode($order->order_discount_json, true);
- }
- if ($order->order_status_payment == 'SUCCESS') {
- return json_success('success');
- }
- $params['orderId'] = $orderId;
- $payDetailType = PayDetail::where('join_pay_order_id', $order->order_groupby)->pluck('pay_prepayid')->toArray();
- try {
- Db::beginTransaction();
- $full = '';
- $payStatus = 'N';
- if (in_array('WXPAY', $payDetailType)) {
- $result = Pay::wechat(config('payment.wxpay'))->find($order->order_groupby, 'pos');
- $result = json_decode(json_encode($result), true);
- // $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"}';
- // $result = json_decode($result, true);
- 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') {
- $payStatus = 'Y';
- $order->order_status_payment = 'SUCCESS';
- if (in_array($order->order_category, ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE'])) {
- $order->order_status_system = 'WAITING';
- } else if (in_array($order->order_category, ['DISHES', 'MEALS'])) {
- $order->order_is_complete = 'Y';
- $order->order_status_system = 'DONE';
- } else if (in_array($order->order_category, ['VIP', 'PARTNER'])) {
- $order->order_status_payment = 'PENDING';
- $totalFee = $result['total_fee'] / 100;
- $order->order_amount_paid = $order->order_amount_paid + $totalFee;
- $order->order_amount_pay = $order->order_amount_paid;
- if ($order->order_amount_paid >= $order->order_amount_total) {
- $full = '-满额';
- $order->order_status_payment = 'SUCCESS';
- $order->order_status_system = 'DONE';
- $order->order_is_complete = 'Y';
- }
- } else {
- $order->order_status_system = 'SENDING';
- }
- $order->save();
- // Sheet
- if ($order->order_status_payment == 'SUCCESS') {
- OrderSheet::where('join_sheet_order_id', $orderId)->where('order_sheet_status', 'PAYING')->update(['order_sheet_status' => 'DONE']);
- }
- // 支付记录
- PayDetail::where('join_pay_order_id', $order->order_groupby)->where('pay_prepayid', 'WXPAY')->update([
- 'pay_status' => 'SUCCESS',
- 'pay_paytimes' => date('Y-m-d H:i:s'),
- 'pay_json_response' => json_encode($result)
- ]);
- // 除微信外的支付记录
- PayDetail::where('join_pay_order_id', $order->order_groupby)->where('pay_prepayid', '<>', 'WXPAY')->update([
- 'pay_status' => 'SUCCESS',
- 'pay_paytimes' => date('Y-m-d H:i:s'),
- 'pay_json_response' => json_encode(['pay-result' => '支付成功', 'result-datetime' => date('Y-m-d H:i:s')])
- ]);
- // 加销售量
- OrderSheetService::addGoodsSales($params['orderId']);
- // 优惠券标记使用
- $this->changeOrderCouponStatus($discountJson, 'USED');
- }
- } else if (in_array('ALIPAY', $payDetailType)) {
- $result = Pay::alipay(config('payment.alipay'))->find($order->order_groupby);
- $result = json_decode(json_encode($result), true);
- // $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"}';
- // $result = json_decode($result, true);
- if (!empty($result['code']) && $result['code'] == '10000' && !empty($result['trade_status']) && $result['trade_status'] == 'TRADE_SUCCESS') {
- $payStatus = 'Y';
- $order->order_status_payment = 'SUCCESS';
- if (in_array($order->order_category, ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE'])) {
- $order->order_status_system = 'WAITING';
- } elseif (in_array($order->order_category, ['DISHES', 'MEALS'])) {
- $order->order_is_complete = 'Y';
- $order->order_status_system = 'DONE';
- } else if (in_array($order->order_category, ['VIP', 'PARTNER'])) {
- $order->order_status_payment = 'PENDING';
- $order->order_amount_paid = $order->order_amount_paid + $result['total_amount'];
- $order->order_amount_pay = $order->order_amount_paid;
- if ($order->order_amount_paid >= $order->order_amount_total) {
- $full = '-满额';
- $order->order_status_system = 'DONE';
- $order->order_status_payment = 'SUCCESS';
- $order->order_is_complete = 'Y';
- }
- } else {
- $order->order_status_system = 'SENDING';
- }
- $order->save();
- // Sheet
- if ($order->order_status_payment == 'SUCCESS') {
- OrderSheet::where('join_sheet_order_id', $orderId)->where('order_sheet_status', 'PAYING')->update(['order_sheet_status' => 'DONE']);
- }
- // 支付记录
- PayDetail::where('join_pay_order_id', $order->order_groupby)->where('pay_prepayid', 'ALIPAY')->update([
- 'pay_status' => 'SUCCESS',
- 'pay_paytimes' => date('Y-m-d H:i:s'),
- 'pay_json_response' => json_encode($result)
- ]);
- // 加销售量
- OrderSheetService::addGoodsSales($params['orderId']);
- // 优惠券标记使用
- $this->changeOrderCouponStatus($discountJson, 'USED');
- // Db::commit();
- // if (in_array($order->order_category, ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE', 'GOODS', 'DISHES', 'MEALS'])) {
- // // 给上级提成
- // Event::dispatch('commission.order', $params);
- // }
- // // 收支明细
- // $params['inout_category'] = $oldOrderPaymentStatus == 'AWAITING' ? '挂账订单结算' : ($order->order_classify == 'VIP' ? ('购买康养城VIP套餐包' . $full) : '餐饮订单');
- // Event::dispatch('statistics.inout.in', $params);
- // return json_success('success');
- }
- }
- if ($payStatus == 'Y') {
- foreach ($payDetailType as $item) {
- if (in_array($item, ['WXPAY', 'ALIPAY'])) {
- continue;
- }
- $amount = PayDetail::where('join_pay_order_id', $order->order_groupby)
- ->where('pay_prepayid', $item)
- ->value('pay_amount');
- $this->deductAccountOne($order->order_groupby, $item, $amount);
- }
- Db::commit();
- if (in_array($order->order_category, ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE', 'GOODS', 'DISHES', 'MEALS'])) {
- // 给上级提成
- Event::dispatch('commission.order', $params);
- }
- // 收支明细
- $params['inout_category'] = $oldOrderPaymentStatus == 'AWAITING' ? '挂账订单结算' : ($order->order_classify == 'VIP' ? ('购买康养城VIP套餐包' . $full) : '餐饮订单');
- Event::dispatch('statistics.inout.in', $params);
- return json_success('success');
- }
- Db::rollBack();
- return json_fail('没有查询到记录');
- } catch (\Exception $e) {
- dump($e->getMessage());
- Db::rollBack();
- return json_fail('查询失败');
- }
- }
- /**
- * @Desc 查询订单状态
- * @Author Gorden
- * @Date 2024/8/19 11:55
- *
- * @param Request $request
- * @return Response|void
- */
- public function getProductOrderPayStatus(Request $request)
- {
- $groupId = $request->get('group_id');
- if (!$groupId) {
- return json_fail('订单不存在');
- }
- $orders = Order::where('order_groupby', $groupId)->get()->toArray();
- if (empty($orders)) {
- return json_fail('订单不存在');
- }
- $params['orderGroupId'] = $groupId;
- $payDetailType = PayDetail::where('join_pay_order_id', $groupId)->pluck('pay_prepayid')->toArray();
- try {
- Db::beginTransaction();
- $payStatus = 'N';
- if (in_array('WXPAY', $payDetailType)) {
- $result = Pay::wechat(config('payment.wxpay'))->find($groupId, 'pos');
- $result = json_decode(json_encode($result), true);
- // $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"}';
- // $result = json_decode($result, true);
- 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') {
- $payStatus = 'Y';
- foreach ($orders as $order) {
- $orderUpdateData = ['order_status_payment' => 'SUCCESS'];
- if (in_array($order['order_category'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE'])) {
- $orderUpdateData['order_status_system'] = 'WAITING';
- } else {
- $orderUpdateData['order_status_system'] = 'SENDING';
- }
- // 主订单
- Order::where('order_groupby', $groupId)->update($orderUpdateData);
- // Sheet
- OrderSheet::where('join_sheet_order_id', $order['order_id'])->where('order_sheet_status', 'PAYING')->update(['order_sheet_status' => 'DONE']);
- // 支付记录
- PayDetail::where('join_pay_order_id', $order['order_groupby'])->where('pay_prepayid', 'WXPAY')->update([
- 'pay_status' => 'SUCCESS',
- 'pay_paytimes' => date('Y-m-d H:i:s'),
- 'pay_json_response' => json_encode($result)
- ]);
- // 加销售量
- OrderSheetService::addGoodsSales($order['order_id']);
- $discountJson = [];
- if (!empty($orders[0]['order_discount_json'])) {
- $discountJson = json_decode($orders[0]['order_discount_json'], true);
- }
- // 优惠券标记使用
- $this->changeOrderCouponStatus($discountJson, 'USED');
- }
- }
- } else if (in_array('ALIPAY', $payDetailType)) {
- $result = Pay::alipay(config('payment.alipay'))->find($groupId);
- $result = json_decode(json_encode($result), true);
- // $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"}';
- // $result = json_decode($result, true);
- if (!empty($result['code']) && $result['code'] == '10000' && !empty($result['trade_status']) && $result['trade_status'] == 'TRADE_SUCCESS') {
- $payStatus = 'Y';
- foreach ($orders as $order) {
- $orderUpdateData = ['order_status_payment' => 'SUCCESS'];
- if (in_array($order['order_category'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE'])) {
- $orderUpdateData['order_status_system'] = 'WAITING';
- } else {
- $orderUpdateData['order_status_system'] = 'SENDING';
- }
- // 主订单
- Order::where('order_groupby', $groupId)->update($orderUpdateData);
- // Sheet
- OrderSheet::where('join_sheet_order_id', $order['order_id'])->where('order_sheet_status', 'PAYING')->update(['order_sheet_status' => 'DONE']);
- // 支付记录
- PayDetail::where('join_pay_order_id', $order['order_groupby'])->where('pay_prepayid', 'ALIPAY')->update([
- 'pay_status' => 'SUCCESS',
- 'pay_paytimes' => date('Y-m-d H:i:s'),
- 'pay_json_response' => json_encode($result)
- ]);
- // 加销售量
- OrderSheetService::addGoodsSales($order['order_id']);
- // 优惠券标记使用
- $discountJson = [];
- if (!empty($orders[0]['order_discount_json'])) {
- $discountJson = json_decode($orders[0]['order_discount_json'], true);
- }
- $this->changeOrderCouponStatus($discountJson, 'USED');
- }
- }
- }
- if ($payStatus == 'Y') {
- foreach ($payDetailType as $item) {
- if (in_array($item, ['WXPAY', 'ALIPAY'])) {
- continue;
- }
- $amount = PayDetail::where('join_pay_order_id', $groupId)
- ->where('pay_prepayid', $item)
- ->value('pay_amount');
- $this->deductAccountOne($groupId, $item, $amount);
- }
- // 如果有余额、VIP、福利账户支付
- // if (in_array($orders[0]['join_order_member_id'] . '-CASH', $payDetailType)) {
- // $cashAmount = PayDetail::where('join_pay_order_id', $groupId)
- // ->where('pay_prepayid', $orders[0]['join_order_member_id'] . '-CASH')
- // ->sum('pay_amount');
- // $this->deductAccountOne($groupId, $orders[0]['join_order_member_id'] . '-CASH', $cashAmount);
- // }
- // if (in_array($orders[0]['join_order_member_id'] . '-VIP', $payDetailType)) {
- // $cashAmount = PayDetail::where('join_pay_order_id', $groupId)
- // ->where('pay_prepayid', $orders[0]['join_order_member_id'] . '-VIP')
- // ->sum('pay_amount');
- // $this->deductAccountOne($groupId, $orders[0]['join_order_member_id'] . '-VIP', $cashAmount);
- // }
- // if (in_array($orders[0]['join_order_member_id'] . '-WELFARE', $payDetailType)) {
- // $cashAmount = PayDetail::where('join_pay_order_id', $groupId)
- // ->where('pay_prepayid', $orders[0]['join_order_member_id'] . '-WELFARE')
- // ->sum('pay_amount');
- // $this->deductAccountOne($groupId, $orders[0]['join_order_member_id'] . 'WELFARE', $cashAmount);
- // }
- Db::commit();
- // 服务产生权益
- if (in_array($orders[0]['order_classify'], ['SERVICE', 'CHNMED', 'CHNNCD'])) {
- $this->insertBenefitService($groupId);
- }
- // 产生套包权益
- if (in_array($orders[0]['order_classify'], ['PACKAGE'])) {
- $this->insertBenefitPackage($groupId);
- }
- // 给上级提成-拆单
- OrderService::splitOrderCommission($params);
- // 入收支明细表
- OrderService::splitOrderStatisticsInOut($params);
- return json_success('success');
- }
- Db::rollBack();
- return json_fail('没有查询到记录');
- } catch (BusinessException $e) {
- Db::rollBack();
- _syslog("支付轮询", '订单支付异常:' . $e->getMessage());
- return json_fail($e->getMessage());
- } catch (\Exception $e) {
- dump($e->getMessage());
- Db::rollBack();
- return json_fail('查询失败');
- }
- }
- /**
- * @Desc 大额支付轮询中的账户扣款
- * @Author Gorden
- * @Date 2024/9/26 13:36
- *
- * @param $accountNbr
- * @param $amount
- * @return void
- * @throws BusinessException
- */
- public function deductAccountOne($groupId, $accountNbr, $amount)
- {
- try {
- $account = MemberAccount::where('member_account_nbr', $accountNbr)->first();
- $account->member_account_expend = $account->member_account_expend + $amount;
- if ($account->member_account_surplus < $amount && strpos($accountNbr, 'CASH') !== false) {
- $account->member_account_added = $account->member_account_added - ($amount - $account->member_account_surplus);
- $account->member_account_surplus = 0;
- } else {
- $account->member_account_surplus = $account->member_account_surplus - $amount;
- }
- if ($account->member_account_surplus == 0){
- MemberService::accountToDone($account->member_account_id,$account->member_account_surplus,$account->member_account_added);
- }
- $account->member_account_update_user_id = JwtToken::getCurrentId();
- $account->member_account_updatetimes = time();
- $account->save();
- PayDetail::where('pay_prepayid', $accountNbr)
- ->where('join_pay_order_id', $groupId)
- ->update([
- 'pay_paytimes' => date('Y-m-d H:i:s'),
- 'pay_status' => 'SUCCESS'
- ]);
- } catch (\Exception $e) {
- Log::info("获取大额支付状态:扣除账户金额失败", ['nbr' => $accountNbr, 'group_id' => $groupId]);
- throw new BusinessException("账户金额扣除失败");
- }
- }
- /**
- * @Desc 服务权益设置
- * @Author Gorden
- * @Date 2024/9/26 16:34
- *
- * @param $groupId
- * @return void
- */
- public function insertBenefitService($groupId)
- {
- try {
- $orders = Order::where('order_groupby', $groupId)->select('order_id', 'order_classify')->get()->toArray();
- $orderIds = array_column($orders, 'order_id');
- $sheets = OrderSheet::whereIn('join_sheet_order_id', $orderIds)->get()->toArray();
- foreach ($sheets as $sheet) {
- $params = [];
- foreach ($orders as $order) {
- if ($sheet['join_sheet_order_id'] == $order['order_id']) {
- $params['goods_classify'] = $order['order_classify'];
- }
- }
- $params['join_order_member_id'] = $sheet['join_sheet_member_id'];
- $params['join_sheet_goods_id'] = $sheet['join_sheet_goods_id'];
- $params['join_sheet_goods_sku_id'] = $sheet['join_sheet_goods_sku_id'];
- $params['orderId'] = $sheet['join_sheet_order_id'];
- $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
- for ($i = 0; $i < $sheet['order_sheet_num']; $i++) {
- $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
- $this->insertAppointment($params, []);
- }
- $goodsModel = Goods::where('goods_id', $sheet['join_sheet_goods_id'])->first();
- $goods = [];
- if (!empty($goodsModel)) {
- $goods['goods_id'] = $sheet['join_sheet_goods_id'];
- $goods['skuId'] = $sheet['join_sheet_goods_sku_id'];
- $goods['category'] = $goodsModel->goods_classify;
- $goods['goods_name'] = $goodsModel->goods_name;
- }
- $params['order_sheet_num'] = $sheet['order_sheet_num'];
- $this->insertMemberBenefit($params, $goods);
- }
- } catch (\Exception $e) {
- _syslog("下单", '权益设置失败');
- }
- }
- /**
- * @Desc 套包权益设置
- * @Author Gorden
- * @Date 2024/9/26 16:34
- *
- * @param $groupId
- * @return void
- */
- public function insertBenefitPackage($groupId)
- {
- try {
- $orders = Order::where('order_groupby', $groupId)->select('order_id', 'order_classify')->get()->toArray();
- $orderIds = array_column($orders, 'order_id');
- $sheets = OrderSheet::whereIn('join_sheet_order_id', $orderIds)->get()->toArray();
- foreach ($sheets as $sheet) {
- $params = [];
- $params['orderId'] = $sheet['join_sheet_order_id'];
- foreach ($orders as $order) {
- if ($sheet['join_sheet_order_id'] == $order['order_id']) {
- $params['goods_classify'] = $order['order_classify'];
- }
- }
- $params['packageId'] = $sheet['join_sheet_goods_id'];;
- $components = GoodsComponent::with([
- 'goods' => function ($query) {
- $query->select('goods_id', 'goods_name', 'goods_classify');
- }
- ])->where('join_component_master_goods_id', $params['packageId'])
- ->get()
- ->toArray();
- $params['join_order_member_id'] = $sheet['join_sheet_member_id'];
- foreach ($components as $component) {
- $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
- $componentJson = json_decode($component['goods_component_json'], true);
- $params['join_sheet_goods_id'] = $component['join_component_goods_id'];
- $params['order_sheet_num'] = $sheet['order_sheet_num'] * $componentJson['nbr'];
- $params['join_sheet_goods_sku_id'] = $componentJson['sku_id'];
- for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
- $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
- // 入预约记录
- $this->insertAppointment($params, []);
- }
- $goods['goods_id'] = $component['join_component_goods_id'];
- $goods['goods_name'] = $component['goods']['goods_name'];
- $goods['goods_classify'] = $component['goods']['goods_classify'];
- $goods['skuId'] = $componentJson['sku_id'];
- $goods['category'] = 'SERVICE';
- // 权益表
- $this->insertMemberBenefit($params, $goods);
- }
- $this->sendCoupon($params, ['goods_id' => $params['packageId']], $params['orderId']);
- }
- } catch (\Exception $e) {
- _syslog("下单", '权益设置失败');
- }
- }
- public function sendCoupon($params, $goods, $orderId)
- {
- try {
- $couponSendParams = [
- 'gettype' => 'PACKAGE',
- 'member_id' => $params['join_order_member_id'],
- 'orderId' => $orderId,
- 'join_sheet_goods_id' => $goods['goods_id']
- ];
- CouponService::autoSendCouponByGoods($couponSendParams);
- } catch (\Exception $e) {
- throw new BusinessException("卡券发放失败");
- }
- }
- public function deductAccount($orderId, $orderGroup, $payWay)
- {
- $payDetails = PayDetail::where('join_pay_order_id', $orderGroup)
- ->where('pay_prepayid', '<>', $payWay)
- ->whereJsonContains('join_pay_object_json->order_id', $orderId)
- ->get()
- ->toArray();
- $pays = [];
- foreach ($payDetails as $payDetail) {
- if (isset($pays[$payDetail['pay_prepayid']])) {
- $pays[$payDetail['pay_prepayid']] += $payDetail['pay_amount'];
- } else {
- $pays[$payDetail['pay_prepayid']] = $payDetail['pay_amount'];
- }
- }
- foreach ($pays as $key => $amount) {
- if (strpos($key, 'CASH') !== false || strpos($key, 'CARD') !== false || strpos($key, 'WELFARE') !== false || strpos($key, 'VIP') !== false) {
- $account = MemberAccount::where('member_account_nbr', $key)->first();
- $account->member_account_expend = $account->member_account_expend + $amount;
- $account->member_account_surplus = $account->member_account_surplus - $amount;
- $account->member_account_update_user_id = JwtToken::getCurrentId();
- $account->member_account_updatetimes = time();
- $account->save();
- }
- }
- PayDetail::where('join_pay_order_id', $orderGroup)
- ->where('pay_prepayid', '<>', $payWay)
- ->whereJsonContains('join_pay_object_json->order_id', $orderId)
- ->update(['pay_status' => 'SUCCESS']);
- }
- /**
- * @Desc 修改订单状态-挂账
- * @Author Gorden
- * @Date 2024/8/20 15:58
- *
- * @param Request $request
- * @return Response
- */
- public function updateStatus(Request $request)
- {
- $orderId = $request->post('order_id', '');
- $orderStatusPayment = $request->post('order_status_payment', '');
- $freeRemark = $request->post('free_remark', '');
- $order = Order::where('order_id', $orderId)
- ->select('order_id', 'order_groupby', 'order_status_payment', 'order_config_json', 'order_amount_total', 'order_discount_json', 'order_extend_json')
- ->first();
- Db::beginTransaction();
- try {
- if ($orderStatusPayment == 'AWAITING' && $order->order_status_payment != 'PENDING') {
- throw new BusinessException("当前订单不允许挂账");
- } else if ($orderStatusPayment == 'FREE' && $order->order_status_payment != 'PENDING') {
- throw new BusinessException("当前订单不允许免单");
- }
- $orderExtendJson = [];
- if (!empty($order->order_extend_json)) {
- $orderExtendJson = json_decode($order->order_extend_json, true);
- }
- // 挂账,释放餐桌
- if (in_array($orderStatusPayment, ['AWAITING', 'FREE'])) {
- $order->order_status_payment = $orderStatusPayment;
- $orderExtendJson['awaiting_times'] = date('Y-m-d H:i:s');
- $order->order_extend_json = json_encode($orderExtendJson, JSON_UNESCAPED_UNICODE);
- // 如果有餐桌,释放
- if (!empty($order->order_config_json)) {
- $orderConfigJson = json_decode($order->order_config_json, true);
- if (!empty($orderConfigJson['tableid'])) {
- SysDept::where('dept_id', $orderConfigJson['tableid'])->update(['dept_status' => 'ACTIVED']);
- }
- }
- }
- if ($orderStatusPayment == 'FREE') {
- $orderDiscountJson = [];
- if (!empty($order->order_discount_json)) {
- $orderDiscountJson = json_decode($order->order_discount_json, true);
- }
- $orderDiscountJson[date('Y-m-d H:i:s')] = [
- 'coupon_id' => null,
- 'coupon_value' => $order->order_amount_total,
- 'coupon_classify' => '免单',
- 'coupon_detail_id' => ['免单'],
- 'coupon_classify_en' => ['free']
- ];
- $orderExtendJson['free_remark'] = $freeRemark;
- $order->order_discount_json = json_encode($orderDiscountJson, JSON_UNESCAPED_UNICODE);
- $order->order_extend_json = json_encode($orderExtendJson, JSON_UNESCAPED_UNICODE);
- $order->order_is_complete = 'Y';
- $order->order_status_system = 'DONE';
- $order->order_amount_pay = 0;
- // sheet表
- OrderSheet::where('join_sheet_order_id', $orderId)->update(['order_sheet_status' => 'DONE']);
- // payDetail 表
- PayDetail::where('join_pay_order_id', $order->order_groupby)
- ->update([
- 'pay_status' => 'SUCCESS',
- 'pay_amount' => 0,
- 'pay_prepayid' => 'MONEY',
- 'pay_paytimes' => date('Y-m-d H:i:s')
- ]);
- }
- $order->save();
- Db::commit();
- return json_success('success');
- } catch (BusinessException $e) {
- Db::rollBack();
- return json_fail($e->getMessage());
- } catch (\Exception $e) {
- Db::rollBack();
- return json_fail('修改订单状态失败');
- }
- }
- public function useCoupon(Request $request)
- {
- $goods = $request->post('goods', []);
- $coupon = $request->post('coupon', []);
- $payAmount = $request->post('pay_amount', 0);
- $memberId = $request->post('member_id', '');
- $settlementNow = $request->post('settlement_now', 'N');
- if (empty($goods) || empty($coupon) || empty($memberId)) {
- return json_fail("参数异常");
- }
- foreach ($coupon as $item) {
- if (!in_array(substr($item, 0, 2), ['CU', 'CO'])) {
- return json_fail("参数异常");
- }
- }
- // 是否是推广券
- $promotionCoupon = Coupon::whereIn('coupon_id', $coupon)
- ->where('coupon_category', 'PROMOTION')
- ->select('coupon_id')
- ->first();
- if (!empty($promotionCoupon)) {
- // 是否已有
- $couponDetail = CouponDetail::whereIn('join_detail_coupon_id', $coupon)
- ->where('join_coupon_detail_member_id', $memberId)
- ->whereIn('coupon_detail_status', ['INIT', 'PENDING', 'ACTIVED'])
- ->first();
- if (empty($couponDetail)) {
- $chooseCoupons[] = [
- 'id' => $coupon[0],
- 'nbr' => 1,
- 'gain_datetime' => date('Y-m-d H:i:s')
- ];
- CouponDetailService::customSendService($chooseCoupons, '', [$memberId], '');
- }
- }
- $amountBalance = [
- 'pay_amount' => $payAmount,
- 'welfare_balance' => 0,
- 'cut_balance' => 0,
- ];
- foreach ($goods as $good) {
- $result = OrderService::chooseCoupon($settlementNow, $memberId, $goods, $good, $coupon, $amountBalance);
- $amountBalance = [
- 'pay_amount' => $result['pay_amount'],
- 'welfare_balance' => $result['welfare_balance'],
- 'cut_balance' => $result['cut_balance'],
- ];
- }
- Redis::del("ORDER:USE:COUPON:" . $memberId);
- return json_success("success", ['pay_amount' => $amountBalance['pay_amount']]);
- }
- /**
- * @Desc 订单的核销记录
- * @Author Gorden
- * @Date 2024/9/13 14:28
- *
- * @param Request $request
- * @return Response
- */
- public function writeOffList(Request $request)
- {
- $orderId = $request->get('order_id');
- $page = $request->get('page', 1);
- $pageSize = $request->get('pageSize', 20);
- if (!$orderId) {
- return json_fail("参数异常");
- }
- $appointments = Appointment::with([
- 'member' => function ($query) {
- $query->select('member_id', 'member_mobile');
- },
- 'memberInfo',
- 'cert',
- 'goods' => function ($query) {
- $query->select('goods_id', 'goods_name');
- }
- ])->where('join_appointment_order_id', $orderId)
- ->where('appointment_status', 'DONE')
- ->select('appointment_id', 'join_appointment_member_id', 'join_appointment_goods_id', 'appointment_done_datetime', 'appointment_done_json');
- $total = $appointments->count();
- $rows = $appointments->forPage($page, $pageSize)
- ->orderBy('appointment_done_datetime', 'DESC')
- ->get();
- foreach ($rows as &$item) {
- $memberMobile = '';
- if (!empty($item['member']) && !empty($item['member']['member_mobile'])) {
- $memberMobile = $item['member']['member_mobile'];
- }
- $memberNickname = '';
- if (!empty($item['member_info']) && !empty($item['member_info']['member_info_nickname'])) {
- $memberNickname = $item['member_info']['member_info_nickname'];
- }
- $memberName = '';
- if (!empty($item['cert']) && !empty($item['cert']['member_cert_name'])) {
- $memberName = $item['cert']['member_cert_name'];
- }
- unset($item['member'], $item['member_info'], $item['cert']);
- $item['member_name'] = MemberService::getMemberName($memberMobile, $memberName, $memberNickname);
- if (!empty($item['appointment_done_json'])) {
- $doneJson = json_decode($item['appointment_done_json'], true);
- if (isset($doneJson['charge']) && !empty($doneJson['charge']['charge_user_id'])) {
- $item['username'] = SysUser::where('user_id', $doneJson['charge']['charge_user_id'])->value('user_name');
- $item['waiter'] = $doneJson['charge']['charge_waiter'] ?? '';
- }
- if (isset($doneJson['charge']) && !empty($doneJson['charge']['charge_premises'])) {
- $item['premise'] = $doneJson['charge']['charge_premises'];
- }
- $item['nbr'] = 1;
- }
- }
- return json_success('', compact('rows', 'page', 'pageSize', 'total'));
- }
- /**
- * @Desc 扣除账户金额
- * @Author Gorden
- * @Date 2024/9/26 14:16
- *
- * @param $accountNbr
- * @param $amount
- * @return void
- */
- public function deductAmount($accountNbr, $amount)
- {
- try {
- $account = MemberAccount::where('member_account_nbr', $accountNbr)->first();
- $account->member_account_expend = $account->member_account_expend + $amount;
- if ($account->member_account_surplus < $amount && strpos($accountNbr, 'CASH') !== false) {
- $account->member_account_added = $account->member_account_added - ($amount - $account->member_account_surplus);
- $account->member_account_surplus = 0;
- } else {
- $account->member_account_surplus = $account->member_account_surplus - $amount;
- }
- if ($account->member_account_surplus == 0){
- MemberService::accountToDone($account->member_account_id,$account->member_account_surplus,$account->member_account_added);
- }
- $account->save();
- } catch (\Exception $e) {
- _syslog("下单扣款", "扣款失败");
- throw new BusinessException("账户扣款失败");
- }
- }
- // public function getMergeOrder(Request $request)
- // {
- // $orderIds = $request->get('order_ids');
- // if (!$orderIds) {
- // return json_fail('参数异常');
- // }
- //
- // $orders = Order::whereIn('order_id', $orderIds)
- // ->select('order_id', 'order_groupby', 'order_amount_total', 'order_amount_pay')
- // ->get()
- // ->toArray();
- // $groupIds = array_column($orders, 'order_groupby');
- // if (count(array_unique($groupIds)) > 1){
- // return json_fail("请选择同批次下单的记录");
- // }
- //
- // return json_success("");
- // }
- public static $goodsClassify = [
- // goodsClassify: {GOODS:"健康产品订单",SERVICE:"服务订单",DEVICE:"设备订单",SPECIAL:"专题业务订单",PACKAGE:"套餐订单",RECHARGE:"充值订单",OTHER:"其他订单"},
- 'GOODS' => "产品订单",
- 'SERVICE' => "服务订单",
- 'CHNMED' => '服务订单',
- 'CHNNCD' => '服务订单',
- 'DEVICE' => '设备订单',
- 'SPECIAL' => '专题业务订单',
- 'PACKAGE' => '套包订单',
- 'RECHARGE' => '充值订单',
- 'OTHER' => '其他订单',
- 'DISHES' => '餐饮订单',
- 'MEALS' => '餐饮订单',
- 'VIP' => '康养城订单',
- 'COMBINE' => '新客专享订单',
- 'PARTNER' => '会员合伙人订单',
- 'REFERRER' => '康养推荐官订单',
- 'CARD' => '储值卡订单'
- ];
- // systemStatus: {BEING:"待生效",PAYING:"待支付",PENDING:"待确认",WAITING:"待受理",SENDING:"待发货",RECVING:"待收货",SIGNED:"已签收",CONFIRM:"确认收货"},
- // paymentStatus: {PENDING:"待支付",CANCEL:"取消支付",SUCCESS:"支付成功"},
- public static $systemStatus = [
- 'BEING' => '待生效',
- 'PAYING' => "待支付",
- 'PENDING' => "待确认",
- 'WAITING' => "待使用",
- 'SENDING' => "待发货",
- 'PICKUP' => "待自提",
- 'RECVING' => "待收货",
- 'SIGNED' => "已签收",
- 'CONFIRM' => "确认收货",
- 'DONE' => '已完成',
- 'CANCEL' => '已取消'
- ];
- public static $paymentStatus = [
- 'WAITING' => "待支付",
- 'PENDING' => "待支付",
- 'CANCEL' => "取消支付",
- 'SUCCESS' => "支付成功",
- 'AWAITING' => "挂账",
- 'FREE' => "免单"
- ];
- }
|