123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923 |
- <?php
- /**
- * 订单数据模型
- * Created by PhpStorm.
- * User: XiaoMing
- * Date: 2019/10/31
- * Time: 15:53
- */
- namespace JinDouYun\Model\Order;
- use JinDouYun\Controller\System\Driver;
- use JinDouYun\Model\System\MDriver;
- use Mall\Framework\Core\StatusCode;
- use Mall\Framework\Core\ErrorCode;
- use Mall\Framework\Core\ResultWrapper;
- use Mall\Framework\Factory;
- use JinDouYun\Cache\ActivityLimitCache;
- use JinDouYun\Cache\CustomerCache;
- use JinDouYun\Cache\OverviewCache;
- use JinDouYun\Cache\SystemCache;
- use JinDouYun\Cache\Stock;
- use JinDouYun\Cache\EnterpriseCache;
- use JinDouYun\Controller\Common\CloudPrint;
- use JinDouYun\Controller\Common\Logger;
- use JinDouYun\Dao\Order\DOrderReceive;
- use JinDouYun\Dao\Order\DOrderIndex;
- use JinDouYun\Dao\Order\DOrder;
- use JinDouYun\Dao\Order\DOrderGoods;
- use JinDouYun\Dao\Order\DOrderStatistics;
- use JinDouYun\Dao\Cashier\DCashierCustomerPrice;
- use JinDouYun\Dao\Customer\DCustomer;
- use JinDouYun\Dao\Department\DStaff;
- use JinDouYun\Dao\System\DCustomerSource;
- use JinDouYun\Dao\System\DExpressCode;
- use JinDouYun\Dao\UserCenter\DUserCenter;
- use JinDouYun\Dao\Finance\DReceivedIndex;
- use JinDouYun\Model\System\MBasicSetup;
- use JinDouYun\Model\Finance\MCustomerBalance;
- use JinDouYun\Model\System\MPaymentSetting;
- use JinDouYun\Model\Market\MUserCoupon;
- use JinDouYun\Model\MBaseModel;
- use JinDouYun\Model\Log\MOrderLog;
- use JinDouYun\Model\GoodsManage\MSku;
- use JinDouYun\Model\Shop\MShop;
- use JinDouYun\Model\Customer\MShippingAddress;
- use JinDouYun\Model\Cart\MCart;
- use JinDouYun\Model\Stock\MInventory;
- use JinDouYun\Model\Stock\MInventoryOut;
- use JinDouYun\Model\Stock\MWarehouse;
- use JinDouYun\Model\Customer\MCustomer;
- use JinDouYun\Model\Goods\MGoods;
- use JinDouYun\Model\Finance\MAccount;
- use JinDouYun\Model\Finance\MReceived;
- use JinDouYun\Model\SysAreaChina\MSysAreaChina;
- use JinDouYun\Model\Customer\MMemberBalanceDetail;
- use JinDouYun\Model\Cashier\MCashier;
- use JinDouYun\Model\Cashier\MCashierCart;
- use JinDouYun\Model\Department\MStaff;
- use JinDouYun\Model\Finance\MMerchantFlow;
- use JinDouYun\Model\Finance\MReceive;
- use JinDouYun\Model\Finance\MRefund;
- use JinDouYun\Model\System\MDeliverySetting;
- use JinDouYun\Model\System\MPrintNum;
- use JinDouYun\Model\System\MProcessSetting;
- use JinDouYun\Model\Order\MPay;
- use JinDouYun\Model\GoodsManage\MGoodsBasic;
- use JinDouYun\Model\Merchant\MMerchantSettlement;
- use JinDouYun\Model\System\MSystemPushMessage;
- use Util\KDNiao\KDNiaoQuery;
- use Util\KuaiDi100\Query;
- use Util\WeiXin\Pay;
- use Util\AliPay\Pay as aliPay;
- use Util\ByteDance\Pay as bytePay;
- //use Util\Common\PartnerTools;
- class MOrder extends MBaseModel
- {
- /**
- * @var DOrder
- */
- private $objDOrder;
- /**
- * @var int 用户id
- */
- private $onlineUserId;
- /**
- * @var int 企业id
- */
- private $onlineEnterpriseId;
- /**
- * @var int 单表数据量
- */
- private $cutTable = 500000;
- /**
- * @var DOrderIndex
- */
- private $objDOrderIndex;
- /**
- * @var DOrderGoods
- */
- private $objDOrderGoods;
- /**
- * @var DOrderStatistics
- */
- private $objDOrderStatistics;
- /**
- * @var bool
- */
- private $isFront;//是否是前台调用此Model 前台=>true
- /**
- * @var OverviewCache
- */
- private $objOverviewCache;
- /**
- * @var string
- */
- private $orderStatisticsTableName = 'order_statistics';
- /**
- * @var MAccount
- */
- private $objMAccount;
- /**
- * @var MReceived
- */
- private $objMReceived;
- /**
- * @var ActivityLimitCache
- */
- private $objActivityLimitCache;
- /**
- * @var SaleOrder 销售单
- */
- private $objSaleOrder;
- /**
- * @var bool 销售单是否打印小票
- */
- private $isEnablePrint = false;
- /**
- * @var DOrderReceive
- */
- private $objDOrderReceive;
- /**
- * @var DCustomer
- */
- private $objDCustomer;
- /**
- * @var int
- */
- private $loginUserCenterId;
- /**
- * @var array
- */
- private $expressMap = [
- 'express_hundred' => 'kuaidi100',
- 'express_bird' => 'kdniao'
- ];
- /**
- * @var bool
- */
- private $isCashier;
- /**
- * @var MProcessSetting
- */
- private $objMProcessSetting;
- use TStdOrder;
- /**
- * MOrder constructor.
- * @param $onlineUserId
- * @param $onlineEnterpriseId
- * @param null $loginUserCenterId
- * @param bool $isFront
- * @throws \Exception
- */
- public function __construct($onlineUserId, $onlineEnterpriseId, $loginUserCenterId = null, $isFront = false, $isCashier = false)
- {
- $this->isCashier = $isCashier;
- $this->isFront = $isFront;
- $this->onlineUserId = $onlineUserId;
- $this->onlineEnterpriseId = $onlineEnterpriseId;
- $this->loginUserCenterId = $loginUserCenterId;
- parent::__construct($this->onlineEnterpriseId, $loginUserCenterId);
- $this->objDOrder = new DOrder('default');
- self::orderSubTable($onlineEnterpriseId, $onlineUserId);
- $this->objDOrderIndex = new DOrderIndex();
- $this->objDOrderGoods = new DOrderGoods('default');
- $this->objDOrderReceive = new DOrderReceive();
- $this->objDOrderStatistics = new DOrderStatistics('default');
- $this->objMAccount = new MAccount($onlineEnterpriseId, $onlineUserId);
- $this->objMReceived = new MReceived($onlineEnterpriseId, $onlineUserId);
- $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId);
- $this->objDOrderStatistics->setTable($this->objDOrderStatistics->get_Table() . '_' . $this->onlineEnterpriseId);
- $this->objDOrder->setSearchIndex('order_search')->setType('order');
- $this->objActivityLimitCache = new ActivityLimitCache($this->onlineEnterpriseId);
- $this->objOverviewCache = new OverviewCache();
- $this->objSaleOrder = new SaleOrder();
- $this->objDCustomer = new DCustomer();
- $this->objDCustomer->setTable('qianniao_customer_' . $this->onlineEnterpriseId);
- $this->objMProcessSetting = new MProcessSetting($this->onlineEnterpriseId);
- }
- /**
- * 订单分表 分表规则:企业id_(客户/200000)
- * @param $enterpriseId (企业id)
- * @param $userId (用户id)
- * @throws \Exception
- */
- public function orderSubTable($enterpriseId, $userId)
- {
- $tableName = $this->objDOrder->getTableName('qianniao_order_' . $enterpriseId, $userId, $this->cutTable);
- self::existsTable($tableName);
- $this->objDOrder->setTable($tableName);
- }
- /**
- * 获取订单表表名
- */
- public function getOrderTable($enterpriseId, $userId){
- return $this->objDOrder->getTableName('qianniao_order_' . $enterpriseId, $userId, $this->cutTable);
- }
- /**
- * 统计订单信息
- *
- * @param $data
- * @param $className
- */
- private static function noticeStatistics($data, $className)
- {
- $i = 1;
- do {
- $postData = [
- 'topicName' => 'MyJob',
- 'topicClass' => "Jobs\Model\MTopic\Order\\" . $className,
- 'topicMethon' => 'push',
- 'topicMethonParams' => [
- 'userCenterId' => $data['userCenterId'],
- 'enterpriseId' => $data['enterpriseId'],
- 'customerId' => $data['customerId'],
- 'no' => $data['no'],
- 'noticeType' => $data['noticeType'],
- ],
- ];
- $url = QIANNIAO_QUEUE . '/CAddJob/add';
- $result = request($url, $postData);
- $i++;
- } while ($result['httpcode'] != 200 && $i <= 3);
- }
- /**
- * 分表后缀+月日+订单id
- * @param $orderId
- * @return string
- */
- private function createVerifyCode($orderId)
- {
- $fix = ceil($this->onlineUserId / $this->cutTable);
- return $fix . '-' . date('nj') . '-' . $orderId;
- }
- /**
- * Doc: (des="")
- * User: XMing
- * Date: 2020/12/25
- * Time: 2:11 下午
- * @param $data
- * @return ResultWrapper
- */
- public function checkLimit($data)
- {
- foreach ($data as $goods) {
- if (isset($goods['activityId'])) {
- //获取活动商品剩余数量
- $surplusNum = $this->objActivityLimitCache->getLen($goods['activityId'], $goods['goodsId'], $goods['skuId']);
- if ($surplusNum < $goods['buyNum']) {
- return ResultWrapper::fail($goods['title'] . '活动剩余数量不足', ErrorCode::$paramError);
- }
- }
- }
- return ResultWrapper::success($data);
- }
- /**
- * Doc: (des="订单编辑")
- * User: XMing
- * Date: 2020/11/5
- * Time: 10:07 上午
- * @param array $params
- * @param $id
- * @return ResultWrapper
- * @throws \Exception
- */
- public function edit(array $params, $id): ResultWrapper
- {
- $orderIndex = $this->objDOrderIndex->get($id);
- if ($orderIndex === false) {
- return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
- }
- if (empty($orderIndex)) {
- return ResultWrapper::fail('未获取到指定订单', ErrorCode::$paramError);
- }
- /*if ($orderIndex['payStatus'] == StatusCode::$standard) {
- return ResultWrapper::fail('订单已支付,不能编辑', ErrorCode::$paramError);
- }
- if ($orderIndex['auditStatus'] != StatusCode::$auditStatus['auditing']) {
- return ResultWrapper::fail('订单已审核不能编辑', ErrorCode::$paramError);
- }*/
- if (
- in_array($orderIndex['orderStatus'], [StatusCode::$orderStatus['waitReceive'], StatusCode::$orderStatus['finish'], StatusCode::$orderStatus['close']])
- ) {
- return ResultWrapper::fail('此订单不能编辑', ErrorCode::$paramError);
- }
- $fix = ceil((empty($params['userCenterId']) ? 1 : $params['userCenterId']) / $this->cutTable);
- $this->objDOrderReceive->setTable('qianniao_order_receive_' . $this->onlineEnterpriseId . '_' . $fix);
- $this->objDOrderGoods->setTable('qianniao_order_goods_' . $this->onlineEnterpriseId . '_' . $fix);
- $objMCustomerBalance = new MCustomerBalance($this->onlineEnterpriseId, $this->onlineUserId);
- $objMOrderGoods = new MOrderGoods($this->onlineUserId, $this->onlineEnterpriseId);
- $customerResult = self::getCustomerInfoByUserCenterId($params['userCenterId']);
- if (!$customerResult->isSuccess()) {
- return ResultWrapper::fail($customerResult->getData(), $customerResult->getErrorCode());
- }
- $customer = $customerResult->getData();
- isset($customer['customerType']) && $params['customerType'] = $customer['customerType'];
- isset($customer['salesManId']) && $params['salesManId'] = $customer['salesManId'];
- isset($customer['salesManName']) && $params['salesManName'] = $customer['salesManName'];
- $params['customerOwe'] = $objMCustomerBalance->getCustomerBalance($customer['id']);//获取客户当前欠款
- $address = [];
- $selfRule = [];
- switch ($params['deliveryType']) {
- case StatusCode::$deliveryType['goodsDelivery']:
- $addressResult = self::getAddressInfo($params['addressId']);
- if (!$addressResult->isSuccess()) {
- return ResultWrapper::fail($addressResult->getData(), $addressResult->getErrorCode());
- }
- $address = $addressResult->getData();
- break;
- case StatusCode::$deliveryType['selfMention']:
- $selfRuleResult = self::getSelfRuleData($params['selfRuleId']);
- if (!$selfRuleResult->isSuccess()) {
- return ResultWrapper::fail($selfRuleResult->getData(), $selfRuleResult->getErrorCode());
- }
- $selfRule = $selfRuleResult->getData();
- break;
- }
- $status = $this->objDOrder->beginTransaction();
- $updateIndexResult = $this->objDOrderIndex->update(
- [
- 'userCenterId' => isset($params['userCenterId']) ? $params['userCenterId'] : 0,
- 'deliveryType' => isset($params['deliveryType']) ? $params['deliveryType'] : 0,
- 'customerId' => isset($params['customerId']) ? $params['customerId'] : 0,
- 'deliveryNo' => isset($params['deliveryNo']) ? $params['deliveryNo'] : '',
- 'expressName' => isset($params['expressName']) ? $params['expressName'] : '',
- 'expressId' => isset($params['expressId']) ? $params['expressId'] : 0,
- 'selfRuleId' => isset($params['selfRuleId']) ? $params['selfRuleId'] : 0,
- 'updateTime' => time(),
- ],
- $id
- );
- if ($updateIndexResult === false) {
- $this->objDOrder->rollBack();
- return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
- }
- $updateOrder = [
- 'customerName' => isset($params['customerName']) ? $params['customerName'] : '',
- 'customerId' => isset($params['customerId']) ? $params['customerId'] : 0,
- 'deliveryType' => isset($params['deliveryType']) ? $params['deliveryType'] : 0,
- 'remark' => isset($params['remark']) ? $params['remark'] : '',
- 'salesManId' => isset($params['salesManId']) ? $params['salesManId'] : 0,
- 'salesManName' => isset($params['salesManName']) ? $params['salesManName'] : '',
- 'customerType' => isset($params['customerType']) ? $params['customerType'] : 0,
- 'userCenterId' => isset($params['userCenterId']) ? $params['userCenterId'] : 0,
- 'customerOwe' => isset($params['customerOwe']) ? $params['customerOwe'] : 0,
- 'preferential' => isset($params['preferential']) ? $params['preferential'] : 0,
- 'vipDiscount' => isset($params['vipDiscount']) ? $params['vipDiscount'] : 0,
- 'expressMoney' => isset($params['expressMoney']) ? $params['expressMoney'] : 0,
- 'expressName' => isset($params['expressName']) ? $params['expressName'] : '',
- 'expressId' => isset($params['expressId']) ? $params['expressId'] : 0,
- 'deliveryNo' => isset($params['deliveryNo']) ? $params['deliveryNo'] : '',
- 'selfRuleId' => isset($params['selfRuleId']) ? $params['selfRuleId'] : 0,
- 'originPayAmount' => isset($params['originPayAmount']) ? $params['originPayAmount'] : 0,
- 'payAmount' => isset($params['payMoney']) ? $params['payMoney'] : 0,
- 'totalMoney' => isset($params['totalMoney']) ? $params['totalMoney'] : 0,
- 'receivedMoney' => isset($params['receivedMoney']) ? $params['receivedMoney'] : 0,
- "accountList" => isset($params['accountList']) ? json_encode($params['accountList']) : null,
- "currentAccountName" => isset($params['currentAccountName']) ? $params['currentAccountName'] : '',
- "totalReduceMoney" => isset($params['totalReduceMoney']) ? $params['totalReduceMoney'] : 0,
- "selfRuleData" => empty($selfRule) ? null : json_encode($selfRule),
- "updateTime" => time(),
- ];
- $updateOrderResult = $this->objDOrder->update($updateOrder, $id);
- if ($updateOrderResult === false) {
- $this->objDOrder->rollBack();
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- if (!empty($address)) {
- $updateReceiveResult = $this->objDOrderReceive->update([
- 'customerId' => $address['customerId'],
- 'customerCode' => $address['customerCode'],
- 'realName' => $address['name'],
- 'mobile' => $address['mobile'],
- 'address' => $address['address'],
- 'provinceCode' => $address['provinceCode'],
- 'cityCode' => $address['cityCode'],
- 'districtCode' => $address['districtCode'],
- 'updateTime' => time()
- ], ['orderId' => $id]);
- if ($updateReceiveResult === false) {
- $this->objDOrder->rollBack();
- return ResultWrapper::fail($this->objDOrderReceive->error(), ErrorCode::$dberror);
- }
- }
- //编辑商品
- if ($orderIndex['payStatus'] != StatusCode::$standard || $orderIndex['auditStatus'] != StatusCode::$auditStatus['auditPass']) {
- //解锁库存
- $objMInventory = new MInventory($this->onlineEnterpriseId, $this->onlineUserId);
- $unlockResult = $objMInventory->unlockInventory([$id], StatusCode::$orderType['saleOrder'], $orderIndex['createTime']);
- if (!$unlockResult->isSuccess()) {
- $this->objDOrder->rollBack();
- Logger::logs(E_USER_ERROR, '编辑订单,库存解锁失败', __CLASS__, __LINE__, $unlockResult->getData());
- return ResultWrapper::fail($unlockResult->getData(), ErrorCode::$dberror);
- }
- $editResult = $objMOrderGoods->edit($params, $id,$orderIndex['no']);
- if (!$editResult->isSuccess()) {
- $this->objDOrder->rollBack();
- return ResultWrapper::fail($editResult->getData(), $editResult->getErrorCode());
- }
- }
- /*
- //跟新es
- $_id = self::createEsDocumentId($id);
- $this->objDOrder->esupdateTypeFieldVaule($updateOrder, $_id);*/
- if ($status){
- $this->objDOrder->commit();
- }
- return ResultWrapper::success(true);
- }
- /**
- * Doc: (des="代客下单,销售订单")
- * User: XMing
- * Date: 2020/12/19
- * Time: 2:38 下午
- * @param $params
- * @return ResultWrapper
- * @throws \Exception
- */
- public function add($params): ResultWrapper
- {
- $params['orderType'] = getArrayItem($params,'orderType',StatusCode::$orderType['saleOrder']);
- $goodsNameStr = self::createGoodsName($params['lists']);
- $commonParamsResult = self::formatCommonParams($params); // 格式化订单关联数据
- if (!$commonParamsResult->isSuccess()){
- return ResultWrapper::fail($commonParamsResult->getData(),$commonParamsResult->getErrorCode());
- }
- $params = $commonParamsResult->getData();
- $lists = $params['lists'];
- unset($params['lists']);
- $groupShopDataResult = self::buildGoodsByShop($lists,$params);
- if (!$groupShopDataResult->isSuccess()){
- return ResultWrapper::fail($groupShopDataResult->getData(),$groupShopDataResult->getErrorCode());
- }
- $shopGoodsData = $groupShopDataResult->getData();
- //锁定库存 查询商铺对应的仓库
- $objMShop = new MShop($this->onlineEnterpriseId, $this->onlineUserId);
- $modelResult = $objMShop->getShopDataByShopIds(array_column($shopGoodsData, 'shopId')); // 根据shopIds获取商铺数据
- if (!$modelResult->isSuccess()) {
- return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
- }
- $shopMap = $modelResult->getData();
- $buildGroupResult = self::groupSupplierOrderData($shopGoodsData,$params,$shopMap); // 将商品数据按照指定的字段分组
- if (!$buildGroupResult->isSuccess()){
- return ResultWrapper::fail($buildGroupResult->getData(),$buildGroupResult->getErrorCode());
- }
- $buildGroup = $buildGroupResult->getData();
- $insertOrderResult = self::insertOrder($buildGroup,$params);
- if (!$insertOrderResult->isSuccess()){
- return ResultWrapper::fail($insertOrderResult->getData(),$insertOrderResult->getErrorCode());
- }
- $orderIds = $insertOrderResult->getData();
- /* 拣货信息 */
- /* 功能临时屏蔽
- $orderNum = 0;
- $notOutNum = 0;
- $notPickingNum = 0;
- $otherNum = 0;
- foreach ($lists as $listKey => $listValue){
- $notOutNum = bcadd($notOutNum,$listValue['buyNum'],4);
- $notPickingNum = bcadd($notPickingNum,$listValue['buyNum'],4);
- $otherNum = bcadd($otherNum,$listValue['otherNum']);
- $orderNum = bcadd($orderNum,$listValue['buyNum']);
- }
- //组装订单拣货信息
- $orderPickingDate = [
- 'orderId' => $orderIds[0],
- 'sort' => 0,
- 'outNum' => 0,
- 'notOutNum' => $notOutNum,
- 'orderNum' => $orderNum,
- 'notPickingNum' => $notPickingNum,
- 'pickingNum' => 0,
- 'outTime' => 0,
- 'otherNum' => $otherNum,
- 'mangeId' => getArrayItem($params,'operatorId',0),
- 'mangeName' => getArrayItem($params,'operatorName',''),
- ];
- $objOrderPicking = new MOrderPicking($this->onlineUserId,$this->onlineEnterpriseId);
- $orderPickingResult = $objOrderPicking->addOrderPick($orderPickingDate); //临时注释
- if(!$orderPickingResult->isSuccess()){
- return ResultWrapper::fail($orderPickingResult->getData(), $orderPickingResult->getErrorCode());
- }*/
- parent::sendMessage($this->onlineEnterpriseId,'NewOrder');
- $params['orderType'] == StatusCode::$orderType['saleOrder'] && self::runProcessNextAudit($orderIds);
- return ResultWrapper::success($orderIds);
- }
- /**
- * Doc: (des="商品名称")
- * User: XMing
- * Date: 2020/11/18
- * Time: 3:27 下午
- * @param $goods
- * @return string
- */
- public static function createGoodsName($goods): string
- {
- $str = '';
- foreach ($goods as $val){
- if (isset($val['goodsName']) && !empty($val['goodsName'])){
- $str .= (string)$val['goodsName'].' ';
- }
- }
- return $str;
- }
- /**
- * Doc: (des="执行订单的下一步操作")
- * User: XMing
- * Date: 2020/11/6
- * Time: 5:03 下午
- * @param array $ids 订单ids
- * @return ResultWrapper
- * @throws \Exception
- */
- private function runProcessNextAudit(array $ids): ResultWrapper
- {
- Logger::logs(E_USER_ERROR,'订单自动审核',__CLASS__,__LINE__,$ids);
- if (empty($ids)){
- return ResultWrapper::success(true);
- }
- $setResult = $this->objMProcessSetting->getProcessSettingByType(StatusCode::$processType['sales'],'audit');
- if (!$setResult->isSuccess()){
- Logger::logs(E_USER_ERROR,'获取流程配置出错',__CLASS__,__LINE__,$setResult->getData());
- return ResultWrapper::fail($setResult->getData(),$setResult->getErrorCode());
- }
- $set = $setResult->getData();
- if (empty($set)){
- Logger::logs(E_USER_ERROR,'配置为空',__CLASS__,__LINE__,'');
- return ResultWrapper::success(true);
- }
- if (isset($set['enableStatus']) && $set['enableStatus'] == StatusCode::$standard){
- Logger::logs(E_USER_ERROR,'配置',__CLASS__,__LINE__,$set);
- return ResultWrapper::success(true);
- }
- foreach ($ids as $id){
- $params = [
- 'id' => $id,
- 'audit' => '自动审核',
- 'auditId' => $this->onlineUserId,
- 'auditStatus' => StatusCode::$auditStatus['auditPass'],
- ];
- $auditResult = $this->updateAuditStatus($params);
- if (!$auditResult->isSuccess()){
- Logger::logs(E_USER_ERROR,'自动审核订单出错',__CLASS__,__LINE__,$auditResult->getData());
- return ResultWrapper::fail($auditResult->getData(),$auditResult->getErrorCode());
- }
- }
- Logger::logs(E_USER_ERROR,'自动审核订单成功',__CLASS__,__LINE__,$ids);
- return ResultWrapper::success(true);
- }
- /**
- * Doc: (des="根据客户id获取客户信息")
- * User: XMing
- * Date: 2020/11/3
- * Time: 2:11 下午
- * @param int $id
- * @return ResultWrapper
- * @throws \Exception
- */
- private function getCustomerInfoByUserCenterId(int $id): ResultWrapper
- {
- $objMCustomer = new MCustomer($this->onlineEnterpriseId, $this->onlineUserId);
- //获取客户信息
- $customerData = $objMCustomer->getCustomerInfoByUserCenterId($id);
- if (!$customerData->isSuccess()) {
- return ResultWrapper::fail($customerData->getData(), $customerData->getErrorCode());
- }
- $customerData = $customerData->getData();
- if (empty($customerData)) {
- return ResultWrapper::fail('未获取到客户信息', ErrorCode::$paramError);
- }
- return ResultWrapper::success($customerData);
- }
- /**
- * Doc: (des="根据id查询自提点信息")
- * User: XMing
- * Date: 2020/11/3
- * Time: 11:49 上午
- * @param int $id
- * @return ResultWrapper
- * @throws \Exception
- */
- private function getSelfRuleData(int $id): ResultWrapper
- {
- $objMDeliverySetting = new MDeliverySetting($this->onlineUserId, $this->onlineEnterpriseId);
- $selfRuleDataResult = $objMDeliverySetting->getSelfRuleInfo($id);
- if (!$selfRuleDataResult->isSuccess()) {
- return ResultWrapper::fail($selfRuleDataResult->getData(), $selfRuleDataResult->getErrorCode());
- }
- $selfRuleData = $selfRuleDataResult->getData();
- $selfRuleData = isset($selfRuleData['setData']) ? $selfRuleData['setData'] : [];
- return ResultWrapper::success($selfRuleData);
- }
- /**
- * Doc: (des="根据id获取收货地址信息")
- * User: XMing
- * Date: 2020/11/3
- * Time: 11:52 上午
- * @param int $id
- * @return ResultWrapper
- */
- private function getAddressInfo($id): ResultWrapper
- {
- $objMShippingAddress = new MShippingAddress($this->onlineEnterpriseId);
- $result = $objMShippingAddress->getShippingAddressInfo($id);
- if (!$result->isSuccess()) {
- return ResultWrapper::fail($result->getData(), ErrorCode::$dberror);
- }
- $addressData = $result->getData();
- if (empty($addressData)) {
- return ResultWrapper::fail('未获取到收货地址信息', ErrorCode::$dberror);
- }
- return ResultWrapper::success($addressData);
- }
- /**
- * Doc: (des="小程序下单")
- * User: XMing
- * Date: 2020/12/18
- * Time: 11:39 上午
- * @param $params
- * @param $ip
- * @param $token
- * @param $auth
- * @return ResultWrapper
- * @throws \Exception
- */
- public function addOrder($params, $ip, $token, $auth): ResultWrapper
- {
- $goodsData = getArrayItem($params,'goodsData',[]);
- unset($params['goodsData']);
- $shopGoodsData = getArrayItem($goodsData,'goodsData',[]);//商品数据
- unset($goodsData['goodsData']);
- $common = array_merge($params,$goodsData);
- $params = $common;//公共数据
- unset($common);
- $params['token'] = $token;
- $params['auth'] = $auth;
- $params['orderType'] = StatusCode::$orderType['saleOrder'];
- $params['userCenterId'] = $this->onlineUserId;
- $params['orderStatus'] = StatusCode::$orderStatus['waitPay'];
- // 货到付款和银行打款 修改订单状态为待发货
- if( in_array($params['payType'],[StatusCode::$payType['cashPay']]) ){
- $params['orderStatus'] = StatusCode::$orderStatus['waitDelivery'];
- }
- $tmpOuterTradeNo = 'tmp' . createOrderSn($params['source'], StatusCode::$orderType['saleOrder'], $this->onlineUserId);
- $params['outerTradeNo'] = $tmpOuterTradeNo;
- // 格式化订单关联数据
- $commonParamsResult = self::formatCommonParams($params);
- if (!$commonParamsResult->isSuccess()){
- return ResultWrapper::fail($commonParamsResult->getData(),$commonParamsResult->getErrorCode());
- }
- $params = $commonParamsResult->getData();
- //查询商铺对应的仓库
- $objMShop = new MShop($this->onlineEnterpriseId, $this->onlineUserId);
- $modelResult = $objMShop->getShopDataByShopIds(array_column($shopGoodsData, 'shopId'));
- if (!$modelResult->isSuccess()) {
- return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
- }
- $shopMap = $modelResult->getData();
- // 将商品数据按照指定的字段分组
- $buildGroupResult = self::groupSupplierOrderData($shopGoodsData,$params,$shopMap);
- if (!$buildGroupResult->isSuccess()){
- return ResultWrapper::fail($buildGroupResult->getData(),$buildGroupResult->getErrorCode());
- }
- $buildGroup = $buildGroupResult->getData();
- //mysql写入数据
- $insertOrderResult = self::insertOrder($buildGroup,$params);
- if (!$insertOrderResult->isSuccess()){
- return ResultWrapper::fail($insertOrderResult->getData(),$insertOrderResult->getErrorCode());
- }
- $orderIds = $insertOrderResult->getData();
- // 处理支付
- $payResult = self::toPay($tmpOuterTradeNo,$params,$orderIds,$ip);
- if (!$payResult->isSuccess()){
- return ResultWrapper::fail($payResult->getData(),$payResult->getErrorCode());
- }
- // 发送新订单提醒
- // parent::sendMessage($this->onlineEnterpriseId,'NewOrder');
- $params['orderType'] == StatusCode::$orderType['saleOrder'] && self::runProcessNextAudit($orderIds);
- $customerData = $this->objDCustomer->get($buildGroup['orderIndex'][0]['customerId']);
- if ($customerData === false) {
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- if(isset($customerData['openId']) && !empty($customerData['openId'])){
- $orderData = $this->objDOrder->get($orderIds);
- if($orderData === false){
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- if( empty($orderData) ){
- return ResultWrapper::fail('查找不到该订单数据', ErrorCode::$contentNotExists);
- }
- foreach($buildGroup['order'] as $key => $value){
- // 发送小程序订阅消息
- $sendMessageData = [
- 'character_string6' => [ 'value' => StatusCode::$noPrefix[1].'-'.$key ], // 订单编号
- 'amount10' => [ 'value' => $value['payAmount'] ], // 订单金额
- 'thing15' => [ 'value' => $buildGroup['orderReceive'][$key]['realName'] ], // 收货人姓名
- 'phone_number16' => [ 'value' => $buildGroup['orderReceive'][$key]['mobile'] ], // 收货人电话
- 'phrase19' => [ 'value' => $orderData['payStatus'] == StatusCode::$delete ? '待支付':'已支付'], // 支付状态
- ];
- $objMSystemPushMessage = new MSystemPushMessage($this->onlineUserId, $this->onlineEnterpriseId);
- $result = $objMSystemPushMessage->sendWeiXinPushMessage(1, $customerData['openId'], $sendMessageData, '/pagesT/order/orderDetail?id='.array_pop($orderIds));
- if(!$result->isSuccess()){
- file_put_contents('/www/wwwroot/logs/api.junhailan.com/phperstar.log',date('Y-m-d H:i:s').'bb'.var_export($result->getData(),true).PHP_EOL,FILE_APPEND);
- }
- }
- }
- return ResultWrapper::success($payResult->getData());
- }
- /**
- * Doc: (des="支付")
- * User: XMing
- * Date: 2020/12/18
- * Time: 4:17 下午
- * @param string $tmpOuterTradeNo 临时订单号
- * @param array $params 公共参数
- * @param array $orderIds 所有订单号
- * @param $ip
- * @return ResultWrapper
- * @throws \Exception
- */
- public function toPay($tmpOuterTradeNo,$params,$orderIds,$ip): ResultWrapper
- {
- // 获取支付金额
- $payMoney = getArrayItem($params,'payMoney',0);
- if (empty($payMoney)){
- return ResultWrapper::fail('支付金额异常',ErrorCode::$paramError);
- }
- // 处理支付方式
- $payType = explode(',', $params['payType']);
- rsort($payType);
- $objSystemCache = new SystemCache();
- // 后台代客下单/货到付款/银行打款不需要返回支付配置
- if ( $params['source'] == StatusCode::$source['manage'] || in_array(StatusCode::$payType['cashPay'], $payType) ) {
- return ResultWrapper::success($orderIds);
- }
- $payment = [];
- $payParams = '';
- $payStatus = StatusCode::$partion;
- $orderStatus = StatusCode::$orderStatus['waitPay'];
- $notPayMoney = $payMoney;
- foreach($payType as $k => $v){
- //判断支付状态(有银行打款是5,没有直接给3)
- // 除了余额支付其他方式都要获取支付配置
- if($v != StatusCode::$payType['balance'] && $v != StatusCode::$payType['bankLoans']){
- $objMPaymentSetting = new MPaymentSetting($this->onlineUserId, $this->onlineEnterpriseId);
- $result = $objMPaymentSetting->getPayData($v);
- if (!$result->isSuccess() || empty($result->getData())) {
- return ResultWrapper::fail('获取微信配置错误', ErrorCode::$configEroor);
- }
- $payment = $result->getData();
- }
- switch (true){
- case in_array(StatusCode::$payType['balance'], $payType):
- //减少余额()
- $status = $this->objDOrderIndex->beginTransaction();
- //新增会员流水记录
- $memberBalanceDetailData = [
- 'customerId' => $params['id'],
- 'type' => StatusCode::$delete,
- 'userCenterId' => $this->onlineUserId,
- 'purpose' => '创建订单消费',
- 'orderIds' =>implode(',',$orderIds),
- 'remark' => '订单id'.implode(',',$orderIds),
- 'financeType' => '会员余额消费'
- ];
- // 组合支付方式
- if( !empty($params['admixPayData']) ) {
- foreach ($params['admixPayData'] as $key => $value) {
- if ($value['payType'] == StatusCode::$payType['balance']) {
- // 本次混合支付余额支付金额
- $memberBalanceDetailData['money'] = $value['payMoney'];
- // 总金额 - 余额支付金额 = 剩余需要搭配支付金额
- $payMoney = bcsub($payMoney, $value['payMoney'], 2);
- $notPayMoney = $payMoney;
- }
- }
- }else{
- $orderStatus = StatusCode::$orderStatus['waitDelivery'];
- $payStatus = StatusCode::$standard;
- $memberBalanceDetailData['money'] = $payMoney;
- $notPayMoney = 0;
- }
- $objMMemberBalanceDetail = new MMemberBalanceDetail($this->onlineEnterpriseId,$this->onlineUserId);
- $memberBalanceDbResult = $objMMemberBalanceDetail->addMemberBalanceDetail($memberBalanceDetailData);
- if (!$memberBalanceDbResult->isSuccess()) {
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($memberBalanceDbResult->getData(), $memberBalanceDbResult->getErrorCode());
- }
- // 查询余额对应的银行账户
- $defaultAccountResult = $this->objMAccount->getDefaultAccount(StatusCode::$payType['balance']);
- if ($defaultAccountResult->isSuccess() == false) {
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($defaultAccountResult->getData(), $defaultAccountResult->getErrorCode());
- }
- if(empty($defaultAccountResult->getData())){
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail('没有默认的'.StatusCode::$payType[$payType['balance']].'账户', ErrorCode::$notAllowAccess);
- }
- $defaultAccount = $defaultAccountResult->getData();
- //修改订单状态
- $time = time();
- $this->objDOrderIndex->setTable('qianniao_order_index_'.$this->onlineEnterpriseId);
- $fix = ceil($params['userCenterId'] / $this->cutTable);
- $this->objDOrder->setTable('qianniao_order_'.$this->onlineEnterpriseId.'_'.$fix);
- foreach ($orderIds as $orderId){
- $updateIndexResult = $this->objDOrderIndex->update(['payStatus' => $payStatus,'orderStatus' => $orderStatus,'updateTime' => $time],$orderId);
- if ($updateIndexResult === false){
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($this->objDOrderIndex->error(),ErrorCode::$dberror);
- }
- $updateIndex = $this->objDOrder->update(['payStatus' => $payStatus,'orderStatus' => $orderStatus,'payTime'=> $time,'updateTime' => $time,'notPayMoney'=>$notPayMoney],$orderId);
- if ($updateIndex === false){
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror);
- }
- $orderInfo = $this->objDOrder->get($orderId);
- if($orderInfo == false){
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- // 生成收款单
- $receivedData = [
- 'customerId' => $orderInfo['customerId'],
- 'customerName' => $orderInfo['customerName'],
- 'currentAccountName' => $orderInfo['shopName'],
- 'financeType' => '销售收款',
- 'financeTypeId' => StatusCode::$systemFinanceType['saleReceipt'],
- 'shopId' => $orderInfo['shopId'],
- 'shopName' => $orderInfo['shopName'],
- 'receiptTime' => time(),
- 'operatorId' => $this->onlineUserId,
- 'originId' => $orderId,
- 'originNo' => $orderInfo['no'],
- 'sourceId' => $orderId,
- 'sourceNo' => $orderInfo['no'],
- 'sourceNoMoney' => $orderInfo['totalMoney'], //原单据订单总金额
- 'auditStatus' => StatusCode::$auditStatus['auditing'],
- 'createTime' => time(),
- 'updateTime' => time(),
- 'accountList' => [
- [
- "accountId" => isset($defaultAccount['id']) ? $defaultAccount['id'] : 0,
- "accountNumber" => isset($defaultAccount['accountNumber']) ? $defaultAccount['accountNumber'] : '',
- 'accountName' => isset($defaultAccount['name']) ? $defaultAccount['name'] : '',
- "money" => $memberBalanceDetailData['money'],
- "discountMoney" => 0,
- "finalMoney" => $memberBalanceDetailData['money'],
- "payWay" => '余额支付',
- "remark" => "在线余额支付自动生成收款单"
- ]
- ],
- ];
- $result = $this->objMReceived->addReceived($receivedData, true);
- if ($result->isSuccess() == false) {
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($result->getData(), $result->getErrorCode());
- }
- unset($receivedData);
- unset($result);
- }
- // 根据客户id (customerId) 获取 openId
- if(!empty($orderInfo['customerId'])){
- $customerId = $orderInfo['customerId'];
- $objDCustomer = new DCustomer('default');
- $objDCustomer->setTable($objDCustomer->get_Table() . '_' . $this->onlineEnterpriseId);
- $customerData = $objDCustomer->get($customerId);
- if($customerData === false){
- return ResultWrapper::fail($objDCustomer->error(), ErrorCode::$dberror);
- }
- if( empty($customerData) ){
- return ResultWrapper::fail('查找不到该客户数据', ErrorCode::$contentNotExists);
- }
- // 小程序订阅消息
- if (isset($customerData['openId']) && !empty($customerData['openId'])) {
- // 发送小程序订阅消息
- $sendMessageData = [
- 'character_string3' => ['value' => StatusCode::$noPrefix[1] . '-' . $orderInfo['no']], // 订单编号
- 'date10' => ['value' => date('Y-m-d H:i:s', $orderInfo['createTime'])], // 下单时间
- 'time4' => ['value' => date('Y-m-d H:i:s', time())], // 支付时间
- 'thing7' => ['value' => '余额支付'], // 支付方式
- 'name8' => ['value' => substr($orderInfo['shopName'],0,30)] // 商家名称
- ];
- $objMSystemPushMessage = new MSystemPushMessage($this->onlineUserId, $this->onlineEnterpriseId);
- $result = $objMSystemPushMessage->sendWeiXinPushMessage(3, $customerData['openId'], $sendMessageData);
- if (!$result->isSuccess()) {
- file_put_contents('/www/wwwroot/logs/api.junhailan.com/systemPushMessage.log', date('Y-m-d H:i:s') . 'bb' . var_export($result->getData(), true) . PHP_EOL, FILE_APPEND);
- }
- }
- }
-
- $status && $this->objDOrderIndex->commit();
- $payParams = ResultWrapper::success(['code'=>100,'msg'=>'余额支付成功']);
- break;
- case in_array(StatusCode::$payType['aliPay'], $payType):
- //ali
- /*********读取支付宝支付参数(原配置)*********/
- /**$aliPayConfigData = Factory::config()->get('alipay');
- * if (empty($aliPayConfigData)) {
- * return ResultWrapper::fail('支付宝配置错误', ErrorCode::$configEroor);
- * }*/
- $payOrderData = [
- 'subject' => '千鸟云商',
- 'out_trade_no' => $tmpOuterTradeNo,
- 'total_amount' => $payMoney,
- 'passback_params' => $this->onlineEnterpriseId . '|' . $this->onlineUserId . '|' . implode('|', $orderIds),
- ];
- $aliPayConfigData = [
- 'appid' => $payment['appid'],
- 'rsaPrivateKey' => $payment['rsaPrivateKey'],
- 'alipayrsaPublicKey' => $payment['alipayrsaPublicKey'],
- ];
- $objAliPay = new aliPay($aliPayConfigData['appid'], $aliPayConfigData['rsaPrivateKey'], $aliPayConfigData['alipayrsaPublicKey']);
- $payParams = $objAliPay->appPay($payOrderData);
- break;
- case in_array(StatusCode::$payType['wxPay'], $payType):
- //wx
- /********************生成小程序唤起支付用到的参数(原配置)*****/
- /**$weixinConfigData = Factory::config()->get('weixin');
- * if (empty($weixinConfigData)) {
- * return ResultWrapper::fail('微信配置错误', ErrorCode::$configEroor);
- * }*/
- // 获取当前登录企业的小程序配置
- $miniprogramSetting = $objSystemCache->getAppIdByEnterpriseId($this->onlineEnterpriseId);
- if (empty($miniprogramSetting)) {
- return ResultWrapper::fail('后台小程序配置项为空', ErrorCode::$configEroor);
- }
- $miniprogramSetting = json_decode($miniprogramSetting, true);//获取小程序appid
- // 获取配置文件微信公众号
- $weixinConfigData = Factory::config()->getAppoint('weixin', 'offiaccount');
- switch ($params['source']) {
- case StatusCode::$source['weiXinBrowser'];
- if (empty($weixinConfigData)) {
- return ResultWrapper::fail('微信公众号配置错误', ErrorCode::$configEroor);
- }
- $appid = $weixinConfigData['appid'];
- $paySource = 'weiXinBrowser';
- break;
- case StatusCode::$source['H5'];
- if (empty($weixinConfigData)) {
- return ResultWrapper::fail('微信公众号配置错误', ErrorCode::$configEroor);
- }
- $appid = $weixinConfigData['appid'];
- $paySource = 'H5';
- break;
- case StatusCode::$source['miniProgram'];
- $appid = $miniprogramSetting['appid'];
- $paySource = 'miniProgram';
- break;
- default :
- $appid = $payment['mobileAppid'];
- $paySource = 'APP';
- break;
- }
- $weixinConfigData = [
- 'mch_id' => $payment['mchId'],
- 'apiPartnerKey' => $payment['apiPartnerKey'],
- 'appid' => $appid
- ];
- $attach = $this->onlineEnterpriseId . '|' . $this->onlineUserId . '|' . implode('|', $orderIds);
- //$objPay = new Pay($appid, $weixinConfigData['pay']['mch_id'], $weixinConfigData['pay']['apiPartnerKey']);//old
- //判断是否是子商户,优先选择子商户
- if(isset($payment['sub_mch_id']) && !empty($payment['sub_mch_id']) && $payMoney['mch_type'] == 2 ){
- $sub_mch_id = $payment['sub_mch_id'];
- $sub_weixinConfigData = Factory::config()->get('weixin');
- if (empty($sub_weixinConfigData)) {
- return ResultWrapper::fail('微信配置错误', ErrorCode::$configEroor);
- }
- $objPay = new Pay($appid, $sub_weixinConfigData['service_pay']['mch_id'], $sub_weixinConfigData['service_pay']['apiPartnerKey']);
- $payParams = $objPay->unifiedorder($tmpOuterTradeNo,$payMoney, $ip, $paySource, '千鸟云商', $params['openId'], $attach,$sub_mch_id);
- break;
- }
- $objPay = new Pay($appid, $weixinConfigData['mch_id'], $weixinConfigData['apiPartnerKey']);
- $payParams = $objPay->unifiedorder($tmpOuterTradeNo,$payMoney, $ip, $paySource, '千鸟云商', $params['openId'], $attach);
- break;
- case in_array(StatusCode::$payType['byte'],$payType):
- //字节跳动
- $mweb_url = '';
- //读取缓存配置
- //$objSystemCache->getByteDanceSetting($this->onlineEnterpriseId);
- // 获取配置文件字节小程序
- $byteDanceConfigData = Factory::config()->getAppoint('byteDance', 'pay');
- if (empty($byteDanceConfigData)) {
- return ResultWrapper::fail('字节跳动配置错误', ErrorCode::$configEroor);
- }
- $objbytePay = new bytePay($byteDanceConfigData['appid'], $byteDanceConfigData['merchant_id'], $byteDanceConfigData['app_secret']);
- unset($payParams);
- $payParams = $objbytePay->pay($tmpOuterTradeNo, $payMoney, '千鸟云商', $ip, $mweb_url);
- break;
- case in_array(StatusCode::$payType['bankLoans'], $payType):
- foreach ($orderIds as $orderId){
- $orderInfo = $this->objDOrder->get($orderId);
- if($orderInfo == false){
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- }
- // 根据客户id (customerId) 获取 openId
- if(!empty($orderInfo['customerId'])){
- $customerId = $orderInfo['customerId'];
- $objDCustomer = new DCustomer('default');
- $objDCustomer->setTable($objDCustomer->get_Table() . '_' . $this->onlineEnterpriseId);
- $customerData = $objDCustomer->get($customerId);
- if($customerData === false){
- return ResultWrapper::fail($objDCustomer->error(), ErrorCode::$dberror);
- }
- if( empty($customerData) ){
- return ResultWrapper::fail('查找不到该客户数据', ErrorCode::$contentNotExists);
- }
- // 小程序订阅消息
- if (isset($customerData['openId']) && !empty($customerData['openId'])) {
- // 发送小程序订阅消息
- $sendMessageData = [
- 'character_string3' => ['value' => StatusCode::$noPrefix[1] . '-' . $orderInfo['no']], // 订单编号
- 'date10' => ['value' => date('Y-m-d H:i:s', $orderInfo['createTime'])], // 下单时间
- 'time4' => ['value' => date('Y-m-d H:i:s', time())], // 支付时间
- 'thing7' => ['value' => '银行打款'], // 支付方式
- 'name8' => ['value' => substr($orderInfo['shopName'],0,30)] // 商家名称
- ];
- $objMSystemPushMessage = new MSystemPushMessage($this->onlineUserId, $this->onlineEnterpriseId);
- $result = $objMSystemPushMessage->sendWeiXinPushMessage(3, $customerData['openId'], $sendMessageData);
- if (!$result->isSuccess()) {
- file_put_contents('/www/wwwroot/logs/api.junhailan.com/systemPushMessage.log', date('Y-m-d H:i:s') . 'bb' . var_export($result->getData(), true) . PHP_EOL, FILE_APPEND);
- }
- }
- }
- $payParams = ResultWrapper::success($orderIds);
- break;
- default:
- //TODO
- return ResultWrapper::fail('暂未开放的支付方式',ErrorCode::$paramError);
- break;
- }
- unset($payType[$k]);
- if (!$payParams->isSuccess()) {
- return ResultWrapper::fail($payParams->getData(), $payParams->getErrorCode());
- }
- }
- return ResultWrapper::success($payParams->getData());
- }
- /**
- * Doc: (des="已审核未出库订单,审核驳回")
- * User: XMing
- * Date: 2021/2/25
- * Time: 9:41 上午
- * @param int $orderId
- * @return ResultWrapper
- * @throws \Exception
- */
- public function revokeAudit(int $orderId): ResultWrapper
- {
- $orderIndex = $this->objDOrderIndex->get($orderId);
- if ($orderIndex === false) {
- return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
- }
- if (empty($orderIndex)) {
- return ResultWrapper::fail('未获取到指定订单', ErrorCode::$paramError);
- }
- $fix = ceil((empty($params['userCenterId']) ? 1 : $params['userCenterId']) / $this->cutTable);
- $this->objDOrder->setTable('qianniao_order_'.$this->onlineEnterpriseId.'_'.$fix);
- $orderData = $this->objDOrder->get($orderId);
- if ($orderData === false){
- return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror);
- }
- if (empty($orderData)){
- return ResultWrapper::fail('为获取到指定的订单信息',ErrorCode::$paramError);
- }
- if ($orderData['auditStatus'] != StatusCode::$auditStatus['auditPass']){
- return ResultWrapper::fail('订单审核状态异常,不能驳回',ErrorCode::$paramError);
- }
- if ($orderData['outStatus'] != StatusCode::$delete){
- return ResultWrapper::fail('订单已经出库,不能驳回',ErrorCode::$paramError);
- }
- if ($orderData['orderStatus'] == StatusCode::$orderStatus['close']){
- return ResultWrapper::fail('订单已关闭,不嫩驳回',ErrorCode::$paramError);
- }
- $this->objDOrderIndex->beginTransaction();
- $time = time();
- //update order
- $updateOrder = $this->objDOrder->update([
- 'auditStatus' => StatusCode::$auditStatus['auditing'],
- 'updateTime' => $time,
- 'revokeTime' => $time
- ],$orderId);
- if ($updateOrder === false){
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror);
- }
- //update orderIndex
- $updateOrderIndex = $this->objDOrderIndex->update([
- 'auditStatus' => StatusCode::$auditStatus['auditing'],
- 'updateTime' => $time
- ],$orderId);
- if ($updateOrderIndex === false){
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror);
- }
- //update stock
- $objMInventoryOut = new MInventoryOut($this->onlineEnterpriseId,$this->onlineUserId);
- $stockOutResult = $objMInventoryOut->delInventoryOutStatus([
- 'sourceId' => $orderId,
- 'type' => StatusCode::$orderType['saleOut']
- ]);
- if (!$stockOutResult->isSuccess()){
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($stockOutResult->getData(),$stockOutResult->getErrorCode());
- }
- // 删除已生成的收款单
- $objDReceivedIndex = new DReceivedIndex('finance');
- $objDReceivedIndex->setTable('qianniao_received_index_' . $this->onlineEnterpriseId);
- $deleteReceive = $objDReceivedIndex->delete(['sourceId'=>$orderIndex['id']]);
- if ($deleteReceive === false) {
- return ResultWrapper::fail($objDReceivedIndex->error(), ErrorCode::$dberror);
- }
- /*
- //update es
- $_id = self::createEsDocumentId($orderId);
- $this->objDOrder->esupdateTypeFieldVaule([
- 'auditStatus' => StatusCode::$auditStatus['auditing'],
- 'updateTime' => $time
- ], $_id);*/
- $this->objDOrderIndex->commit();
- return ResultWrapper::success(true);
- }
- /**
- * Doc: (des="")
- * User: XMing
- * Date: 2021/3/9
- * Time: 5:13 下午
- * @param int $orderId
- * @return ResultWrapper
- * @throws \Exception
- */
- public function reStockOut(int $orderId): ResultWrapper
- {
- // 获取订单索引表数据
- $orderIndex = $this->objDOrderIndex->get($orderId);
- if ($orderIndex === false){
- return ResultWrapper::fail($this->objDOrderIndex->error(),ErrorCode::$dberror);
- }
- if (empty($orderIndex)){
- return ResultWrapper::fail('未获取到指定地订单信息',ErrorCode::$paramError);
- }
- // 获取订单数据
- $fix = ceil($orderIndex['userCenterId'] / $this->cutTable);
- $this->objDOrder->setTable('qianniao_order_'.$this->onlineEnterpriseId.'_'.$fix);
- $orderData = $this->objDOrder->get($orderId);
- if ($orderData === false){
- return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror);
- }
- if (empty($orderData)){
- return ResultWrapper::fail('未获取到指定的订单信息',ErrorCode::$paramError);
- }
- if ($orderData['outStatus'] == StatusCode::$standard){
- return ResultWrapper::fail('订单已经出库,请不要重复出库',ErrorCode::$paramError);
- }
- // 查询销售订单是否还有未审核的出库单,必须先处理完,再生成新的出库单
- $objMInventoryOut = new MInventoryOut($this->onlineEnterpriseId,$this->onlineUserId);
- $condition = [
- 'originId' => $orderData['id'],
- 'deleteStatus' => StatusCode::$standard,
- 'auditStatus' => StatusCode::$auditStatus['auditing'],
- ];
- $result = $objMInventoryOut->getInventoryOutData($condition);
- if (!$result->isSuccess()) {
- return ResultWrapper::fail($result->getData(), ErrorCode::$dberror);
- }
- $inventoryOutData = $result->getData();
- if( !empty($inventoryOutData) ){
- return ResultWrapper::fail('当前销售订单还有未审核的出库单,单号:'.StatusCode::$noPrefix[5].'-'.$inventoryOutData[0]['no'].',请先处理完成', ErrorCode::$notAllowAccess);
- }
- // 查询订单商品表数据
- $this->objDOrderGoods->setTable('qianniao_order_goods_'.$this->onlineEnterpriseId.'_'.$fix);
- $orderGoodsData = $this->objDOrderGoods->select(['orderId' => $orderId,'deleteStatus' => StatusCode::$standard]);
- if ($orderGoodsData === false){
- return ResultWrapper::fail($this->objDOrderGoods->error(),ErrorCode::$dberror);
- }
- if (empty($orderGoodsData)){
- return ResultWrapper::fail('订单商品获取失败',ErrorCode::$paramError);
- }
- // 组装出库单数据
- $saleOutData = [
- 'sourceId' => $orderData['id'],
- 'sourceNo' => $orderData['no'],
- 'originNo' => $orderData['no'],
- 'originId' => $orderData['id'],
- 'shopId' => $orderData['shopId'],
- 'shopName' => $orderData['shopName'],
- 'amount' => $orderData['payAmount'],
- 'operatorId' => $orderData['auditId'],//操作人id
- 'operatorName' => $orderData['audit'],//操作人信息
- 'customerId' => $orderData['customerId'],
- 'customerName' => $orderData['customerName'],
- 'customerCode' => createCode(StatusCode::$code['customer']['prefix'], $orderData['customerId'], StatusCode::$code['customer']['length']),
- 'customerMobile' => $orderData['customerMobile'],
- 'source' => StatusCode::$orderType['saleOrder'], //订单来源(出库类型)
- 'type' => StatusCode::$orderType['saleOut'],
- 'deliveryType' => $orderData['deliveryType'],//配送方式
- 'remark' => $orderData['remark'],
- ];
- $saleOutData['materielNum'] = 0;
- //获取sku
- $objMSku = new MSku($this->onlineUserId, $this->onlineEnterpriseId);
- $skuIds = array_column(array_values($orderGoodsData), 'skuId');
- $modelResult = $objMSku->getSkuDataBySkuIds($skuIds);
- if (!$modelResult->isSuccess()) {
- return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
- }
- $skuData = $modelResult->getData();
- unset($modelResult);
- foreach ($orderGoodsData as $key => $value) {
- if ($value['outOfNum'] > 0 && $value['isEq'] == StatusCode::$delete){
- $saleOutData['materielNum']++;
- $totalMoney = bcsub(bcsub($value['totalMoney'], $value['vipDiscount']), $value['preferential']);//销售总价 !优惠后
- $saleOutData['orderGoodsData'][] = [
- 'materielId' => $value['goodsBasicId'],
- 'materielName' => $value['goodsName'],
- 'materielCode' => createCode(StatusCode::$code['goodsBasic']['prefix'], $value['goodsBasicId'], StatusCode::$code['goodsBasic']['length']),
- 'skuId' => $value['skuId'],
- 'num' => $value['outOfNum'],
- 'otherNum' => $value['otherNum'],
- 'outNum' => 0,
- 'total' => $value['outOfNum'],
- 'unitName' => isset($value['unitName']) ? $value['unitName'] : '',
- 'skuName' => isset($skuData[$value['skuId']]) ? $skuData[$value['skuId']]['skuName'] : '',
- 'unitPrice' => $value['price'],//单价 不优惠
- 'totalPrice' => $totalMoney,//销售总价 !优惠后
- ];
- }
- }
- if (empty($saleOutData['orderGoodsData'])){
- return ResultWrapper::fail('此订单没有需要出库的商品',ErrorCode::$paramError);
- }
- // 新增出库单
- $dbResult = $objMInventoryOut->addInventoryOut($saleOutData);
- if (!$dbResult->isSuccess()){
- return ResultWrapper::fail($dbResult->getData(),$dbResult->getErrorCode());
- }
- return ResultWrapper::success($dbResult->getData());
- }
- /**
- * Doc: (des="")
- * User: XMing
- * Date: 2021/3/18
- * Time: 6:55 下午
- * @param int $orderId
- * @return ResultWrapper
- * @throws \Exception
- */
- public function retAmount(int $orderId)
- {
- $message = '退款成功';
- // 从订单索引表查询订单数据
- $orderIndex = $this->objDOrderIndex->get($orderId);
- if ($orderIndex === false){
- return ResultWrapper::fail($this->objDOrderIndex->error(),ErrorCode::$dberror);
- }
- if (empty($orderIndex)){
- return ResultWrapper::fail('未获取到订单数据',ErrorCode::$paramError);
- }
- // 从订单和订单商品查询订单数据
- $fix = ceil($orderIndex['userCenterId'] / $this->cutTable);
- $this->objDOrder->setTable('qianniao_order_'.$this->onlineEnterpriseId.'_'.$fix);
- $this->objDOrderGoods->setTable('qianniao_order_goods_'.$this->onlineEnterpriseId.'_'.$fix);
- $order = $this->objDOrder->get($orderId);
- if ($order === false){
- return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror);
- }
- if ( empty($order) ){
- return ResultWrapper::fail('未获取到指定订单信息',ErrorCode::$paramError);
- }
- $sql = 'SELECT * FROM qianniao_order_goods_'.$this->onlineEnterpriseId.'_'.$fix.' WHERE orderId = '.$orderId.' AND deleteStatus = '.StatusCode::$standard.' AND outOfNum > 0';
- $rows = $this->objDOrderGoods->query($sql);
- if ($rows === false){
- return ResultWrapper::fail($this->objDOrderGoods->error(),ErrorCode::$dberror);
- }
- if (empty($rows)){
- return ResultWrapper::fail('未获取到指定订单的商品信息',ErrorCode::$paramError);
- }
- // 根据实际订单未出库数量计算退款金额
- $receiveMoney = 0;
- foreach ($rows as $row){
- if ($row['outOfNum'] <= 0) continue;
- $receiveMoney = bcadd($receiveMoney,bcmul($row['price'],$row['outOfNum'], 4),4);
- }
- // 保留4位判断金额是否异常
- if ($receiveMoney <= 0){
- return ResultWrapper::fail('退款金额异常',ErrorCode::$paramError);
- }
- $receiveMoney = bcadd($receiveMoney, '0', 2); // 实际退款保留两位
- $status = $this->objDOrder->beginTransaction();
- $payType = explode(',', $orderIndex['payType']);
- // 未支付订单不生成退款单
- if( $order['payStatus'] == StatusCode::$standard){
- // 小于1分钱不做退款处理
- if ($receiveMoney >= 0.01){
- // 根据订单支付方式规划退款账户
- $objMAccount = new MAccount($this->onlineEnterpriseId,$this->onlineUserId);
- // 包含余额组合支付方式统一返回余额,其他原路返回
- if( in_array(StatusCode::$payType['balance'],$payType) ){
- $financeAccountData = $objMAccount->getDefaultAccount(StatusCode::$payType['balance']);
- }else if( in_array(StatusCode::$payType['bankLoans'],$payType) ){
- $extends = json_decode($order['extends'], true);
- if( isset($extends['bankData']['id']) && !empty($extends['bankData']['id'])){
- $accountId = $extends['bankData']['id'];
- //获取银行打款账户信息
- $financeAccountData = $objMAccount->getAccountInfo($accountId);
- }else{
- $financeAccountData = ResultWrapper::fail('获取打款账户错误');
- }
- } else{
- $financeAccountData = $objMAccount->getDefaultAccount($payType);
- }
- if(!$financeAccountData->isSuccess()){
- return ResultWrapper::fail($financeAccountData->getData(), $financeAccountData->getErrorCode());
- }
- $financeAccountData = $financeAccountData->getData();
- //记录负应收的id
- //$financeRefundData['offsetId'] = (int)$addReceiveResult->getData();
- // 生成财务退款单
- $financeRefundData = [
- 'originId' => getArrayItem($order,'id',0),
- 'originNo' => getArrayItem($order,'no',''),
- 'sourceId' => getArrayItem($order,'id',0),
- 'sourceNo' => getArrayItem($order,'no',''),
- 'refundTime' => time(),
- 'createTime' => time(),
- 'unitId' => getArrayItem($order,'customerId',0),
- 'unitName' => getArrayItem($order,'customerName',0),
- 'currentAccountName' => getArrayItem($order,'customerName',''),
- 'financeType' => '订单完结退款',
- 'financeTypeId' => 1,
- 'payType' =>getArrayItem($order,'payType',''),
- 'shopId' => getArrayItem($order,'shopId',0),
- 'shopName' => getArrayItem($order,'shopName',0),
- 'money' => $receiveMoney,
- 'operatorId' => $this->onlineUserId,
- 'type' => StatusCode::$standard,
- 'auditStatus' => StatusCode::$auditStatus['auditing'],
- 'remark' => '订单一键完结,订单编号:'. getArrayItem($order,'no','').'完结后需退款金额:'.$receiveMoney
- ];
- $financeRefundData['accountList'] = [
- [
- 'accountId' => $financeAccountData['id'],
- 'accountNumber' => $financeAccountData['accountNumber'],
- 'accountName' => $financeAccountData['name'],
- 'money' => $receiveMoney,
- ]
- ];
- $objMRefund = new MRefund($this->onlineEnterpriseId,$this->onlineUserId);
- $result = $objMRefund->addRefund($financeRefundData);
- if(!$result->isSuccess()){
- $this->objDOrder->rollBack();
- return ResultWrapper::fail($result->getData(),$result->getErrorCode());
- }
- // 应收自动审核队列
- //Factory::cache('finance')->zadd('salesOutReceive::'.$this->onlineEnterpriseId, time(), $addReceiveResult->getData());
- }else{
- $message = '退款金额少于0.01,不做退款处理,退款成功';
- }
- }
- $updateIndexData = [
- 'updateTime' => time(),
- 'isRet' => StatusCode::$standard,
- ];
- $updateOrderIndex = $this->objDOrderIndex->update($updateIndexData, $orderId);
- if ($updateOrderIndex === false){
- $this->objDOrder->rollBack();
- return ResultWrapper::fail($this->objDOrderIndex->error(),ErrorCode::$dberror);
- }
- $update = [
- 'updateTime' => time(),
- 'retTime' => time(),
- 'retMoney' => $receiveMoney,
- 'isRet' => StatusCode::$standard,
- ];
- $updateOrder = $this->objDOrder->update($update,$orderId);
- if ($updateOrder === false){
- $this->objDOrder->rollBack();
- return ResultWrapper::fail($this->objDOrderIndex->error(),ErrorCode::$dberror);
- }
- //订单解锁
- $objMInventory = new MInventory($this->onlineEnterpriseId, $this->onlineUserId);
- $unlockResult = $objMInventory->unlockInventory([$orderId], StatusCode::$orderType['saleOrder'], $orderIndex['createTime']);
- if (!$unlockResult->isSuccess()) {
- $this->objDOrder->rollBack();
- return ResultWrapper::fail($unlockResult->getData(), ErrorCode::$dberror);
- }
- $status && $this->objDOrder->commit();
- return ResultWrapper::success($message);
- }
- /**
- * Doc: (des="创建分销")
- * User: XMing
- * Date: 2020/7/29
- * Time: 6:41 下午
- * @param string $token
- * @param string $auth
- * @param int $customerId
- * @param int $orderId
- */
- private function taskCreateCommission(string $token, string $auth, int $customerId, int $orderId)
- {
- $i = 1;
- do {
- $postData = [
- 'topicName' => 'MyJob',
- 'topicClass' => 'Jobs\Model\MTopic\Order\MCommissionOrder',
- 'topicMethon' => 'push',
- 'topicMethonParams' => [
- 'Authorization' => $auth,
- 'Token' => $token,
- 'orderId' => $orderId,
- 'customerId' => $customerId,
- 'PROJECT_DOMAIN' => PROJECT_DOMAIN
- ],
- ];
- $url = QIANNIAO_QUEUE . '/CAddJob/add';
- $result = request($url, $postData);
- $i++;
- } while ($result['httpcode'] != 200 && $i <= 3);
- Logger::logs(E_USER_ERROR, '投递任务成功', __CLASS__, __LINE__, $postData);
- }
- /**
- * Doc: (des="修改订单的退货状态")
- * User: XMing
- * Date: 2020/7/14
- * Time: 3:54 下午
- * @param $params
- * @return ResultWrapper
- * @throws \Exception
- */
- public function editOrder($params)
- {
- if (empty($params['id'])) {
- return ResultWrapper::fail('没有订单id', ErrorCode::$paramError);
- }
- $id = $params['id'];
- unset($params['id']);
- $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId);
- $orderIndex = $this->objDOrderIndex->get(['id' => $id], 'userCenterId');
- if ($orderIndex === false) {
- return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
- }
- $this->objDOrderIndex->beginTransaction();
- $updateResult = $this->objDOrderIndex->update([
- 'updateTime' => $params['updateTime'],
- 'returnStatus' => $params['returnStatus'],
- ], ['id' => $id]);
- if ($updateResult === false) {
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
- }
- $tableNum = ceil($orderIndex['userCenterId'] / $this->cutTable);
- $this->objDOrder->setTable('qianniao_order_' . $this->onlineEnterpriseId . '_' . $tableNum);
- $dbResult = $this->objDOrder->update([
- 'updateTime' => $params['updateTime'],
- 'returnStatus' => $params['returnStatus'],
- ], $id);
- if ($dbResult === false) {
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- $this->objDOrderIndex->commit();
- /*//修改es数据
- $_id = self::createEsDocumentId($id);
- $this->objDOrder->esupdateTypeFieldVaule(['returnStatus' => $params['returnStatus'], 'updateTime' => $params['updateTime']], $_id);*/
- return ResultWrapper::success($dbResult);
- }
- /**
- * 更新ES
- * @param $orderId
- * @param $order
- * @param $addressData
- * @param $addOrderGoodsName
- * @param int $userCenterId
- */
- public function updateEsData($orderId, $order, $addressData, $addOrderGoodsName, $userCenterId = 0)
- {
- $orderEsData = [
- /*订单表信息*/
- 'id' => $orderId,//订单编号,
- 'no' => $order['no'],//订单编号,
- 'outerTradeNo' => '',//'外部流水号(支付宝/微信返回的流水号)'
- 'shopId' => $order['shopId'],
- 'shopName' => $order['shopName'],
- 'enterpriseId' => $this->onlineEnterpriseId,
- 'userCenterId' => $userCenterId != 0 ? $userCenterId : $this->onlineUserId,
- 'totalMoney' => $order['totalMoney'],
- 'payAmount' => $order['payAmount'],
- 'buyTotal' => isset($order['buyTotal']) ? $order['buyTotal'] : 0,//购买总数
- 'customerName' => $order['customerName'],//客户姓名
- 'customerId' => $order['customerId'],//客户id
- 'customerType' => isset($order['customerType']) ? $order['customerType'] : 0,//客户类型
- 'payStatus' => StatusCode::$delete,//'支付状态 默认4 未支付 5已支付'
- 'orderStatus' => StatusCode::$orderStatus['waitPay'],//订单状态 默认1 创建 2待支付 3代发货 4待收货 5已完成 6已关闭
- 'payType' => $order['payType'],//'支付方式 1微信 2支付宝 3货到付款 4上门自提'
- 'deliveryType' => $order['deliveryType'],//'配送方式 1商品配送 2上门自提'
- 'source' => $order['source'],//订单来源 默认1 ios 2android 3小程序 4后台创建
- 'remark' => $order['remark'],//订单备注
- 'auditStatus' => $order['auditStatus'],// '审核状态 默认1 待审 2审核通过 3 审核未通过 4 审核中'
- //'payTime' => '',//'付款时间'
- 'createTime' => $order['createTime'],//'创建时间'
- 'updateTime' => $order['updateTime'],//'修改时间',
- 'salesManId' => isset($order['salesManId']) ? $order['salesManId'] : 0,
- 'salesManName' => isset($order['salesManName']) ? $order['salesManName'] : '',
- 'returnStatus' => StatusCode::$orderReturn['notReturn'],
- 'outStatus' => StatusCode::$delete,
- 'verifyCode' => $order['verifyCode'],//核销码
- /*收货人信息*/
- 'realName' => isset($addressData['realName']) ? $addressData['realName'] : '',//收货人姓名
- 'mobile' => isset($addressData['mobile']) ? $addressData['mobile'] : '',//收货人电话
- 'address' => isset($addressData['address']) ? $addressData['address'] : '',//收货详细地址
- 'provinceCode' => isset($addressData['provinceCode']) ? $addressData['provinceCode'] : '',//收货人省份编码
- 'cityCode' => isset($addressData['cityCode']) ? $addressData['cityCode'] : '',//收货人城市编码
- 'districtCode' => isset($addressData['districtCode']) ? $addressData['districtCode'] : '',//收货人区编码
- /*优惠信息*/
- 'preferential' => $order['preferential'],//优惠券优惠金额
- 'vipDiscount' => $order['vipDiscount'],//会员卡优惠金额
- 'vipDoubleDiscount' => $order['vipDoubleDiscount'],//会员卡折上折优惠金额
- /*商品信息*/
- 'goodsName' => $addOrderGoodsName,
- 'orderType' => isset($order['orderType']) ? $order['orderType'] : StatusCode::$orderType['salesSlip'],
- ];
- isset($order['salesManName']) && $orderEsData['salesManName'] = $order['salesManName'];
- $_id = self::createEsDocumentId($orderId);
- $result = $this->objDOrder->addUpSearchIndexDocument($orderEsData, $_id);
- if (isset($result['_shards']) && isset($result['_shards']['successful']) && $result['_shards']['successful'] == 1) {
- //echo "es操作成功";
- //return;
- }
- //echo "es操作失败";
- }
- /**
- * 创建文档id
- *
- * @param $orderId
- * @return string
- */
- private function createEsDocumentId($orderId)
- {
- return 'EnterpriseId_' . $this->onlineEnterpriseId . '_OrderId_' . $orderId;
- }
- /**
- * Doc: (des="获取订单创建时间,用于其它业务计算分表使用")
- * User: XMing
- * Date: 2020/12/25
- * Time: 2:16 下午
- * @param $orderId
- * @return ResultWrapper
- * @throws \Exception
- */
- public function getOrderCreateTime($orderId)
- {
- $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId);
- $orderIndexRes = $this->objDOrderIndex->get_by('id', $orderId);
- if ($orderIndexRes === false) {
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- if (empty($orderIndexRes)) {
- return ResultWrapper::fail('未找到订单信息', ErrorCode::$paramError);
- }
- return ResultWrapper::success($orderIndexRes);
- }
- /**
- * Doc: (des="获取订单详情")
- * User: XMing
- * Date: 2020/7/14
- * Time: 6:25 下午
- * @param $id
- * @return ResultWrapper
- * @throws \Exception
- */
- public function getOrderInfoById($id): ResultWrapper
- {
- $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId);
- $orderIndexRes = $this->objDOrderIndex->get_by('id', $id);
- if ($orderIndexRes === false) {
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- if (empty($orderIndexRes)) {
- return ResultWrapper::fail('未找到订单信息', ErrorCode::$paramError);
- }
- //切换分表
- self::orderSubTable($this->onlineEnterpriseId, $orderIndexRes['userCenterId']);
- $dbResult = $this->objDOrder->get_by('id', $id);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- $formatData = self::format($dbResult);
- if (!$formatData->isSuccess()){
- return ResultWrapper::fail($formatData->getData(),$formatData->getErrorCode());
- }
- $dbResult = $formatData->getData();
- //添加订单打印的数据
- $printResult = self::printInfo($dbResult);
- if (!$printResult->isSuccess()){
- return ResultWrapper::fail($printResult->getData(),$printResult->getErrorCode());
- }
- $dbResult = $printResult->getData();
- //logisticsData
- $dbResult['logisticsData'] = json_decode($dbResult['logisticsData'],true);
- // 查询订单退货对应退货单的状态
- if($dbResult['returnStatus']){
- $objMOrderReturn = new MOrderReturn($this->onlineEnterpriseId, $this->onlineUserId);
- $result = $objMOrderReturn->getAuditStatusByOrderId($id);
- $dbResult['returnAuditStatus'] = StatusCode::$auditStatus['auditing'];
- if($result->isSuccess()){
- $dbResult['returnAuditStatus'] = $result->getData();
- }
- }
- return ResultWrapper::success($dbResult);
- }
- /**
- * 补充打印订单字段信息
- *
- * @param $dbResult
- * @return ResultWrapper
- * @throws \Exception
- */
- public function printInfo($dbResult)
- {
- if ($dbResult['source'] == StatusCode::$source['manage']){
- $dbResult['receivable'] = $dbResult['totalMoney'];//应收
- }else{
- $dbResult['receivable'] = $dbResult['payAmount'];//应收
- }
- if ($dbResult['payType'] == StatusCode::$payType['cashPay']
- || $dbResult['payType'] == StatusCode::$payType['bankLoans']
- ) {
- //货到付款 已支付 = payAmount金额
- if ($dbResult['source'] == StatusCode::$source['manage']){
- $dbResult['netReceipts'] = isset($dbResult['receivedMoney']) ? $dbResult['receivedMoney'] : 0;
- }else{
- if ($dbResult['payStatus'] == StatusCode::$standard) {
- $dbResult['netReceipts'] = $dbResult['payAmount'];//实收
- } else {
- $dbResult['netReceipts'] = 0;//实收
- }
- }
- } else {
- //在线支付 已支付 = payAmount金额
- if ($dbResult['payStatus'] == StatusCode::$standard) {
- $dbResult['netReceipts'] = $dbResult['payAmount'];//实收
- } else {
- $dbResult['netReceipts'] = 0;//实收
- }
- }
- $dbResult['currentShortage'] = bcsub($dbResult['receivable'], $dbResult['netReceipts'], 2);//本单欠
- $dbResult['upOwe'] = $dbResult['customerOwe'];//上欠
- $dbResult['totalDeficit'] = bcadd($dbResult['currentShortage'], $dbResult['upOwe'], 2);
- $objMShop = new MShop($this->onlineEnterpriseId, $this->onlineUserId);
- $shopData = $objMShop->getShopInfo(['id' => $dbResult['shopId']]);
- if (!$shopData->isSuccess()) {
- return ResultWrapper::fail($shopData->getData(),$shopData->getErrorCode());
- } else {
- $shopData = $shopData->getData();
- }
- $dbResult['shopAddress'] = isset($shopData['area']) ? $shopData['area'] : [];
- $dbResult['shopMobile'] = isset($shopData['mobile']) ? $shopData['mobile'] : '';
- $dbResult['shopDescribe'] = isset($shopData['describe']) ? $shopData['describe'] : '';
- $dbResult['partnerPhone'] = isset($shopData['mobile']) ? $shopData['mobile'] : '';//合伙人联系电弧
- $objMAccount = new MAccount($this->onlineEnterpriseId,$this->onlineUserId);
- $accountName = '';
- if ($dbResult['payType'] == StatusCode::$payType['wxPay'] || $dbResult['payType'] == StatusCode::$payType['aliPay']){
- $accountResult = $objMAccount->getDefaultAccount($dbResult['payType']);
- if (!$accountResult->isSuccess()){
- return ResultWrapper::fail($accountResult->getData(),$accountResult->getErrorCode());
- }
- $account = $accountResult->getData();
- $accountName = isset($account['name']) ? $account['name'] : '';
- }else{
- $account = isset($dbResult['accountList']) ? array_shift($dbResult['accountList']) : [];
- $accountName = isset($account['accountName']) ? $account['accountName'] : '';
- }
- $dbResult['accountName'] = $accountName;//收款账户
- $pbjMPrintNum = new MPrintNum($this->onlineEnterpriseId);
- $dbResult['printingNum'] = $pbjMPrintNum->getObjectPrintNum($dbResult['no'], $dbResult['orderType']);
- return ResultWrapper::success($dbResult);
- }
- /**
- * 检索导出(ES)
- *
- * @param $dsl
- * @return ResultWrapper
- * @throws \Exception
- */
- private function exportSearch($dsl)
- {
- $result = $this->objDOrder->getScrollSearchQueryDsl($dsl);
- if (isset($result['status']) && $result['status'] == 400) {
- return ResultWrapper::fail('获取数据失败' . $result['error']['reason'], ErrorCode::$apiNotResult);
- }
- if (!isset($result['hits']) && $result['hits']['total'] == 0) {
- return ResultWrapper::fail('导出数据为空' . $result['error']['reason'], ErrorCode::$apiNotResult);
- }
- $dbResult = $result['hits']['hits'];
- $list = [];
- foreach ($dbResult as $key => &$value) {
- $data = [];
- $data = $value['_source'];
- $list[] = $data;
- }
- self::exportOrder($list, 'es');
- }
- /**
- * 导出方法
- *
- * @param $allOrderData
- */
- private static function export($allOrderData)
- {
- //导出到本地
- header("Content-type:application/vnd.ms-excel");
- header("Content-Disposition:filename=订单记录.csv");
- header('Cache-Control: max-age=0');
- $fp = fopen('php://output', 'a');
- $head = ['ID', '订单编号', '下单时间', '客户名称', '收货人', '业务员', '联系电话', '订单金额', '订单状态', '收款状态', '配送方式', '订单来源', '订单审核']; //定义标题
- foreach ($head as $i => $v) {
- $head[$i] = mb_convert_encoding($v, 'GBK', 'utf-8'); //将中文标题转换编码,否则乱码
- }
- fputcsv($fp, $head);
- $limit = 10000;
- $num = 0;//计数器
- foreach ($allOrderData as $v) {
- //循环数据
- $num++;
- if ($num == $limit) {
- ob_flush();//释放内存
- flush();
- }
- $rows['id'] = $v['id'];
- $rows['no'] = $v['no'];
- $rows['createTime'] = date('Y-m-d H:i:s', $v['createTime']);
- $rows['customerName'] = $v['customerName'];
- $rows['realName'] = $v['realName'];
- $rows['salesManName'] = $v['salesManName'];
- $rows['mobile'] = $v['mobile'];
- $rows['payAmount'] = $v['payAmount'];
- $rows['orderStatus'] = StatusCode::$orderStatus[$v['orderStatus']];
- $rows['payStatus'] = StatusCode::$standard == $v['payStatus'] ? '已支付' : '未支付';
- $rows['deliveryType'] = ($v['deliveryType'] != StatusCode::$deliveryType['goodsDelivery'] && $v['deliveryType'] != StatusCode::$deliveryType['selfMention']) ? '' : StatusCode::$deliveryType[$v['deliveryType']];
- $rows['source'] = StatusCode::$source[$v['source']];
- $rows['auditStatus'] = StatusCode::$auditStatus[$v['auditStatus']];
- foreach ($rows as $kk => $vv) {
- $rs[$kk] = mb_convert_encoding($vv, 'GBK', 'utf-8'); //转译编码
- }
- fputcsv($fp, $rs);
- $rows = [];
- }
- exit;
- }
- /**
- * 导出列表(数据库)
- *
- * @param string $sql
- * @return ResultWrapper
- * @throws \Exception
- */
- public function exportAllOrder(string $sql)
- {
- $objDOrderIndex = new DOrderIndex();
- $dbResult = $objDOrderIndex->query($sql);
- if ($dbResult === false) {
- return ResultWrapper::fail($objDOrderIndex->error(), ErrorCode::$dberror);
- }
- $allOrderData = [];
- $allGroupData = [];
- foreach ($dbResult as $key => $val) {
- $tableNum = (int)ceil($val['userCenterId'] / $this->cutTable);
- //这里感觉没有必要使用对主索引表的订单id进行分组,可以通过条件直接查询表下的数据
- $allGroupData[$tableNum][] = $val['id'];
- }
- $fields = 'o.id,o.no,o.createTime,o.customerName,o.salesManName,o.payAmount,o.orderStatus,o.payStatus,o.source,o.deliveryType,o.auditStatus,r.realName,r.mobile';
- foreach ($allGroupData as $k => $orderId) {
- $this->objDOrder->setTable('qianniao_order_' . $this->onlineEnterpriseId . '_' . $k);
- $sql = 'SELECT ' . $fields . ' FROM qianniao_order_' . $this->onlineEnterpriseId . '_' . $k . ' AS o LEFT JOIN qianniao_order_receive_' . $this->onlineEnterpriseId . '_' . $k . ' AS r ON o.id=r.orderId WHERE o.id IN(' . implode(',', $orderId) . ') ORDER BY o.createTime DESC';
- $dbResult = $this->objDOrder->query($sql);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- $allOrderData = array_merge($dbResult, $allOrderData);
- }
- self::export($allOrderData);
- }
- /**
- * Doc: (des="订单导出,构建查询数据")
- * User: XMing
- * Date: 2020/8/22
- * Time: 10:25 上午
- * @param array|string $data
- * @param string $field
- * @return ResultWrapper
- */
- private function buildSelectGroupDataByCondition($data, string $field)
- {
- switch ($field) {
- case 'db':
- $result = self::getAllOrderIdsBySql($data);
- break;
- case 'es':
- $result = self::getAllOrderIdsBySearchResult($data);
- break;
- }
- if (!$result->isSuccess()) {
- return ResultWrapper::fail($result->getData(), $result->getErrorCode());
- }
- return ResultWrapper::success($result->getData());
- }
- /**
- * Doc: (des="将es检索数据,进行数据分组转化为统一格式")
- * [[表后缀]=>[订单id,]]
- * User: XMing
- * Date: 2020/8/22
- * Time: 10:15 上午
- * @param array $data
- * @return ResultWrapper
- */
- private function getAllOrderIdsBySearchResult(array $data)
- {
- if (empty($data)) {
- return ResultWrapper::success([]);
- }
- $groupMapRes = self::buildGroupMapByArray((array)$data);
- if (!$groupMapRes->isSuccess()) {
- return ResultWrapper::fail($groupMapRes->getData(), $groupMapRes->getErrorCode());
- }
- return ResultWrapper::success($groupMapRes->getData());
- }
- /**
- * Doc: (des="")
- * User: XMing
- * Date: 2020/8/22
- * Time: 10:18 上午
- * @param array $data
- * @return ResultWrapper
- */
- private function buildGroupMapByArray(array $data)
- {
- if (empty($data)) {
- return ResultWrapper::success([]);
- }
- $allGroupMap = [];
- //对所有数据进行分组,[[表后缀]=>[订单id,]]
- foreach ($data as $key => $val) {
- $tableNum = (int)ceil($val['userCenterId'] / $this->cutTable);
- //这里感觉没有必要使用对主索引表的订单id进行分组,可以通过条件直接查询表下的数据
- $allGroupMap[$tableNum][] = $val['id'];
- }
- return ResultWrapper::success($allGroupMap);
- }
- /**
- * Doc: (des="通过sql,进行数据分组转化为统一格式")
- * [[表后缀]=>[订单id,]]
- * User: XMing
- * Date: 2020/8/22
- * Time: 9:55 上午
- * @param string $sql
- * @return ResultWrapper
- */
- private function getAllOrderIdsBySql(string $sql)
- {
- if (empty($sql)) {
- return ResultWrapper::success([]);
- }
- $list = $this->objDOrderIndex->exportQuery($sql);
- if ($list === false) {
- return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
- }
- $list = self::getGeneratorData($list);
- if (empty($list)) {
- return ResultWrapper::success([]);
- }
- $groupMapRes = self::buildGroupMapByArray((array)$list);
- if (!$groupMapRes->isSuccess()) {
- return ResultWrapper::fail($groupMapRes->getData(), $groupMapRes->getErrorCode());
- }
- return ResultWrapper::success($groupMapRes->getData());
- }
- /**
- * Doc: (des="获取export查询方法返回的数据集合")
- * User: XMing
- * Date: 2020/8/22
- * Time: 11:42 上午
- * @param $object
- * @return array
- */
- private static function getGeneratorData($object)
- {
- $arrayList = [];
- foreach ($object as $value) {
- $arrayList[] = $value;
- }
- return $arrayList;
- }
- /**
- * Doc: (des="格式化导出数据,统一根据订单id格式化数据")
- * User: XMing
- * Date: 2020/8/22
- * Time: 9:44 上午
- * @param array|string $data
- * @param string $source
- * @return ResultWrapper
- * @throws \Exception
- */
- private function exportOrder($data, string $source)
- {
- if (empty($data)) {
- return ResultWrapper::success([]);
- }
- $groupMapRes = self::buildSelectGroupDataByCondition($data, $source);
- if (!$groupMapRes->isSuccess()) {
- return ResultWrapper::fail($groupMapRes->getData(), $groupMapRes->getErrorCode());
- }
- $groupMap = $groupMapRes->getData();
- if (empty($groupMap)) {
- return ResultWrapper::fail('导出数据构建失败', ErrorCode::$paramError);
- }
- //查询需要导出的数据
- $orderFields = '*';
- $orderReceiveFields = '*';
- $orderGoodsFields = '*';
- $allOrderData = [];//订单集
- $allOrderReceiveData = [];//订单收货地址集
- $allOrderGoodsData = [];//订单商品信息
- foreach ($groupMap as $k => $orderIds) {
- //订单表
- $this->objDOrder->setTable('qianniao_order_' . $this->onlineEnterpriseId . '_' . $k);
- $orderResult = $this->objDOrder->exportSelect(['id' => $orderIds], $orderFields, 'createTime desc');//查询订单
- if ($orderResult === false) {
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- $orderResult = self::getGeneratorData($orderResult);
- //订单收货表
- $this->objDOrderReceive->setTable('qianniao_order_receive_' . $this->onlineEnterpriseId . '_' . $k);
- $orderReceiveResult = $this->objDOrderReceive->exportSelect(['orderId' => $orderIds], $orderReceiveFields, 'createTime desc');//订单收货
- if ($orderReceiveResult === false) {
- return ResultWrapper::fail($this->objDOrderReceive->error(), ErrorCode::$dberror);
- }
- $orderReceiveResult = self::getGeneratorData($orderReceiveResult);
- //订单商品表
- $this->objDOrderGoods->setTable('qianniao_order_goods_' . $this->onlineEnterpriseId . '_' . $k);
- $orderGoodsResult = $this->objDOrderGoods->exportSelect(['orderId' => $orderIds], $orderGoodsFields, 'createTime desc');
- if ($orderGoodsResult === false) {
- return ResultWrapper::fail($this->objDOrderGoods->error(), ErrorCode::$dberror);
- }
- $orderGoodsResult = self::getGeneratorData($orderGoodsResult);
- //对数据进行合并
- $allOrderData = array_merge($orderResult, $allOrderData);
- $allOrderReceiveData = array_merge($orderReceiveResult, $allOrderReceiveData);
- $allOrderGoodsData = array_merge($orderGoodsResult, $allOrderGoodsData);
- }
- $formatResult = self::formatManageOrderList($allOrderData, $allOrderReceiveData, $allOrderGoodsData);
- if (!$formatResult->isSuccess()) {
- return ResultWrapper::fail($formatResult->getData(), $formatResult->getErrorCode());
- }
- $exportData = $formatResult->getData();
- if (empty($exportData)) {
- return ResultWrapper::fail('构建导出数据为空', ErrorCode::$paramError);
- }
- //将数据导出
- self::exportCsv($exportData);
- }
- /**
- * Doc: (des="")
- * User: XMing
- * Date: 2020/8/22
- * Time: 2:24 下午
- * @param array $area
- * @param string $address
- * @return string
- */
- private static function createAddress($area, $address)
- {
- $str = '';
- if (isset($area['provinceName']) && !empty($area['provinceName'])) {
- $str .= $area['provinceName'];
- }
- if (isset($area['cityName']) && !empty($area['cityName'])) {
- $str .= $area['cityName'];
- }
- if (isset($area['districtName']) && !empty($area['districtName'])) {
- $str .= $area['districtName'];
- }
- $str .= $address;
- return $str;
- }
- /**
- * Doc: (des="生成规格名字")
- * User: XMing
- * Date: 2020/8/22
- * Time: 2:47 下午
- * @param array $specGroup
- * @return string
- */
- private static function createSpecName($specGroup)
- {
- if(empty($specGroup)){
- return "无";
- }
- $str = '';
- foreach ($specGroup as $value) {
- empty($str) && $str .= ' ';
- $str .= $value['specName'] . ':';
- $str .= $value['specValueName'];
- }
- return $str;
- }
- /**
- * Doc: (des="将数据导出到表格")
- * User: XMing
- * Date: 2020/8/22
- * Time: 11:09 上午
- * @param array $data
- */
- private function exportCsv(array $data)
- {
-
- //导出到本地
- header("Content-type:application/vnd.ms-excel");
- header("Content-Disposition:filename=订单记录.csv");
- header('Cache-Control: max-age=0');
- $fp = fopen('php://output', 'a');
- $head = ['ID', '订单编号', '订单金额', '优惠金额', '付款金额', '订单状态', '支付方式', '付款状态','配送方式','订单来源','审核状态','下单时间','客户名称','收货人','收货人电话','收货人地址','所属店铺', '业务员','件数','商品编码','商品名称','单位','属性','数量','销售单价(元)','销售总价'];//定义标题
- foreach ($head as $i => $v) {
- $head[$i] = mb_convert_encoding($v, 'GBK', 'utf-8'); //将中文标题转换编码,否则乱码
- }
- fputcsv($fp, $head);
- $limit = 10000;
- $num = 0;//计数器
- $rows = [];
- foreach ($data as $v) {
- //循环数据
- $num++;
- if ($num == $limit) {
- ob_flush();//释放内存
- flush();
- }
- foreach ($v['goodsData'] as $index => $item) {
- self::buildExportData($rows, $v, $item, $index);
- foreach ($rows as $kk => $vv) {
- $rs[$kk] = mb_convert_encoding($vv, 'GBK', 'utf-8'); //转译编码
- }
- fputcsv($fp, $rs);
- $rows = [];
- }
- }
- exit;
- }
- /**
- * Doc: (des="")
- * User: XMing
- * Date: 2020/8/22
- * Time: 3:28 下午
- * @param array $rows
- * @param array $v
- * @param array $item
- * @param int $index
- */
- private static function buildExportData(&$rows, array $v, array $item, int $index)
- {
- $rows['id'] = '';
- $rows['no'] = '';
- $rows['totalMoney'] = '';
- $rows['subMoney'] = '';
- $rows['payMoney'] = '';
- $rows['orderMsg'] = '';
- $rows['payTypeMsg'] = '';
- $rows['payMsg'] = '';
- $rows['deliveryMsg'] = '';
- $rows['sourceMsg'] = '';
- $rows['auditMsg'] = '';
- $rows['createTime'] = '';
- $rows['customerName'] = '';
- $rows['receiveName'] = '';
- $rows['receiveMobile'] = '';
- $rows['receiveAddress'] = '';
- $rows['shopName'] = '';
- $rows['salesManName'] = '';
- $rows['otherNum'] = '';
- $rows['id'] = $v['id'];
- $rows['no'] = $v['no'];
- $rows['totalMoney'] = $v['totalMoney'];
- $rows['subMoney'] = bcsub($v['payAmount'], $v['totalMoney'], 2);
- $rows['payMoney'] = $v['payAmount'];
- $rows['orderMsg'] = $v['orderMsg'];
- $rows['payTypeMsg'] = $v['payTypeMsg'];
- $rows['payMsg'] = $v['payMsg'];
- $rows['deliveryMsg'] = $v['deliveryMsg'];
- $rows['sourceMsg'] = $v['sourceMsg'];
- $rows['auditMsg'] = $v['auditMsg'];
- $rows['createTime'] = date('Y-m-d H:i:s', $v['createTime']);
- $rows['customerName'] = $v['customerName'];
- $rows['receiveName'] = $v['receiveData']['realName'];
- $rows['receiveMobile'] = $v['receiveData']['mobile'];
- $rows['receiveAddress'] = self::createAddress($v['receiveData']['area'], $v['receiveData']['address']);
- $rows['shopName'] = $v['shopName'];
- $rows['salesManName'] = $v['salesManName'];
- $rows['goodsCode'] = $item['goodsCode'];
- $rows['goodsName'] = $item['goodsName'];
- $rows['unitName'] = $item['unitName'];
- $rows['specName'] = self::createSpecName((isset($item['specGroup']) && !empty($item['specGroup'])) ? json_decode($item['specGroup'], true) : []);
- $rows['buyNum'] = $item['buyNum'];
- $rows['unitPrice'] = $item['price'];
- $rows['totalPrice'] = $item['totalMoney'];
- $rows['otherNum'] = $item['otherNum'];
- }
- /**
- * 获取所有订单
- *
- * @param $selectParams
- * @param $search
- * @param bool $is_export
- * @return ResultWrapper
- * @throws \Exception
- * @waitAudit:等待审核 orderStatus != 6 auditStatus = 1
- * @waitOutStock:待出库 orderStatus != 6 auditPass = 2
- * @hasOutStock:已出库 orderStatus = 4 auditPass = 2
- * @finish:已完成 orderStatus = 5 auditPass 2
- * @close:已关闭 orderStatus = 6
- *
- * 新订单列表 {"page":1,"pageSize":10,"search":{"auditStatus":1}}
- * 订单查询 {"page":1,"pageSize":10,"search":{"auditStatus":2}} 订单查询:此页面只展示新订单审核后的订单,订单状态为【待出库】,订单出库后,页面会显示出【确认收货】的按钮,订单在出库管理进行出库后,订单状态为【已出库】,客户或后台操作【确认收货】后,订单状态为【已完成】。
- * 自提订单 {"page":1,"pageSize":10,"search":{"deliveryType":2}}
- * 取消订单 {"page":1,"pageSize":10,"search":{"orderStatus":6}}
- *
- */
- public function getAllOrder($selectParams, $search, $is_export = false)
- {
- $objDOrderIndex = new DOrderIndex();
- $selectParams = array_merge($selectParams, $search);
- // 组装检索sql语句
- $buildSql = self::setOrderStatusSqlAttr($selectParams);
- $sql = $buildSql['sql'];
- if ($is_export === true) self::exportOrder($sql, 'db');//导出数据
- $total = $objDOrderIndex->query($buildSql['countSql']);
- if (isset($selectParams['limit']) && isset($selectParams['offset'])) {
- $sql .= ' limit ' . $selectParams['offset'] . ',' . $selectParams['limit'];
- }
- $dbResult = $objDOrderIndex->query($sql);
- if ($dbResult === false) {
- return ResultWrapper::fail($objDOrderIndex->error(), ErrorCode::$dberror);
- }
- $allOrderData = [];//订单集
- $allOrderReceiveData = [];//订单收货地址集
- $allGroupData = [];
- if (!empty($dbResult)) {
- foreach ($dbResult as $key => $val) {
- $tableNum = ceil($val['userCenterId'] / $this->cutTable);
- $allGroupData[$tableNum][] = $val['id'];
- }
- foreach ($allGroupData as $k => $orderId) {
- $this->objDOrder->setTable('qianniao_order_' . $this->onlineEnterpriseId . '_' . $k);
- $dbResult = $this->objDOrder->select(['id' => $orderId], '*', 'createTime desc');//查询订单
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- //物流信息展示
- if( !empty($dbResult['logisticsData']) ){
- json_decode($dbResult['logisticsData'],true);
- }
- $this->objDOrderReceive->setTable('qianniao_order_receive_' . $this->onlineEnterpriseId . '_' . $k);
- $orderReceiveResult = $this->objDOrderReceive->select(['orderId' => $orderId], '*', 'createTime desc');//订单收货
- if ($orderReceiveResult === false) {
- return ResultWrapper::fail($this->objDOrderReceive->error(), ErrorCode::$dberror);
- }
- $allOrderData = array_merge($dbResult, $allOrderData);//订单集
- $allOrderReceiveData = array_merge($orderReceiveResult, $allOrderReceiveData);//订单收货地址集
- }
- }
- // 格式化后台订单列表
- $formatResult = self::formatManageOrderList($allOrderData, $allOrderReceiveData);
- if (!$formatResult->isSuccess()) {
- return ResultWrapper::fail($formatResult->getData(), $formatResult->getErrorCode());
- }
- $return = [
- 'data' => $formatResult->getData(),
- 'total' => isset($total[0]['total']) ? $total[0]['total'] : 0,
- ];
- return ResultWrapper::success($return);
- }
-
- /**
- * Doc: (des="获取检索订单数据")
- *订单列表搜索商品名称、商品编码、收货人、电话
- * @waitAudit:等待审核 orderStatus != 6 auditStatus = 1
- * @waitOutStock:待出库 orderStatus != 6 auditPass = 2
- * @hasOutStock:已出库 orderStatus = 4 auditPass = 2
- * @finish:已完成 orderStatus = 5 auditPass 2
- * @close:已关闭 orderStatus = 6
- * @param $export
- * @param $selectParams
- */
- public function keywordSearch($selectParams,$export = '')
- {
- // 组装检索sql
- $whereSql = '';
- if(!empty($selectParams['keywordType']) && !empty($selectParams['keyword'])){
- $whereSql = self::assemblySql($selectParams['keywordType'],$selectParams['keyword']);
- }
- $orderTab ='qianniao_order_'.$this->onlineEnterpriseId.'_'.'1';
- $orderGoodsTab ='qianniao_order_goods_'.$this->onlineEnterpriseId.'_'.'1';
- $orderReceive ='qianniao_order_receive_'.$this->onlineEnterpriseId.'_'.'1';
- // 初始化表
- $this->objDOrder->setTable($orderTab);
- $this->objDOrder->setTable($orderGoodsTab);
- $this->objDOrder->setTable($orderReceive);
- $condition = '';
- $limit = '';
- if(!$export){
- if (isset($selectParams['limit']) && isset($selectParams['offset'])) {
- $limit .= ' limit ' . $selectParams['offset'] . ',' . $selectParams['limit'];
- }
- }
-
- // 时间筛选
- if (isset($selectParams['startTime']) && !empty($selectParams['startTime'])){
- $condition .= ' AND o.createTime BETWEEN '.$selectParams['startTime'].' AND '.$selectParams['endTime'];
- }
- //userCenterId
- if (isset($selectParams['userCenterId']) && !empty($selectParams['userCenterId'])) {
- $condition .= ' and o.userCenterId = ' . $selectParams['userCenterId'];
- }
-
- //customerId
- if (isset($selectParams['customerId']) && !empty($selectParams['customerId'])) {
- $condition .= ' and o.customerId = ' . $selectParams['customerId'];
- }
- //shopId
- if (isset($selectParams['shopId']) && !empty($selectParams['shopId'])) {
- $condition .= ' and o.shopId = ' . $selectParams['shopId'];
- }
- // 付款状态 支付状态 默认4 未支付 5已支付
- if (isset($selectParams['payStatus']) && !empty($selectParams['payStatus'])) {
- $condition .= ' and o.payStatus = ' . $selectParams['payStatus'];
- }
-
- //支付方式
- if (isset($selectParams['payType']) && !empty($selectParams['payType'])) {
- $condition .= ' and find_in_set('.$selectParams['payType'].',o.payType) ';
- }
- // 客户类型
- if (isset($selectParams['customerType']) && !empty($selectParams['customerType'])){
- $condition .= ' AND o.customerType = '.$selectParams['customerType'];
- }
- // 订单来源 订单来源 默认1 ios 2android 3小程序 4后台创建
- if (isset($selectParams['source']) && !empty($selectParams['source'])){
- $condition .= ' AND o.source = '.$selectParams['source'];
- }
-
- //出库状态
- if (isset($selectParams['outStatus']) && !empty($selectParams['outStatus'])) {
- $condition .= ' and o.outStatus = ' . $selectParams['outStatus'];
- }
- //退货状态
- if (isset($selectParams['returnStatus']) && !empty($selectParams['returnStatus'])) {
- if (is_array($selectParams['returnStatus'])) {
- $returnStatusStr = implode(',', $selectParams['returnStatus']);
- $condition .= ' and o.returnStatus in(' . $returnStatusStr . ') ';
- } else {
- $condition .= ' and o.returnStatus = ' . $selectParams['returnStatus'];
- }
- }
-
- //订单状态
- if (isset($selectParams['state']) && !empty($selectParams['state'])) {
- $condition = self::orderStateSql($condition, $selectParams['state']);
- }
- if($export){
- $sql ='SELECT o.*,g.goodsCode,g.goodsName,g.unitName,g.specGroup,g.buyNum,g.price,g.otherNum,g.preferential,g.totalMoney,r.realName, r.mobile,r.provinceCode,r.cityCode,r.districtCode,r.address FROM '.$orderTab.' AS o LEFT JOIN '.$orderGoodsTab.' as g ON o.id =g.orderId LEFT JOIN '.$orderReceive.' AS r on o.id= r.orderId WHERE o.deleteStatus='.StatusCode::$standard.$whereSql.$condition.' order by o.id desc ';
-
- $orderGoodsData = $this->objDOrder->exportQuery($sql);
- if ($orderGoodsData === false) {
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- $result = self::exportOrderList($orderGoodsData);
- exit;
- }
- $sql ='SELECT o.* FROM '.$orderTab.' AS o LEFT JOIN '.$orderGoodsTab.' as g ON o.id =g.orderId LEFT JOIN '.$orderReceive.' AS r on o.id= r.orderId WHERE o.deleteStatus='.StatusCode::$standard.$whereSql.$condition.' GROUP BY o.id order by o.createTime desc '.$limit;
- $dbResult = $this->objDOrder->query($sql);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- // 格式化后台订单列表
- $formatResult = self::formatManageOrderList($dbResult,[]);
- if (!$formatResult->isSuccess()) {
- return ResultWrapper::fail($formatResult->getData(), $formatResult->getErrorCode());
- }
- $sqlTotal ='SELECT count( DISTINCT o.id) as total FROM '.$orderTab.' AS o LEFT JOIN '.$orderGoodsTab.' as g ON o.id =g.orderId LEFT JOIN '.$orderReceive.' AS r on o.id= r.orderId WHERE o.deleteStatus='.StatusCode::$standard.$whereSql.$condition;
- $total = $this->objDOrder->query($sqlTotal);
- if ($total === false) {
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
-
- $return = [
- 'data' => $formatResult->getData(),
- 'total' => isset($total[0]['total']) ? $total[0]['total'] : 0,
- ];
-
- return ResultWrapper::success($return);
- }
- /**
- * 获取检索订单数据导出
- * @param $orderListData
- * @return ResultWrapper
- */
- public function exportOrderList($orderListData)
- {
-
- //导出到本地
- header("Content-type:application/vnd.ms-excel");
- header("Content-Disposition:filename=订单管理.csv");
- header('Cache-Control: max-age=0');
- $fp = fopen('php://output', 'a');
- $head = ['ID', '订单编号', '订单金额', '订单金额', '付款金额', '订单状态', '支付方式', '付款状态','配送方式','订单来源','审核状态','下单时间','客户名称','收货人','收货人电话','收货人地址','所属店铺', '业务员','件数','商品编码','商品名称','单位','属性','数量','销售单价(元)','优惠金额','销售总价'];//定义标题
- foreach ($head as $i => $v) {
- $head[$i] = mb_convert_encoding($v, 'GBK', 'utf-8'); //将中文标题转换编码,否则乱码
- }
- fputcsv($fp, $head);
-
- $limit = 10000;
- $num = 0;//计数器
- foreach ($orderListData as $value) {//循环数据
- $orderReceiveData[]= [
- 'orderId' => $value['id'],
- 'provinceCode' => $value['provinceCode'],
- 'cityCode' => $value['cityCode'],
- 'districtCode' => $value['districtCode'],
- 'allAddress' => $value['allAddress']
- ];
- // 格式化后台订单列表
- $fromatValue = self::formatManageOrderList([$value],$orderReceiveData);
- if (!$fromatValue->isSuccess()) {
- echo($fromatValue->getData());
- exit();
- }
- $fromatValue = array_pop($fromatValue->getData());
- $value = array_merge($value, $fromatValue);
-
- $num++;
- if ($num == $limit) {
- ob_flush();//释放内存
- flush();
- }
- $rows['id'] = isset($value['id']) ? $value['id'] : null; // ID
- $rows['no'] = isset($value['no']) ? $value['no'] : null; // 订单编号
- $rows['totalMoney'] = isset($value['totalMoney']) ? $value['totalMoney'] : null; // 订单金额
- $rows['subMoney'] = isset($value['payAmount']) && isset($value['totalMoney']) ? bcsub($value['payAmount'], $value['totalMoney'], 2): 0; // 订单金额
- $rows['payAmount'] = isset($value['payAmount']) ? $value['payAmount'] : null; // 付款金额
- $rows['orderMsg'] = isset($value['orderMsg']) ? $value['orderMsg'] : null; // 订单状态
- $rows['payTypeMsg'] = isset($value['payTypeMsg']) ? $value['payTypeMsg'] : null; // 支付方式
- $rows['payMsg'] = isset($value['payMsg']) ? $value['payMsg'] : null; // 付款状态
- $rows['deliveryMsg'] = isset($value['deliveryMsg']) ? $value['deliveryMsg'] : null; // 配送方式
- $rows['sourceMsg'] = isset($value['sourceMsg']) ? $value['sourceMsg'] : null; // 订单来源
- $rows['auditMsg'] = isset($value['auditMsg']) ? $value['auditMsg'] : null; // 审核状态
- $rows['createTime'] = isset( $value['createTime']) ? date('Y-m-d H:i:s', $value['createTime']) : null; // 下单时间
- $rows['customerName'] = isset($value['customerName']) ? $value['customerName'] : null; // 客户名称
- $rows['receiveName'] = isset($value['realName']) ? $value['realName']: null; // 收货人
- $rows['receiveMobile'] = isset($value['mobile']) ? $value['mobile'] : null; // 收货人电话
- $rows['receiveAddress'] = isset($value['receiveData']['allAddress']) ? $value['receiveData']['allAddress'] : null;// '收货人地址'
- $rows['shopName'] = isset($value['shopName']) ? $value['shopName'] : null; // ,'所属店铺',
- $rows['salesManName'] = isset($value['salesManName']) ? $value['salesManName'] : null; // '业务员'
- $rows['otherNum'] = getArrayItem($value, 'otherNum', 0); //件数
- $rows['goodsCode'] = getArrayItem($value, 'goodsCode'); // '商品编码'
- $rows['goodsName'] = getArrayItem($value, 'goodsName'); // '商品名称
- $rows['unitName'] = getArrayItem($value, 'unitName'); // 单位
- $rows['specName'] = self::createSpecName((isset($value['specGroup']) && !empty($value['specGroup'])) ? json_decode($value['specGroup'], true) : []);
- $rows['buyNum'] = getArrayItem($value, 'buyNum', 0);
- $rows['unitPrice'] = getArrayItem($value, 'price', 0);
- $rows['preferential'] = getArrayItem($value, 'preferential', 0);
- $rows['totalPrice'] = getArrayItem($value, 'totalMoney', 0); // '销售单价(元)'
-
- foreach ($rows as $kk => $vv) {
- $rs[$kk] = mb_convert_encoding($vv, 'GBK', 'utf-8'); //转译编码
- }
- fputcsv($fp, $rs);
- $rows = [];
- }
- }
- /**
- * 根据订单列表 keywordType 拼装sql
- * @param $keywordType
- * @param $keyword
- */
- public function assemblySql($keywordType,$keyword)
- {
- $whereSql = '';
- switch ($keywordType){
- case 1: // 单据编号 order
- if(strpos($keyword,StatusCode::$noPrefix[1]) !== false){
- $orderNo = explode('-',$keyword);
- if(count($orderNo)==3){
- $orderNo = $orderNo[1].'-'.$orderNo[2];
- }elseif(count($orderNo)==2){
- $orderNo = $orderNo[1];
- }else{
- $orderNo = $keyword;
- }
-
- $whereSql .= ' and o.no = "'.$orderNo.'"';
- }else{
- $whereSql .= ' and o.no = "'.$keyword.'"';
- }
-
- break;
- case 2: // 自提码 order
- $whereSql .= ' and o.verifyCode ="'.$keyword.'"';
- break;
- case 3: // 商品名称 order_goods
- $whereSql .=' and g.goodsName LIKE "%' .$keyword. '%" ';
- break;
- case 4: // 商品编码 order_goods
- $whereSql .=' and g.goodsCode ="'.$keyword.'"';
- break;
- case 5: // 收货人 order_receive
- $whereSql .=' and r.realName LIKE "%' .$keyword. '%" ';
- break;
- case 6: // 电话 order_receive
- $whereSql .=' and r.mobile ="'.$keyword.'"';
- break;
- case 7: // 业务员 order
- $whereSql .=' and o.salesManName LIKE "%' .$keyword. '%" ';
- break;
- case 8: // 详细地址 order_receive
- $whereSql .=' and r.address LIKE "%' .$keyword. '%" ';
- }
- return $whereSql;
- }
-
- /**
- * Doc: (des="state标示多选sql处理")
- *
- */
- private static function orderStateSql($sql, $states)
- {
- if (is_array($states)) {
- if (in_array('all', $states)) {
- return $sql;
- }
- foreach ($states as $index => $state) {
- $sql .= $index == 0 ? ' and (' . self::orderstate($state) : ' or ' . self::orderstate($state);
- }
- $sql .= ') ';
- } else {
- if ($states == 'all') {
- return $sql;
- }
- $stateSql = self::orderstate($states);
- if (!empty($stateSql)) {
- $sql .= ' and ' . self::orderstate($states);
- }
- }
- return $sql;
- }
-
- /**
- * Doc: (des="state标示对应sql")
- */
- private static function orderstate($state)
- {
- $sql = '';
- switch ($state) {
- case 'waitAudit'://待审核
- $sql .= ' (o.auditStatus = ' . StatusCode::$auditStatus['auditing'] . ' and o.orderStatus != ' . StatusCode::$orderStatus['close'] . ')';
- break;
- case 'waitOutStock'://待出库
- $sql .= ' (o.auditStatus = ' . StatusCode::$auditStatus['auditPass'] . ' and (o.orderStatus = ' . StatusCode::$orderStatus['waitPay'] . ' or orderStatus = ' . StatusCode::$orderStatus['waitDelivery'] . ')) ';
- break;
- case 'hasOutStock'://已出库
- $sql .= ' (o.auditStatus = ' . StatusCode::$auditStatus['auditPass'] . ' and o.orderStatus = ' . StatusCode::$orderStatus['waitReceive'] . ')';
- break;
- case 'finish'://已完成
- $sql .= ' (o.auditStatus = ' . StatusCode::$auditStatus['auditPass'] . ' and o.orderStatus = ' . StatusCode::$orderStatus['finish'] . ')';
- break;
- case 'close'://已关闭
- $sql .= ' (o.orderStatus = ' . StatusCode::$orderStatus['close'] . ')';
- break;
- case 'all'://全部订单
- break;
- }
- return $sql;
- }
-
- /**
- * Doc: (des="格式化后台订单列表")
- * User: XMing
- * Date: 2020/7/11
- * Time: 5:02 下午
- * @param array $orderData
- * @param array $orderReceiveData
- * @param array $orderGoodsData
- * @return ResultWrapper
- */
- public function formatManageOrderList(array $orderData, array $orderReceiveData, array $orderGoodsData = [])
- {
- $returnData = [];
- if (empty($orderData)) {
- return ResultWrapper::success($returnData);
- }
- $receiveMap = [];
- if (!empty($orderReceiveData)) {
- $orderReceiveData = self::formatSysArea($orderReceiveData);// 订单收货地址集渲染
- foreach ($orderReceiveData as $key => &$item) {
- $receiveMap[$item['orderId']] = [
- 'customerId' => getArrayItem($item, 'customerId', 0),
- 'address' => getArrayItem($item, 'address'),
- 'allAddress' => $item['area']['provinceName'].$item['area']['cityName'].$item['area']['districtName'].getArrayItem($item, 'address'),
- 'realName' => getArrayItem($item, 'realName'),
- 'mobile' => getArrayItem($item, 'mobile'),
- 'area' => getArrayItem($item, 'area', [])
- ];
- }
- unset($item);
- }
- $orderData = self::formatOrderStatus($orderData); // 格式化订单状态
- $goodsMap = [];
- if (!empty($orderGoodsData)) {
- foreach ($orderGoodsData as $key => $item) {
- $goodsMap[$item['orderId']][] = $item;
- }
- }
- unset($item);
- // 映射下打印次数
- $allOrderNos = [];
- foreach ($orderData as $key => $value){
- $allOrderNos[] = $value['no'];
- }
- $pbjMPrintNum = new MPrintNum($this->onlineEnterpriseId);
- $printNumData = $pbjMPrintNum->getObjectPrintNumByNos($allOrderNos); // 批量获取打印次数
- $orderNoBindPritNum = [];
- if(!empty($printNumData)){
- foreach ($printNumData as $key => $value){
- $orderNoBindPritNum[$value['objectNo']] = $value['printNum'];
- }
- }
- foreach ($orderData as $key => $datum) {
- $returnData[$key] = [
- 'id' => $datum['id'],
- 'no' => self::formatSn($datum['no']),
- 'shopId' => $datum['shopId'],
- 'shopName' => isset($datum['shopName']) ? $datum['shopName'] : '',
- 'customerId' => $datum['customerId'],
- 'customerName' => $datum['customerName'],
- 'userCenterId' => $datum['userCenterId'],
- 'payAmount' => $datum['payAmount'],
- 'retMoney' => $datum['retMoney'],
- 'totalMoney' => $datum['totalMoney'],
- 'payStatus' => $datum['payStatus'],
- 'auditStatus' => $datum['auditStatus'],
- 'returnStatus' => $datum['returnStatus'],
- 'outStatus' => $datum['outStatus'],
- 'deliveryType' => $datum['deliveryType'],
- 'payType' => $datum['payType'],
- 'salesManName' => empty($datum['salesManName']) ? '' : $datum['salesManName'],
- 'salesman' => !isset($datum['salesman']) || is_null($datum['salesman']) ? '' : $datum['salesman'],
- 'salesManId' => $datum['salesManId'],
- 'createTime' => $datum['createTime'],
- 'source' => $datum['source'],
- 'orderStatus' => $datum['orderStatus'],
- 'receiveData' => isset($receiveMap[$datum['id']]) ? $receiveMap[$datum['id']] : [],
- 'orderMsg' => $datum['orderMsg'],
- 'payMsg' => $datum['payMsg'],
- 'deliveryMsg' => $datum['deliveryMsg'],
- 'payTypeMsg' => $datum['payTypeMsg'],
- 'sourceMsg' => $datum['sourceMsg'],
- 'auditMsg' => $datum['auditMsg'],
- 'extends' => json_decode($datum['extends'],true),
- 'printingNum' => getArrayItem($orderNoBindPritNum, $datum['no'], 0),
- ];
- if (!empty($orderGoodsData)) {
- $returnData[$key]['goodsData'] = isset($goodsMap[$datum['id']]) ? $goodsMap[$datum['id']] : [];
- }
- }
- return ResultWrapper::success($returnData);
- }
- private static function formatSn($no): string
- {
- return StatusCode::$noPrefix[StatusCode::$orderType['saleOrder']].'-'.$no;
- }
- /**
- * Doc: (des="订单查询index表 sql生成")
- * User: XMing
- * Date: 2020/7/11
- * Time: 11:23 上午
- * @waitAudit:等待审核 orderStatus != 6 auditStatus = 1
- * @waitOutStock:待出库 orderStatus != 6 auditPass = 2
- * @hasOutStock:已出库 orderStatus = 4 auditPass = 2
- * @finish:已完成 orderStatus = 5 auditPass 2
- * @close:已关闭 orderStatus = 6
- * @param array $selectParams
- * @return array
- */
- public function setOrderStatusSqlAttr(array $selectParams): array
- {
- $fields = 'id,userCenterId,no,customerId';
- $countFields = ' COUNT(id) AS total ';
- //订单类型
- $whereSql = '';
- if (isset($selectParams['orderType']) && !empty($selectParams['orderType'])) {
- if (is_array($selectParams['orderType'])) {
- $orderTypeStr = implode(',', $selectParams['orderType']);
- $whereSql .= ' and orderType in(' . $orderTypeStr . ') ';
- } else {
- $whereSql .= ' and orderType = ' . $selectParams['orderType'];
- }
- } else {
- $whereSql .= ' and orderType = ' . StatusCode::$orderType['saleOrder'];
- }
- if (isset($selectParams['keyword']) && !empty($selectParams['keyword'])){
- if (strstr($selectParams['keyword'],StatusCode::$noPrefix['1'])){
- $selectParams['keyword']= substr($selectParams['keyword'],strlen(StatusCode::$noPrefix[StatusCode::$orderType['saleOrder']])+1);
- }
- $keyword = '"%'.$selectParams['keyword'].'%"';
- $whereSql .= ' and no LIKE '.$keyword.' or verifyCode LIKE '.$keyword;
- }
- if (isset($selectParams['orderType']) && $selectParams['orderType'] == StatusCode::$orderType['cashierOrder']) {
- $selectParams['cashierUid'] = $this->onlineUserId;
- }
- if (isset($selectParams['isAll']) && $selectParams['isAll'] == StatusCode::$standard) {
- unset($selectParams['cashierUid']);
- }
- //userCenterId
- if (isset($selectParams['userCenterId']) && !empty($selectParams['userCenterId'])) {
- $whereSql .= ' and userCenterId = ' . $selectParams['userCenterId'];
- }
- //customerId
- if (isset($selectParams['customerId']) && !empty($selectParams['customerId'])) {
- $whereSql .= ' and customerId = ' . $selectParams['customerId'];
- }
- //收银员id
- if (isset($selectParams['cashierStaffId']) && !empty($selectParams['cashierStaffId'])) {
- $whereSql .= ' and cashierStaffId = ' . $selectParams['cashierStaffId'];
- }
- //no
- if (isset($selectParams['no']) && !empty($selectParams['no'])) {
- $whereSql .= ' and no = "' . $selectParams['no'].'"';
- }
- //shopId
- if (isset($selectParams['shopId']) && !empty($selectParams['shopId'])) {
- $whereSql .= ' and shopId = ' . $selectParams['shopId'];
- }
- //收银员id
- if (isset($selectParams['cashierUid']) && !empty($selectParams['cashierUid'])) {
- $whereSql .= ' and cashierUid = ' . $selectParams['cashierUid'];
- }
- //审核状态
- if (isset($selectParams['auditStatus']) && !empty($selectParams['auditStatus'])) {
- $whereSql .= ' and auditStatus = ' . $selectParams['auditStatus'];
- }
- //出库状态
- if (isset($selectParams['outStatus']) && !empty($selectParams['outStatus'])) {
- $whereSql .= ' and outStatus = ' . $selectParams['outStatus'];
- }
- //退货状态
- if (isset($selectParams['returnStatus']) && !empty($selectParams['returnStatus'])) {
- if (is_array($selectParams['returnStatus'])) {
- $returnStatusStr = implode(',', $selectParams['returnStatus']);
- $whereSql .= ' and returnStatus in(' . $returnStatusStr . ') ';
- } else {
- $whereSql .= ' and returnStatus = ' . $selectParams['returnStatus'];
- }
- }
- //配送方式
- if (isset($selectParams['deliveryType']) && !empty($selectParams['deliveryType'])) {
- $whereSql .= ' and deliveryType = ' . $selectParams['deliveryType'];
- }
- //支付方式
- if (isset($selectParams['payType']) && !empty($selectParams['payType'])) {
- $whereSql .= ' and find_in_set('.$selectParams['payType'].',payType) ';
- }
- if (isset($selectParams['startTime']) && !empty($selectParams['startTime'])){
- $whereSql .= ' AND createTime BETWEEN '.$selectParams['startTime'].' AND '.$selectParams['endTime'];
- }
- if (isset($selectParams['source']) && !empty($selectParams['source'])){
- $whereSql .= ' AND source = '.$selectParams['source'];
- }
- if (isset($selectParams['salesManId']) && !empty($selectParams['salesManId'])){
- $whereSql .= ' AND salesManId = '.$selectParams['salesManId'];
- }
- if (isset($selectParams['customerType']) && !empty($selectParams['customerType'])){
- $whereSql .= ' AND customerType = '.$selectParams['customerType'];
- }
- //订单状态
- if (isset($selectParams['state']) && !empty($selectParams['state'])) {
- $whereSql = self::buildStateSqlAttr($whereSql, $selectParams['state']);
- }
- //数据域
- if (isset($selectParams['orderType']) && $selectParams['orderType'] == StatusCode::$orderType['cashierOrder'] && isset($selectParams['cashierUid']) && !empty($selectParams['cashierUid'])) {
- //收银台列表
- } else {
- $whereSql = parent::getSalesManQueryParams($whereSql);
- }
- $whereSql = parent::getShopIdQueryParams($whereSql);
- $whereSql .= ' order by createTime desc';
- $sql = 'select ' . $fields . ' from qianniao_order_index_' . $this->onlineEnterpriseId . ' where deleteStatus = ' . StatusCode::$standard.$whereSql;
- $countSql = 'select ' . $countFields . ' from qianniao_order_index_' . $this->onlineEnterpriseId . ' where deleteStatus = ' . StatusCode::$standard.$whereSql;
- return [
- 'sql' => $sql,
- 'countSql' => $countSql
- ];
- }
- /**
- * Doc: (des="state标示多选sql处理")
- * User: XMing
- * Date: 2020/7/13
- * Time: 9:38 上午
- * @param string $sql
- * @param mixed $states
- * @return string
- */
- private static function buildStateSqlAttr(string $sql, $states)
- {
- if (is_array($states)) {
- if (in_array('all', $states)) {
- return $sql;
- }
- foreach ($states as $index => $state) {
- $sql .= $index == 0 ? ' and (' . self::stateSql($state) : ' or ' . self::stateSql($state);
- }
- $sql .= ') ';
- } else {
- if ($states == 'all') {
- return $sql;
- }
- $stateSql = self::stateSql($states);
- if (!empty($stateSql)) {
- $sql .= ' and ' . self::stateSql($states);
- }
- }
- return $sql;
- }
- /**
- * Doc: (des="state标示对应sql")
- * User: XMing
- * Date: 2020/7/13
- * Time: 9:43 上午
- * @param string $state
- * @return string
- */
- private static function stateSql(string $state)
- {
- $sql = '';
- switch ($state) {
- case 'waitAudit'://待审核
- $sql .= ' (auditStatus = ' . StatusCode::$auditStatus['auditing'] . ' and orderStatus != ' . StatusCode::$orderStatus['close'] . ')';
- break;
- case 'waitOutStock'://待出库
- $sql .= ' (auditStatus = ' . StatusCode::$auditStatus['auditPass'] . ' and (orderStatus = ' . StatusCode::$orderStatus['waitPay'] . ' or orderStatus = ' . StatusCode::$orderStatus['waitDelivery'] . ')) ';
- break;
- case 'hasOutStock'://已出库
- $sql .= ' (auditStatus = ' . StatusCode::$auditStatus['auditPass'] . ' and orderStatus = ' . StatusCode::$orderStatus['waitReceive'] . ')';
- break;
- case 'finish'://已完成
- $sql .= ' (auditStatus = ' . StatusCode::$auditStatus['auditPass'] . ' and orderStatus = ' . StatusCode::$orderStatus['finish'] . ')';
- break;
- case 'close'://已关闭
- $sql .= ' (orderStatus = ' . StatusCode::$orderStatus['close'] . ')';
- break;
- case 'all'://全部订单
- break;
- }
- return $sql;
- }
- /**
- * 删除订单视图
- */
- public function dropView()
- {
- $sql = 'DROP VIEW ' . $this->orderStatisticsTableName . '_' . $this->onlineEnterpriseId;
- $dbResult = $this->objDOrder->query($sql);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- return ResultWrapper::success('删除成功');
- }
- /**
- * 判断表是否存在
- * @param $tableName
- */
- public function existsTable($tableName)
- {
- $exists = $this->objDOrder->existsTable($tableName);
- if (!$exists) {
- //不存在删除视图
- self::dropView();
- }
- }
- /**
- * 添加银行打款数据
- */
- public function addOrderBankData($orderBankData)
- {
- //切换分表
- $fix = $fix = ceil($this->onlineUserId / $this->cutTable);
- $this->objDOrder->setTable('qianniao_order_' . $this->onlineEnterpriseId . '_' . $fix);
- foreach ($orderBankData['orderId'] as $key => $value){
- //获取订单信息
- $orderData = $this->objDOrder->get(['id' => $value]);
- if ($orderData === false) {
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- if(empty($orderData)){
- return ResultWrapper::fail('订单不存在', ErrorCode::$contentNotExists);
- }
- $orderData['extends'] = json_decode($orderData['extends'], true);
- $orderData['extends']['bankData'] = $orderBankData['bankData'];
- $orderData['extends'] = json_encode($orderData['extends']);
- $dbReuslt = $this->objDOrder->update(['extends'=>$orderData['extends'],'updateTime'=>time()], $value);
- if ($dbReuslt === false) {
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- }
- return ResultWrapper::success($dbReuslt);
- }
- /**
- * Doc: (des="审核订单,到出库单")
- * User: XMing
- * Date: 2020/7/14
- * Time: 6:38 下午
- * @param array $params
- * @return ResultWrapper
- * @throws \Exception
- */
- public function updateAuditStatus(array $params)
- {
- $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId);
- $orderIndex = $this->objDOrderIndex->get(['id' => $params['id']]);
-
- if ($orderIndex === false) {
- return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
- }
- if (empty($orderIndex)) {
- return ResultWrapper::fail('没有找到订单信息', ErrorCode::$paramError);
- }
- if ($orderIndex['auditStatus'] == StatusCode::$auditStatus['auditPass']) {
- return ResultWrapper::fail('当前订单已经审核通过!', ErrorCode::$paramError);
- }
- if ($this->isCashier === false) {
- //在线支付的订单必须是已支付才能审核
- if ($orderIndex['payType'] == StatusCode::$payType['wxPay'] || $orderIndex['payType'] == StatusCode::$payType['aliPay']) {
- if ($params['auditStatus'] == StatusCode::$auditStatus['auditPass'] && $orderIndex['payStatus'] == StatusCode::$delete) {
- return ResultWrapper::fail('订单尚未支付,不能审核', ErrorCode::$notAllowAccess);
- }
- }
- }
- //切换分表
- $fix = $fix = ceil($orderIndex['userCenterId'] / $this->cutTable);
- $this->objDOrder->setTable('qianniao_order_' . $this->onlineEnterpriseId . '_' . $fix);
- //获取订单信息
- $orderData = $this->objDOrder->get(['id' => $params['id']]);
- if ($orderData === false) {
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- // 银行打款支付方式审核之前需要判断是否上传凭证
- if( $orderData['payType'] == StatusCode::$payType['bankLoans'] ){
- $extends = json_decode($orderData['extends'],true);
- if (!array_key_exists('bankData',$extends)){
- return ResultWrapper::fail('该订单未上传银行打款凭证', ErrorCode::$paramError);
- }
- $customerData = $this->objDCustomer->get(['id'=>$orderData['customerId']]);
- if ($customerData === false) {
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- if(isset($customerData['openId']) && !empty($customerData['openId'])){
- // 银行打款上传凭证小程序订阅消息
- $sendMessageData = [
- 'date4' => [ 'value' => date('Y-m-d H:i:s',$orderData['createTime'])], // 提交时间
- 'thing10' => [ 'value' => $customerData['name'] ], // 申请人
- 'thing2' => [ 'value' => '银行打款凭证是否通过'], // 审核内容
- 'date3' => [ 'value' => date('Y-m-d H:i:s',$orderData['updateTime']) ], // 审核时间
- 'phrase1' => [ 'value' => $orderData['auditStatus'] == StatusCode::$auditStatus['auditPass'] ? '审核通过':'审核未通过'], // 审核结果
- ];
- $objMSystemPushMessage = new MSystemPushMessage($this->onlineUserId, $this->onlineEnterpriseId);
- $result = $objMSystemPushMessage->sendWeiXinPushMessage(4, $customerData['openId'], $sendMessageData);
- if(!$result->isSuccess()){
- file_put_contents('/www/wwwroot/logs/api.junhailan.com/wexinPushMessage.log',date('Y-m-d H:i:s').'bb'.var_export($result->getData(),true).PHP_EOL,FILE_APPEND);
- }
- }
- }
- $this->objDOrderIndex->beginTransaction();
- // 生成收款单
- $receivedResult = self::createReceived($orderData);
- if (!$receivedResult->isSuccess()) {
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($receivedResult->getData(), $receivedResult->getErrorCode());
- }
- $update = [
- 'auditStatus' => $params['auditStatus'],
- 'updateTime' => time(),
- ];
- if ( $orderData['payType'] == StatusCode::$payType['bankLoans'] ){//银行打款更新payStatus,orderStatus
- $update = [
- 'auditStatus' => $params['auditStatus'],
- 'payStatus' => StatusCode::$standard,
- 'orderStatus' => StatusCode::$orderStatus['waitDelivery'],
- 'updateTime' => time(),
- ];
- }
- //操作索引表
- $orderIndexUpdate = $this->objDOrderIndex->update($update, ['id' => $params['id']]);
- if ($orderIndexUpdate === false) {
- $this->objDOrderIndex->rollBack();
- Logger::logs(E_USER_ERROR, 'sql错误', __CLASS__, __LINE__, $this->objDOrderIndex->error());
- return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
- }
- //操作订单表
- $orderUpdate = $this->objDOrder->update($update, $params['id']);
- if ($orderUpdate === false) {
- $this->objDOrderIndex->rollBack();
- Logger::logs(E_USER_ERROR, 'sql错误', __CLASS__, __LINE__, $this->objDOrder->error());
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- //订单审核出库
- $outId = 0;
- if ($params['auditStatus'] == StatusCode::$auditStatus['auditPass']) {
- $orderData['auditId'] = $params['auditId'];
- $orderData['audit'] = $params['audit'];
- $addInventoryOutResult = self::addInventoryOut($params['id'], $orderData, $orderData['userCenterId']);
- if (!$addInventoryOutResult->isSuccess()) {
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($addInventoryOutResult->getData(), $addInventoryOutResult->getErrorCode());
- }
- $outId = $addInventoryOutResult->getData();
- }
- $this->objDOrderIndex->commit();
- /*
- //跟新es
- $_id = self::createEsDocumentId($params['id']);
- $this->objDOrder->esupdateTypeFieldVaule($update, $_id);*/
- self::runProcessNextOut($outId,$orderData);
-
- if ($params['auditStatus'] == StatusCode::$auditStatus['auditPass']) {
- return ResultWrapper::success($outId);
- }
- if(isset($customerData['openId']) && !empty($customerData['openId'])){
- // 订单审核通过
- $sendMessageData = [
- 'date4' => [ 'value' => date('Y-m-d H:i:s',$orderData['createTime'])], // 提交时间
- 'thing2' => [ 'value' => '银行打款凭证是否通过'], // 审核内容
- 'phrase1' => [ 'value' => $orderData['auditStatus'] == 2 ? '审核通过':'审核未通过'], // 审核结果
- 'date3' => [ 'value' => date('Y-m-d H:i:s',$orderData['updateTime']) ], // 审核时间
- ];
- $objMSystemPushMessage = new MSystemPushMessage($this->onlineUserId, $this->onlineEnterpriseId);
- $result = $objMSystemPushMessage->sendWeiXinPushMessage(6, $customerData['openId'], $sendMessageData);
- if(!$result->isSuccess()){
- file_put_contents('/www/wwwroot/logs/api.junhailan.com/shenhe.log',date('Y-m-d H:i:s').'bb'.var_export($result->getData(),true).PHP_EOL,FILE_APPEND);
- }
- }
-
- return ResultWrapper::success('操作成功');
- }
- /**
- * Doc: (des="step 3: 审核出库")
- * User: XMing
- * Date: 2020/11/9
- * Time: 9:24 上午
- * @param array $order
- * @param int $outId
- * @return ResultWrapper
- * @throws \Exception
- */
- private function runProcessNextOut(int $outId,array $order): ResultWrapper
- {
- if (empty($outId)){
- return ResultWrapper::success(true);
- }
- if ($order['orderType'] != StatusCode::$orderType['saleOrder']){
- return ResultWrapper::success(true);
- }
- $setResult = $this->objMProcessSetting->getProcessSettingByType(StatusCode::$processType['sales'],'out');
- if (!$setResult->isSuccess()){
- Logger::logs(E_USER_ERROR,'获取流程配置出错',__CLASS__,__LINE__,$setResult->getData());
- return ResultWrapper::fail($setResult->getData(),$setResult->getErrorCode());
- }
- $set = $setResult->getData();
- if (empty($set)){
- Logger::logs(E_USER_ERROR,'配置为空',__CLASS__,__LINE__,'');
- return ResultWrapper::success(true);
- }
- if (isset($set['enableStatus']) && $set['enableStatus'] == StatusCode::$standard){
- Logger::logs(E_USER_ERROR,'配置',__CLASS__,__LINE__,$set);
- return ResultWrapper::success(true);
- }
- $params = [
- 'id' => $outId,
- 'auditId' => $this->onlineUserId,//操作人id
- 'auditName' => '自动审核',//操作人姓名
- ];
- $objMInventoryOut = new MInventoryOut($this->onlineEnterpriseId,$this->onlineUserId);
- $result = $objMInventoryOut->updateInventoryOutStatus($params);
- if (!$result->isSuccess()){
- Logger::logs(E_USER_ERROR,'自动审核出库单出错',__CLASS__,__LINE__,$result->getData());
- return ResultWrapper::fail($result->getData(),$result->getErrorCode());
- }
- Logger::logs(E_USER_ERROR,'自动审核出库单成功',__CLASS__,__LINE__,$outId);
- return ResultWrapper::success(true);
- }
- /**
- * Doc: (des="后台代客下单创建收款单")
- * User: XMing
- * Date: 2020/11/5
- * Time: 5:31 下午
- * @param array $orderData
- * @return ResultWrapper
- * @throws \Exception
- */
- private function createReceived(array $orderData): ResultWrapper
- {
- // 银行打款
- if ($orderData['payType'] == StatusCode::$payType['bankLoans']){
- $orderExtendsData = json_decode($orderData['extends'], true);
- // 组装收款单账户数据
- $accountListData[] = [
- 'discountMoney' => 0,
- 'money' => $orderData['payAmount'],
- 'payWay' => StatusCode::$payType[4],
- 'remark' => '银行打款生成收款',
- 'accountId' => ($orderExtendsData['bankData']['id']) ? : 0,
- 'accountName' => ($orderExtendsData['bankData']['name']) ? : '',
- 'accountNumber' => ($orderExtendsData['bankData']['accountNumber']) ? : '',
- 'finalMoney' => $orderData['payAmount'],
- ];
- $orderData['accountList'] = json_encode($accountListData);
- $orderData['currentAccountName'] = ($orderExtendsData['bankData']['name']) ? : '';
- }
- //生成收款单
- if ( ($orderData['orderType'] == StatusCode::$orderType['saleOrder'] || $orderData['orderType'] == StatusCode::$orderType['salesSlip']) &&
- $orderData['source'] == StatusCode::$source['manage'] &&
- !empty($orderData['accountList']) &&
- !empty(floatval($orderData['receivedMoney'])) || ( $orderData['payType'] == StatusCode::$payType['bankLoans'] )//银行打款也生成收款单
- ) {
- $this->objDOrderIndex->beginTransaction();
- //生成收款单
- $objMReceived = new MReceived($this->onlineEnterpriseId, $this->onlineUserId);
- //创建收款单
- $received = [
- 'currentAccountName' => $orderData['currentAccountName'],
- 'financeType' => '银行打款收款',
- 'financeTypeId' => 2,
- 'shopId' => $orderData['shopId'],
- 'shopName' => $orderData['shopName'],
- 'receiptTime' => time(),
- 'operatorId' => $this->onlineUserId,
- 'accountList' => json_decode($orderData['accountList'], true),
- 'customerId' => $orderData['customerId'],
- 'customerName' => $orderData['customerName'],
- 'sourceNo' => $orderData['no'],
- 'sourceId' => $orderData['id'],
- 'originId' => $orderData['id'],
- 'originNo' => $orderData['originNo'],
- 'sourceNoMoney' => $orderData['receivedMoney'],
- 'extends' => isset($orderExtendsData['bankData']) ? json_encode($orderExtendsData['bankData']) : '[]',
- 'createTime' => time(),
- 'auditStatus' => StatusCode::$auditStatus['auditing'],
- 'updateTime' => time(),
- ];
- $receivedResult = $objMReceived->addReceived($received, true);
- if (!$receivedResult->isSuccess()) {
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($receivedResult->getData(), $receivedResult->getErrorCode());
- }
- $up = [];
- if ($orderData['receivedMoney'] >= $orderData['payAmount']) {
- $up = [
- 'payStatus' => StatusCode::$standard,
- 'updateTime' => time(),
- ];
- }else{
- if ($orderData['receivedMoney'] != 0){
- $up = [
- 'payStatus' => StatusCode::$offline,//部分收款
- 'updateTime' => time(),
- ];
- }
- }
- if (!empty($up)){
- $result = $this->objDOrderIndex->update($up, $orderData['id']);
- if ($result === false) {
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
- }
- $result = $this->objDOrder->update($up, $orderData['id']);
- if ($result === false) {
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- }
- $this->objDOrderIndex->commit();
- }
- return ResultWrapper::success(true);
- }
- /**
- * Doc: (des="订单审核出库,使用此方法一定要注意在上文获取当前订单的userCenterId用于下文切换分表")
- * User: XMing
- * Date: 2020/7/15
- * Time: 9:48 上午
- * @param array $orderData
- * @param int $id
- * @param int $thisOnlineUserId 当前订单的用户id,用来切换分表
- * @return ResultWrapper
- * @throws \Exception
- */
- private function addInventoryOut(int $id, array $orderData, int $thisOnlineUserId)
- {
- //查询订单商品表
- $objMOrderGoods = new MOrderGoods($thisOnlineUserId, $this->onlineEnterpriseId);
- $selectData = ['orderId' => $id];
- $orderGoodsDataObj = $objMOrderGoods->getOrderGoodsByOrderIds($selectData);
- if (!$orderGoodsDataObj->isSuccess()) {
- return ResultWrapper::fail($orderGoodsDataObj->getData(), ErrorCode::$dberror);
- }
- $objMInventoryOut = new MInventoryOut($this->onlineEnterpriseId, $this->onlineUserId);
- $totalResult = $objMInventoryOut->getTotalByOrderId($orderData['id']);
- if (!$totalResult->isSuccess()){
- return ResultWrapper::fail($totalResult->getData(),$totalResult->getErrorCode());
- }
- $total = (int)$totalResult->getData();
- if ($total > 0){
- //已经生成过出库单了
- Logger::logs(E_USER_ERROR, '订单id:'.$orderData['id'].',重复生成出库单', __CLASS__, __LINE__,$orderData);
- return ResultWrapper::fail('不要重复操作,避免生成成多个出库单',ErrorCode::$paramError);
- }
- //查询商铺id对应的仓库数据
- $objMShop = new MShop($this->onlineEnterpriseId, $this->onlineUserId);
- $modelResult = $objMShop->getShopDataByShopIds([$orderData['shopId']]);
- if (!$modelResult->isSuccess()) {
- return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
- }
- $shopData = $modelResult->getData();
- unset($modelResult);
- //获取订单收货信息
- $orderReceiveDbResult = [];
- if ($orderData['deliveryType'] == StatusCode::$deliveryType['goodsDelivery']) {
- $fix = ceil($thisOnlineUserId / $this->cutTable);
- $this->objDOrderReceive->setTable('qianniao_order_receive_' . $this->onlineEnterpriseId . '_' . $fix);
- $orderReceiveDbResult = $this->objDOrderReceive->get(['orderId' => $id]);
- if ($orderReceiveDbResult === false) {
- return ResultWrapper::fail($this->objDOrderReceive->error(), ErrorCode::$dberror);
- }
- if (empty($orderReceiveDbResult)) {
- return ResultWrapper::fail('订单收货地址查询失败', ErrorCode::$dberror);
- }
- }
- $objMCustomer = new MCustomer($this->onlineEnterpriseId,$this->onlineUserId);
- $customerResult = $objMCustomer->getCustomerByCustomerId($orderData['customerId']);
- if (!$customerResult->isSuccess()){
- return ResultWrapper::fail($customerResult->getData(),$customerResult->getErrorCode());
- }
- $customer = $customerResult->getData();
- $orderGoodsData = $orderGoodsDataObj->getData();//订单商品数据
- $saleOutData = [
- 'sourceId' => $orderData['id'],
- 'sourceNo' => $orderData['no'],
- 'originNo' => $orderData['no'],
- 'originId' => $orderData['id'],
- 'shopId' => $orderData['shopId'],
- 'shopName' => $orderData['shopName'],
- 'amount' => $orderData['payAmount'],
- 'operatorId' => $orderData['auditId'],//操作人id
- 'operatorName' => $orderData['audit'],//操作人信息
- 'customerId' => $orderData['customerId'],
- 'customerName' => $orderData['customerName'],
- 'customerCode' => createCode(StatusCode::$code['customer']['prefix'], $orderData['customerId'], StatusCode::$code['customer']['length']),
- 'customerMobile' => isset($customer['mobile']) ? $customer['mobile'] : '',
- 'source' => StatusCode::$orderType['saleOrder'], //订单来源(出库类型)
- 'type' => StatusCode::$orderType['saleOut'],
- 'deliveryType' => $orderData['deliveryType'],//配送方式
- 'remark' => $orderData['remark'],
- ];
- $saleOutData['materielNum'] = 0;
- //获取sku
- $objMSku = new MSku($this->onlineUserId, $this->onlineEnterpriseId);
- $skuIds = array_column(array_values($orderGoodsData), 'skuId');
- $modelResult = $objMSku->getSkuDataBySkuIds($skuIds);
- if (!$modelResult->isSuccess()) {
- return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
- }
- $skuData = $modelResult->getData();
- unset($modelResult);
- foreach ($orderGoodsData as $key => $value) {
- $saleOutData['materielNum']++;
- $totalMoney = bcsub(bcsub($value['totalMoney'], $value['vipDiscount']), $value['preferential']);//销售总价 !优惠后
- $saleOutData['orderGoodsData'][] = [
- 'materielId' => $value['goodsBasicId'],
- 'materielName' => $value['goodsName'],
- 'materielCode' => createCode(StatusCode::$code['goodsBasic']['prefix'], $value['goodsBasicId'], StatusCode::$code['goodsBasic']['length']),
- 'skuId' => $value['skuId'],
- 'num' => $value['buyNum'],
- 'otherNum' => $value['otherNum'],
- 'outNum' => 0,
- 'total' => $value['buyNum'],
- 'unitName' => isset($value['unitName']) ? $value['unitName'] : '',
- 'skuName' => isset($skuData[$value['skuId']]) ? $skuData[$value['skuId']]['skuName'] : '',
- 'unitPrice' => $value['price'],//单价 不优惠
- 'totalPrice' => $totalMoney,//销售总价 !优惠后
- 'extend' => $value['extends'],
- 'isEq' => $value['isEq'],
- ];
- }
- $dbResult = $objMInventoryOut->addInventoryOut($saleOutData);
- if (!$dbResult->isSuccess()) {
- Logger::logs(E_USER_ERROR, 'sql错误', __CLASS__, __LINE__, $dbResult->getData());
- return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror);
- }
- self::noticeStatistics([
- 'userCenterId' => $thisOnlineUserId,
- 'enterpriseId' => $this->onlineEnterpriseId,
- 'customerId' => $orderData['customerId'],
- 'no' => $orderData['no'],
- 'noticeType' => 'audit',//审核
- ], 'MOrderStatistics');
- //添加日志
- parent::saveLog([
- 'no' => $orderData['no'],
- 'actionType' => '审核通过',
- 'operationData' => '',
- 'userCenterId' => $this->onlineUserId,
- 'enterpriseId' => $this->onlineEnterpriseId,
- 'createTime' => time(),
- ]);
- self::sendMessage($this->onlineEnterpriseId,'NewOrder','stockOut');
- return ResultWrapper::success($dbResult->getData());
- }
- /**
- * 批量审核
- * @param array $params
- * @return ResultWrapper
- * @throws \Exception
- */
- public function batchUpdateAuditStatus(array $params)
- {
- $auditParam = [
- 'audit' => $params['audit'],
- 'auditId' => $params['auditId'],
- 'auditStatus' => $params['auditStatus']
- ];
- foreach ($params['ids'] as $id) {
- $auditParam['id'] = $id;
- $result = self::updateAuditStatus($auditParam);
- if (!$result->isSuccess()) {
- return ResultWrapper::fail($result->getData(), $result->getErrorCode());
- }
- }
- return ResultWrapper::success("审核成功");
- }
- /**
- * Doc: (des="修改订单的状态,orderStatus")
- * User: XMing
- * Date: 2020/7/14
- * Time: 5:25 下午
- * @param $id
- * @param $selectParams
- * @param array $header
- * @return ResultWrapper
- * @throws \Exception
- */
- public function updateOrderStatus($id, $selectParams, array $header)
- {
- // 查询订单索引表数据
- $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId);
- $orderIndex = $this->objDOrderIndex->get(['id' => $id], 'userCenterId,payStatus,createTime,customerId,no,updateTime');
- if ($orderIndex === false) {
- return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
- }
- if (empty($orderIndex)) {
- return ResultWrapper::fail('订单信息不存在', ErrorCode::$paramError);
- }
- // 后台设置的审核通过不能取消订单
- $objEnterpriseCache = new EnterpriseCache();
- $enterSettingData = $objEnterpriseCache->getEnterpriseSetting($this->onlineEnterpriseId);
- if(isset($enterSettingData['cancelOrder']) && $enterSettingData['cancelOrder'] == StatusCode::$delete && $orderIndex['auditStatus'] == StatusCode::$auditStatus['auditPass'] && $selectParams['orderStatus'] == StatusCode::$orderStatus['close']){
- return ResultWrapper::fail('当前订单已经审核通过,暂不支持取消,请联系客服处理', ErrorCode::$notAllowAccess);
- }
- if ($selectParams['orderStatus'] == StatusCode::$orderStatus['close']
- && isset($orderIndex['outStatus']) && $orderIndex['outStatus'] == StatusCode::$standard) {
- return ResultWrapper::fail('已经发货订单不能取消', ErrorCode::$paramError);
- }
- // 切换订单分表,查询订单主单据数据
- $fix = ceil($orderIndex['userCenterId'] / $this->cutTable);;
- $this->objDOrder->setTable('qianniao_order_' . $this->onlineEnterpriseId . '_' . $fix);
- $orderData = $this->objDOrder->get(['id' => $id]);
- if($orderData === false) {
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- if(empty($orderData)){
- return ResultWrapper::fail('要操作的订单不存在', ErrorCode::$contentNotExists);
- }
- $this->objDOrderIndex->beginTransaction();
- $selectParams['cancelbeforeOrderStatus'] = $orderData["orderStatus"];
- // 更新订单表
- $orderData['extends'] = json_decode($orderData['extends'], true);
- if( !empty($selectParams['cancelReason']) ){
- $orderData['extends']['cancelReason'] = $selectParams['cancelReason'];
- $orderData['extends']['cancelbeforeOrderStatus'] = $selectParams['cancelbeforeOrderStatus'];
- $selectParams['successFullyTime'] = time();
- }
- if( !empty($selectParams['cancelRejectReason']) ){
- $orderData['extends']['cancelRejectReason'] = $selectParams['cancelRejectReason'];
- $selectParams['orderStatus'] = $orderData['extends']['cancelbeforeOrderStatus']; // 取消被拒恢复到取消之前的订单状态
- }
- // 更新索引表
- $orderIndexUpdate = $this->objDOrderIndex->update([
- 'orderStatus' => $selectParams['orderStatus'],
- 'updateTime' => time()
- ], ['id' => $id]);
- if ($orderIndexUpdate === false) {
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
- }
- $selectParams['extends'] = json_encode($orderData['extends']);
- $selectParams['updateTime'] = time();
- unset($selectParams['cancelReason']);
- unset($selectParams['cancelRejectReason']);
- unset($selectParams['cancelbeforeOrderStatus']);
- $orderUpdate = $this->objDOrder->update($selectParams, ['id' => $id]);
- if ($orderUpdate === false) {
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- // 取消订单
- if ($selectParams['orderStatus'] == StatusCode::$orderStatus['close']) {
- // 解锁库存
- $unlockResult = self::unlockInventory($id, $orderData);
- if (!$unlockResult->isSuccess()) {
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($unlockResult->getData(), $unlockResult->getErrorCode());
- }
- // 已经支付订单做自动退款处理
- if($orderData['payStatus'] == StatusCode::$standard){
- // 生成财务退款单
- $financeRefundData = [
- 'originId' => getArrayItem($orderData,'id',0),
- 'originNo' => getArrayItem($orderData,'no',''),
- 'sourceId' => getArrayItem($orderData,'id',0),
- 'sourceNo' => getArrayItem($orderData,'no',''),
- 'refundTime' => time(),
- 'createTime' => time(),
- 'updateTime' => time(),
- 'unitId' => getArrayItem($orderData,'customerId',0),
- 'unitName' => getArrayItem($orderData,'customerName',0),
- 'currentAccountName' => getArrayItem($orderData,'customerName',''),
- 'financeType' => '订单取消退款',
- 'financeTypeId' => 1,
- 'payType' =>getArrayItem($orderData,'payType',''),
- 'shopId' => getArrayItem($orderData,'shopId',0),
- 'shopName' => getArrayItem($orderData,'shopName',0),
- 'money' => $orderData['payAmount'],
- 'operatorId' => $this->onlineUserId,
- 'type' => StatusCode::$standard,
- 'auditStatus' => StatusCode::$auditStatus['auditing'],
- 'remark' => '订单取消,订单编号:'. getArrayItem($orderData,'no','').'需退款金额:'.$orderData['payAmount'],
- ];
- // 根据订单支付方式规划退款账户
- $objMAccount = new MAccount($this->onlineEnterpriseId,$this->onlineUserId);
- $extends = is_array($orderData['extends'])?$orderData['extends']: json_decode($orderData['extends'], true);
- if(isset($extends['admixPayData'])){ // 组合支付
- foreach ($extends['admixPayData'] as $key => $value){
- $financeAccountData = $objMAccount->getDefaultAccount($value['payType']);
- if(!$financeAccountData->isSuccess()){
- return ResultWrapper::fail($financeAccountData->getData(), $financeAccountData->getErrorCode());
- }
- $financeAccountData = $financeAccountData->getData();
- $financeRefundData['accountList'][] = [
- 'accountId' => $financeAccountData['id'],
- 'accountNumber' => $financeAccountData['accountNumber'],
- 'accountName' => $financeAccountData['name'],
- 'money' => $value['payMoney'],
- ];
- }
- }else{
- $financeAccountData = $objMAccount->getDefaultAccount($orderData['payType']);
- if(!$financeAccountData->isSuccess()){
- return ResultWrapper::fail($financeAccountData->getData(), $financeAccountData->getErrorCode());
- }
- $financeAccountData = $financeAccountData->getData();
- $financeRefundData['accountList'] = [
- [
- 'accountId' => $financeAccountData['id'],
- 'accountNumber' => $financeAccountData['accountNumber'],
- 'accountName' => $financeAccountData['name'],
- 'money' => $orderData['payAmount'],
- ]
- ];
- }
- $objMRefund = new MRefund($this->onlineEnterpriseId,$this->onlineUserId);
- $result = $objMRefund->addRefund($financeRefundData);
- if(!$result->isSuccess()){
- return ResultWrapper::fail($result->getData(),$result->getErrorCode());
- }
- // 自动审核退款单
- $result = $objMRefund->updateRefundStatus(['id'=>$result->getData(),'createTime'=>time()]);
- if(!$result->isSuccess()){
- return ResultWrapper::fail($result->getData(),$result->getErrorCode());
- }
- }
- // 订单审核待出库时取消订单 同步删除销售出库单
- if($orderData['auditStatus'] == StatusCode::$auditStatus['auditPass']){
- $objMInventoryOut = new MInventoryOut($this->onlineEnterpriseId, $this->onlineUserId);
- $inventoryOutResult = $objMInventoryOut->delInventoryOutStatus(['originId' => $orderData['id']]);
- if (!$inventoryOutResult->isSuccess()) {
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($inventoryOutResult->getData(), $inventoryOutResult->getErrorCode());
- }
- }
- $customerData = $this->objDCustomer->get(['id'=>$orderData['customerId']]);
- if ($customerData === false) {
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- if(isset($customerData['openId']) && !empty($customerData['openId'])){
- // 后台取消订单小程序订阅消息
- $sendMessageData = [
- 'character_string13' => [ 'value' => StatusCode::$noPrefix[1] . '-' . $orderData['no']], // 订单编号
- 'date10' => [ 'value' => date('Y-m-d H:i:s',$orderData['createTime']) ], // 下单时间
- 'thing14' => [ 'value' => substr($orderData['shopName'],0,30)], // 门店名称
- 'date2' => [ 'value' => date('Y-m-d H:i:s',$orderData['updateTime']) ], // 取消时间
- ];
- $objMSystemPushMessage = new MSystemPushMessage($this->onlineUserId, $this->onlineEnterpriseId);
- $result = $objMSystemPushMessage->sendWeiXinPushMessage(5, $customerData['openId'], $sendMessageData);
- if(!$result->isSuccess()){
- file_put_contents('/www/wwwroot/logs/api.junhailan.com/quxiao.log',date('Y-m-d H:i:s').'bb'.var_export($result->getData(),true).PHP_EOL,FILE_APPEND);
- }
- }
- }
- //订单完成
- if ($selectParams['orderStatus'] == StatusCode::$orderStatus['finish'] && !empty($header)) {
- // 计算分销订单提成
- $i = 1;
- do {
- $postData = [
- 'topicName' => 'MyJob',
- 'topicClass' => 'Jobs\Model\MTopic\Order\MCommissionOrder',
- 'topicMethon' => 'updateBalance',
- 'topicMethonParams' => [
- 'Authorization' => $header['Authorization'],
- 'Token' => $header['Token'],
- 'orderId' => $id,
- 'PROJECT_DOMAIN' => PROJECT_DOMAIN
- ],
- ];
- $url = QIANNIAO_QUEUE . '/CAddJob/add';
- $result = request($url, $postData);
- $i++;
- } while ($result['httpcode'] != 200 && $i <= 3);
- // 计算用户积分 start
- // 查询客户信息
- $customerData = $this->objDCustomer->get($orderIndex['customerId']);
- if ($customerData === false) {
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- // 查询订单商品数据
- $fix = ceil($orderIndex['userCenterId'] / $this->cutTable);
- $this->objDOrderGoods->setTable('qianniao_order_goods_' . $this->onlineEnterpriseId . '_' . $fix);
- $orderGoodsData = $this->objDOrderGoods->select(['deleteStatus'=>StatusCode::$standard,'orderId'=>$id]);
- if ($orderGoodsData === false) {
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- // 调用计算积分方法
- $objMCustomer = new MCustomer($this->onlineEnterpriseId, $this->onlineUserId);
- $result = $objMCustomer->addCustomerIntegralByOrder(0, $customerData, $orderData, $orderGoodsData);
- if(!$result->isSuccess()){
- return ResultWrapper::fail($result->getData(), $result->getErrorCode());
- }
- //调用计算提成方法
- $objMStaff = new MStaff($this->onlineEnterpriseId, $this->onlineUserId);
- $result = $objMStaff->addStaffRewardByOrder(0, $customerData, $orderData, $orderGoodsData);
- if(!$result->isSuccess()){
- return ResultWrapper::fail($result->getData(), $result->getErrorCode());
- }
- //订单完成商户结算金额
- $objMMerchantSettlement = new MMerchantSettlement($this->onlineEnterpriseId, $this->onlineUserId);
- $updateMerchantSettlement = $objMMerchantSettlement->updateMerchantSettlement(['orderId'=>$orderData['id']]);
- if(!$updateMerchantSettlement->isSuccess()){
- return ResultWrapper::fail($updateMerchantSettlement->getData(), $updateMerchantSettlement->getErrorCode());
- }
-
-
- //只有小程序微信支付订单才可以计算分佣
- if(!empty($orderData) && $orderData["payAmount"]>0 && $orderData["payType"]==1 && $orderData["source"]==3){
- $checkData = [
- "parentPath"=>$customerData["parentPath"],
- "payAmount"=>$orderData["payAmount"],
- ];
- // PartnerTools::addTask($orderData["id"], $this->onlineEnterpriseId,$checkData);
- }
-
- }
- //取消订单
- if ($selectParams['orderStatus'] == StatusCode::$orderStatus['close'] && !empty($header)) {
- $i = 1;
- do {
- $postData = [
- 'topicName' => 'MyJob',
- 'topicClass' => 'Jobs\Model\MTopic\Order\MCommissionOrder',
- 'topicMethon' => 'cancelSubCommission',
- 'topicMethonParams' => [
- 'Authorization' => $header['Authorization'],
- 'Token' => $header['Token'],
- 'orderId' => $id,
- 'PROJECT_DOMAIN' => PROJECT_DOMAIN
- ],
- ];
- $url = QIANNIAO_QUEUE . '/CAddJob/add';
- $result = request($url, $postData);
- $i++;
- } while ($result['httpcode'] != 200 && $i <= 3);
- }
- /*
- //ES更新
- $_id = self::createEsDocumentId($id);
- $this->objDOrder->esupdateTypeFieldVaule(['orderStatus' => $selectParams['orderStatus']], $_id);*/
- $this->objDOrderIndex->commit();
- return ResultWrapper::success('操作成功');
- }
- /**
- * Doc: (des="取消订单解锁库存")
- * User: XMing
- * Date: 2020/7/14
- * Time: 5:54 下午
- * @param int $id 订单id
- * @param array $params 订单数据
- * @return ResultWrapper
- */
- private function unlockInventory(int $id, array $params)
- {
- //解锁库存
- $objMInventory = new MInventory($this->onlineEnterpriseId, $this->onlineUserId);
- $unlockResult = $objMInventory->unlockInventory([$id], StatusCode::$orderType['saleOrder'], $params['createTime']);
- if (!$unlockResult->isSuccess()) {
- //暂时关闭,没发现有锁定的地方
- // return ResultWrapper::fail($unlockResult->getData(), ErrorCode::$dberror);
- }
- self::noticeStatistics([
- 'userCenterId' => $this->onlineUserId,
- 'enterpriseId' => $this->onlineEnterpriseId,
- 'customerId' => $params['customerId'],
- 'no' => $params['no'],
- 'data' => $params,
- 'noticeType' => 'close',//取消订单
- ], 'MOrderStatistics');
- //记录日志
- parent::saveLog([
- 'no' => $params['no'],
- 'actionType' => '取消订单',
- 'operationData' => '',
- 'userCenterId' => $this->onlineUserId,
- 'enterpriseId' => $this->onlineEnterpriseId,
- 'createTime' => time(),
- ]);
- return ResultWrapper::success($unlockResult->getData());
- }
- /**
- * Doc: (des="订单出库状态")
- * User: XMing
- * Date: 2020/12/28
- * Time: 10:38 上午
- * @param array $params
- * @param array $where
- * @param array $outInventoryMap
- * @return ResultWrapper
- * @throws \Exception
- * @oaram $outInventoryMap
- */
- public function updateOutStatus(array $params,array $where,array $outInventoryMap): ResultWrapper
- {
- if (empty($where)) {
- return ResultWrapper::fail('参数为空', ErrorCode::$paramError);
- }
- $orderIndex = $this->objDOrderIndex->get($where);
- if ($orderIndex === false){
- return ResultWrapper::fail($this->objDOrderIndex->error(),ErrorCode::$dberror);
- }
- if (empty($orderIndex)){
- return ResultWrapper::fail('未获取到指定的订单信息',ErrorCode::$paramError);
- }
- $orderId = getArrayItem($orderIndex,'id',0);
- $fix = ceil($orderIndex['userCenterId'] / $this->cutTable);
- $this->objDOrder->setTable('qianniao_order_'.$this->onlineEnterpriseId.'_'.$fix);
- $this->objDOrderGoods->setTable('qianniao_order_goods_'.$this->onlineEnterpriseId.'_'.$fix);
- $this->objDOrderIndex->beginTransaction();
- foreach ($outInventoryMap as $skuId => $outNum){
- $row = $this->objDOrderGoods->get(['orderId' => $orderId, 'skuId' => $skuId, 'deleteStatus' => StatusCode::$standard]);
- if ($row === false){
- $this->objDOrderIndex->rollback();
- return ResultWrapper::fail($this->objDOrderGoods->error(),ErrorCode::$dberror);
- }
- $update = [
- 'outNum' => bcadd($row['outNum'],$outNum,2),
- 'outOfNum' => bcsub($row['outOfNum'],$outNum,2),
- 'updateTime' => time(),
- ];
- if ($update['outOfNum'] < 0){
- Logger::logs(E_USER_ERROR,'企业:'.$this->onlineEnterpriseId.' 订单:'.$orderId.' 出库数量异常',__CLASS__,__LINE__,$row);
- $this->objDOrderIndex->rollback();
- return ResultWrapper::fail('出库数量异常',ErrorCode::$paramError);
- }
- $updateGoodsResult = $this->objDOrderGoods->update($update,['id' => $row['id']]);
- if ($updateGoodsResult === false){
- Logger::logs(E_USER_ERROR,'sql error',__CLASS__,__LINE__,$this->objDOrderGoods->error());
- $this->objDOrderIndex->rollback();
- return ResultWrapper::fail($this->objDOrderGoods->error(),ErrorCode::$paramError);
- }
- }
- $outStatusResult = self::checkStockOutStatus($orderId);
- if (!$outStatusResult->isSuccess()){
- $this->objDOrderIndex->rollback();
- return ResultWrapper::fail($outStatusResult->getData(),$outStatusResult->getErrorCode());
- }
- $outStatus = (int)$outStatusResult->getData();
- $params['outStatus'] = $outStatus;//出库状态
- $updateIndex = $this->objDOrderIndex->update($params,$orderId);
- if ($updateIndex === false){
- $this->objDOrderIndex->rollback();
- return ResultWrapper::fail($this->objDOrderIndex->error(),ErrorCode::$dberror);
- }
- $updateOrder = $this->objDOrder->update($params,$orderId);
- if ($updateOrder === false){
- $this->objDOrderIndex->rollback();
- return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror);
- }
- /*
- $_id = self::createEsDocumentId($orderId);
- $this->objDOrder->esupdateTypeFieldVaule($params, $_id);*/
- $this->objDOrderIndex->commit();
- return ResultWrapper::success($orderId);
- }
- /**
- * Doc: (des="返回订单的出库")
- * User: XMing
- * Date: 2021/3/10
- * Time: 10:35 上午
- * @param int $orderId
- * @return ResultWrapper
- */
- public function checkStockOutStatus(int $orderId): ResultWrapper
- {
- //检测是否都已经出库
- $lists = $this->objDOrderGoods->select(['orderId' => $orderId,'deleteStatus' => StatusCode::$standard]);
- if ($lists === false){
- Logger::logs(E_USER_ERROR,'sql error',__CLASS__,__LINE__,$this->objDOrderGoods->error());
- return ResultWrapper::fail($this->objDOrderGoods->error(),ErrorCode::$dberror);
- }
- if (empty($lists)){
- return ResultWrapper::fail('订单商品获取失败',ErrorCode::$paramError);
- }
- foreach ($lists as $item){
- if ($item['outOfNum'] > 0){
- //还有未出库商品
- return ResultWrapper::success(6);
- }
- }
- return ResultWrapper::success(5);
- }
- /**
- * Doc: (des="修改订单的支付状态")
- * User: XMing
- * Date: 2020/7/14
- * Time: 5:18 下午
- * @param $orderData
- * @param $condition
- * @param bool $isNotify
- * @return ResultWrapper
- * @throws \Exception
- */
- public function updateOrderPayData($orderData, $condition, $isNotify = false): ResultWrapper
- {
- $total_fel = 0;
- if ($isNotify) {
- $total_fel = $orderData['total_fel'];
- unset($orderData['total_fel']);
- }
- if (isset($orderData['pay_way'])) {
- $pay_way = $orderData['pay_way'];
- unset($orderData['pay_way']);
- }
- // 查询订单数据
- $orderInfoData = $this->objDOrder->select($condition);
- if (empty($orderInfoData)) {
- return ResultWrapper::fail('查询订单数据为空', ErrorCode::$paramError);
- }
- if ($orderInfoData === false) {
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- // 回调通知判断订单是否已经修改过订单状态
- if ($isNotify == true && $orderInfoData[0]['payStatus'] == StatusCode::$standard) {
- return ResultWrapper::fail('支付状态已经修改过了', ErrorCode::$notAllowAccess);
- }
- $this->objDOrder->beginTransaction();
- // 如果之前是组合支付方式,修改支付方式的时候不能直接修改
- if( in_array(StatusCode::$payType['balance'], explode(',', $orderInfoData[0]['payType'])) ){
- $orderData['payType'] = $orderData['payType'].','.StatusCode::$payType['balance'];
- $orderData['notPayMoney'] = bcsub($orderData['notPayMoney'], $orderData['total_fel'], 2);
- }
- $dbResult = $this->objDOrder->update($orderData, $condition);
- if ($dbResult === false) {
- $this->objDOrder->rollBack();
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- unset($dbResult);
- if (!isset($condition['id'])) {
- //查询订单id
- $dbResult = $this->objDOrder->get($condition, 'id');
- if ($dbResult === false) {
- $this->objDOrder->rollBack();
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- if (empty($dbResult) || !isset($dbResult['id'])) {
- $this->objDOrder->rollBack();
- return ResultWrapper::fail('订单数据为空', ErrorCode::$dberror);
- }
- $condition['id'][] = $dbResult['id'];
- unset($dbResult);
- }
- unset($orderData['notPayMoney']);
- $dbResult = self::updateOrderIndex($orderData, $condition);
- if (!$dbResult->isSuccess()) {
- $this->objDOrder->rollBack();
- return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror);
- }
- if (!is_array($condition['id'])){
- $condition['id'] = [$condition['id']];
- }
- /*
- foreach ($condition['id'] as $key => $value) {
- $_id = self::createEsDocumentId($value);
- $this->objDOrder->esupdateTypeFieldVaule($orderData, $_id);
- }*/
- //线上支付生成收款单$orderData['payStatus'] $condition['id'] 支付完成后回调这两个有值
- if (isset($pay_way) && isset($orderData['payStatus']) && isset($condition['id'])) {
- if ($orderData['payStatus'] == StatusCode::$standard) {
- //拿到微信默认账户
- $defaultAccountResult = $this->objMAccount->getDefaultAccount($pay_way);
- if ($defaultAccountResult->isSuccess() == false) {
- $this->objDOrder->rollBack();
- return ResultWrapper::fail($defaultAccountResult->getData(), $defaultAccountResult->getErrorCode());
- }
- $defaultAccount = $defaultAccountResult->getData();
- if(empty($defaultAccount)){
- return ResultWrapper::fail('支付方式对应的银行账户为空', ErrorCode::$contentNotExists);
- }
- foreach ($orderInfoData as $orderInfo) {
- // 组合支付,收款单金额重新计算
- if( in_array(StatusCode::$payType['balance'], explode(',', $orderInfoData[0]['payType'])) ){
- $orderInfo['extends'] = json_decode($orderInfo['extends'], true);
- if( isset($orderInfo['extends']['admixPayData']) ){
- foreach ($orderInfo['extends']['admixPayData'] as $key => $value){
- if($value['payType'] == StatusCode::$payType['wxPay']){
- $orderInfo['payAmount'] = $value['payMoney'];
- }
- }
- }
- }
- //循环订单数据,拼接生成收款单
- $receivedData = [
- 'customerId' => $orderInfo['customerId'],
- 'customerName' => $orderInfo['customerName'],
- 'currentAccountName' => $orderInfo['shopName'],
- 'financeType' => '线上支付收款',
- 'financeTypeId' => StatusCode::$systemFinanceType['saleReceipt'],
- 'shopId' => $orderInfo['shopId'],
- 'shopName' => $orderInfo['shopName'],
- 'receiptTime' => time(),
- 'operatorId' => 0,
- 'originId' => $orderInfo['id'],
- 'originNo' => $orderInfo['no'],
- 'sourceId' => $orderInfo['id'],
- 'sourceNo' => $orderInfo['no'],
- 'sourceNoMoney' => $orderInfo['payAmount'],
- 'auditStatus' => StatusCode::$auditStatus['auditing'],
- 'offsetMoney' => 0,
- 'notOffsetMoney' => 0,
- 'offsetStatus' => StatusCode::$delete,
- 'createTime' => time(),
- 'updateTime' => time(),
- 'accountList' => [
- [
- "accountId" => isset($defaultAccount['id']) ? $defaultAccount['id'] : 0,
- "accountNumber" => isset($defaultAccount['accountNumber']) ? $defaultAccount['accountNumber'] : '请设置默认的收款账户',
- "money" => $orderInfo['payAmount'],
- "discountMoney" => 0,
- "finalMoney" => $orderInfo['payAmount'],
- "payWay" => isset($pay_way) ? $pay_way . "支付" : '在线支付',
- "remark" => "在线支付自动生成收款单"
- ]
- ],
- ];
- $result = $this->objMReceived->addReceived($receivedData, true);
- if ($result->isSuccess() == false) {
- $this->objDOrder->rollBack();
- return ResultWrapper::fail($result->getData(), $result->getErrorCode());
- }
- // 微信生成的收款单自动审核
- if( in_array(StatusCode::$payType['wxPay'], explode(',', $orderInfoData[0]['payType'])) ){
- $updateReceived = $this->objMReceived->updateReceivedStatus(['id'=>$result->getData(),'createTime'=>time()]);
- if (!$updateReceived->isSuccess()) {
- $this->objDOrder->rollBack();
- return ResultWrapper::fail($updateReceived->getData(), $updateReceived->getErrorCode());
- }
- }
- unset($receivedData);
- unset($result);
- }
- }
- }
- if ($isNotify) {
- self::runProcessNextAudit($condition['id']);
- $objMCustomer = new MCustomer($this->onlineEnterpriseId, $this->onlineUserId);
- $customer = $objMCustomer->getCustomerInfoByUserCenterId($this->onlineUserId);
- if (!$customer->isSuccess()) {
- return ResultWrapper::fail($customer->getData(), $customer->getErrorCode());
- }
- $customer = $customer->getData();
- parent::coupon([
- 'userCenterId' => $this->onlineUserId,
- 'enterpriseId' => $this->onlineEnterpriseId,
- 'customerId' => isset($customer['id']) ? $customer['id'] : '',
- 'payAmount' => isset($total_fel) ? $total_fel : 0,
- ], 'MOnlinePayCoupon');
- $objCustomerCache = new CustomerCache();
- $objCustomerCache->delInterestCustomerAfterPay($customer['id'], $this->onlineEnterpriseId);
-
-
- if (isset($customer['openId']) && !empty($customer['openId'])) {
- /* $payment = '';
- //判断支付方式
- switch ($orderInfoData[0]['payType']) {
- case StatusCode::$payType['wxPay']:
- $payment = StatusCode::$payType[1];
- break;
- case StatusCode::$payType['balance']:
- $payment = StatusCode::$payType[7];
- break;
- case StatusCode::$payType['cashPay']:
- $payment = StatusCode::$payType[3];
- break;
- case StatusCode::$payType['bankLoans']:
- $payment = StatusCode::$payType[4];
- break;
- }
- $orderInfoData[0]['extends'] = json_decode($orderInfoData[0]['extends'], true);
- if (isset($orderInfoData[0]['extends']['admixPayData'])) {
- $payment = '组合支付';
- }*/
- // 发送小程序订阅消息
- $sendMessageData = [
- 'character_string3' => ['value' => StatusCode::$noPrefix[1] . '-' . $orderInfoData[0]['no']], // 订单编号
- 'date10' => ['value' => date('Y-m-d H:i:s', $orderInfoData[0]['createTime'])], // 下单时间
- 'time4' => ['value' => date('Y-m-d H:i:s', time())], // 支付时间
- 'thing7' => ['value' => '微信支付'], // 支付方式
- 'name8' => ['value' => substr($orderInfoData[0]['shopName'],0,30)] // 商家名称
- ];
- $objMSystemPushMessage = new MSystemPushMessage($this->onlineUserId, $this->onlineEnterpriseId);
- $result = $objMSystemPushMessage->sendWeiXinPushMessage(3, $customer['openId'], $sendMessageData);
- if (!$result->isSuccess()) {
- file_put_contents('/www/wwwroot/logs/api.junhailan.com/systemPushMessage.log', date('Y-m-d H:i:s') . 'bb' . var_export($result->getData(), true) . PHP_EOL, FILE_APPEND);
- }
- }
- }
- $this->objDOrder->commit();
- $objMMerchantFlow = new MMerchantFlow($this->onlineEnterpriseId,$this->onlineUserId);
- if ($isNotify == true || $orderData['payStatus'] == StatusCode::$standard){
- foreach ($condition['id'] as $key => $id) {
- $objMMerchantFlow->calculation($id);
- }
- }
- return ResultWrapper::success('操作成功');
- }
- /**
- * 更新索引表订单状态,支付状态,支付方式
- * @param $orderData
- * @param $params
- * @return ResultWrapper
- * @throws \Exception
- */
- private function updateOrderIndex($orderData, $params)
- {
- $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId);
- $updateData = [];
- isset($orderData['payType']) && $updateData['payType'] = $orderData['payType'];
- isset($orderData['payStatus']) && $updateData['payStatus'] = $orderData['payStatus'];
- isset($orderData['orderStatus']) && $updateData['orderStatus'] = $orderData['orderStatus'];
- isset($orderData['outStatus']) && $updateData['outStatus'] = $orderData['outStatus'];
- $where['id'] = $params['id'];
- $dbResult = $this->objDOrderIndex->update($updateData, $where);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
- }
- return ResultWrapper::success($dbResult);
- }
- /**
- * 格式化返回数据
- * @param $data
- * @return array
- * @throws \Exception
- * @return ResultWrapper
- */
- private function format($data): ResultWrapper
- {
- // 提取所有订单id
- $allOrderIds = [];
- $allShopIds = [];
- $allOrderNo = [];
- $customerIds = [];
- $allCustomerTypeIds = [];
- if (isset($data['id'])) {
- $dimension = $data;
- unset($data);
- $data[] = $dimension;
- }
- foreach ($data as $key => $value) {
- $allOrderNo[] = $value['no'];
- $allOrderIds[] = $value['id'];
- $allShopIds[] = $value['shopId'];
- $allCustomerTypeIds = $value['customerType'];
- $customerIds[] = $value['customerId'];
- $this->onlineUserId = $value['userCenterId'];
- if ($value['auditStatus'] == StatusCode::$auditStatus['auditing']) {
- $data[$key]['orderMsg'] = '待审核';
- }
- if ($value['auditStatus'] == StatusCode::$auditStatus['auditPass']) {
- $data[$key]['orderMsg'] = '待出库';
- if ($value['orderStatus'] == StatusCode::$orderStatus['waitReceive']) {
- $data[$key]['orderMsg'] = '已出库';
- if ($value['outStatus'] == 6 && $value['isRet'] != StatusCode::$standard){
- $data[$key]['orderMsg'] = '部分出库';
- }
- }
- if ($value['orderStatus'] == StatusCode::$orderStatus['finish']) {
- $data[$key]['orderMsg'] = '已完成';
- }
- }
- switch ($value['orderStatus']){
- case StatusCode::$orderStatus['close']:
- $data[$key]['orderMsg'] = '已关闭';
- break;
- case StatusCode::$orderStatus['cancelIng'];
- $data[$key]['orderMsg'] = '待取消';
- break;
- }
- if (isset($value['payType'])) {
- $data[$key]['payTypeMsg'] = isset(StatusCode::$payType[$value['payType']]) ? StatusCode::$payType[$value['payType']] : '';
- }
- }
- //获取客户类型
- $customerTypeMap = [];
- if (!empty($allCustomerTypeIds)) {
- $objDCustomerSource = new DCustomerSource();
- $customerSourceLists = $objDCustomerSource->select(['id' => $allCustomerTypeIds], 'id,name');
- if ($customerSourceLists != false) {
- foreach ($customerSourceLists as $val) {
- $customerTypeMap[$val['id']] = $val['name'];
- }
- }
- }
- //获取店铺信息
- $objMShop = new MShop($this->onlineEnterpriseId, $this->onlineUserId);
- $shopData = $objMShop->getShopName($allShopIds);
- /********************************订单商品 start****************************/
- $objMOrderGoods = new MOrderGoods($this->onlineUserId, $this->onlineEnterpriseId);
- $dbResult = $objMOrderGoods->getOrderGoodsByOrderIds(['orderId' => $allOrderIds, 'deleteStatus' => StatusCode::$standard]);
- $orderGoodsData = [];//订单商品信息
- if (!$dbResult->isSuccess()) {
- return ResultWrapper::fail($dbResult->getData(),$dbResult->getErrorCode());
- }
- $orderGoodsData = $dbResult->getData();
- unset($dbResult);
- //查询sku信息
- $objMSku = new MSku($this->onlineUserId, $this->onlineEnterpriseId);
- //查询商品数据
- $allGoodsIds = array_unique(array_column($orderGoodsData, 'goodsId'));
- $allGoodsBasicIds = array_unique(array_column($orderGoodsData, 'goodsBasicId'));
- $objMGoods = new MGoods($this->onlineEnterpriseId, false, $this->onlineUserId);
- $goodsData = $objMGoods->getGoodsNames($allGoodsIds);
- //获取商品的库存
- $inventorySelectParams = [];
- $objMInventory = new MInventory($this->onlineEnterpriseId, '');
- foreach ($orderGoodsData as $item){
- $inventorySelectParams[$item['shopId']][] = $item['skuId'];
- }
- $inventoryMap = [];
- foreach ($inventorySelectParams as $shopId => $skuIds){
- $inventoryResult = $objMInventory->getInventoryByShopIdAndSkuIds($shopId,$skuIds);
- if (!$inventoryResult->isSuccess()) {
- return ResultWrapper::fail($inventoryResult->getData(),$inventoryResult->getErrorCode());
- }
- $inventoryMap[$shopId] = $inventoryResult->getData();
- }
- //sku信息
- $skuResult = $objMSku->getSpecNameBySkuId(array_column($orderGoodsData, 'skuId'));
- if (!$skuResult->isSuccess()) {
- return ResultWrapper::fail($skuResult->getData(),$skuResult->getErrorCode());
- }
- $allSku = $skuResult->getData();
- $goods = [];
- $allSkuIds = [];
- foreach ($orderGoodsData as $val){
- if (!in_array($val['skuId'],$allSkuIds)){
- $allSkuIds[] = $val['skuId'];
- }
- }
- foreach ($orderGoodsData as $key => &$value) {
- $value['isNew'] = isset($allSku[$value['skuId']]['isNew']) ? $allSku[$value['skuId']]['isNew'] : StatusCode::$delete;
- $value['barCode'] = isset($allSku[$value['skuId']]['barCode']) ? $allSku[$value['skuId']]['barCode'] : '';
- $value['unitName'] = isset($allSku[$value['skuId']]['unitName']) ? $allSku[$value['skuId']]['unitName'] : '';
- $value['specGroup'] = isset($allSku[$value['skuId']]['specGroup']) ? $allSku[$value['skuId']]['specGroup'] : [];
- $value['images'] = isset($goodsData[$value['goodsId']]['images']) ? json_decode($goodsData[$value['goodsId']]['images'], true) : '';
- $value['returnPrice'] = bcdiv(bcsub(bcsub($value['totalMoney'], $value['preferential']), $value['vipDiscount']), $value['buyNum']);
- $value['isMater'] = isset($allSku[$value['skuId']]['isMaster']) ? $allSku[$value['skuId']]['isMaster'] : StatusCode::$delete;
- $value['conversion'] = isset($allSku[$value['skuId']]['conversion']) ? $allSku[$value['skuId']]['conversion'] : 0;
- $value['inventory'] = isset($inventoryMap[$value['shopId']][$value['skuId']]['num']) ? $inventoryMap[$value['shopId']][$value['skuId']]['num'] : 0;
- // 处理订单商品表扩展字段
- if( !empty($value['extends']) ){
- $extends = json_decode($value['extends'], true);
- if(!empty($extends)){
- foreach($extends as $keys => $item){
- $value[$keys] = $item;
- }
- }
- }
- $allOrderGoodsData[$value['orderId']][] = $value;
- if (!isset($goods[$value['orderId']]['goodsPreferential'])) {
- $goods[$value['orderId']]['goodsPreferential'] = 0;
- }
- $goods[$value['orderId']]['goodsPreferential'] = bcadd($goods[$value['orderId']]['goodsPreferential'], bcmul($value['preferential'], $value['buyNum']), 2);
- }
- unset($dbResult);
- /********************************收货信息 start******************************/
- $objMOrderReceive = new MOrderReceive($this->onlineUserId, $this->onlineEnterpriseId);
- $dbResult = $objMOrderReceive->getOrderReceiveByOrderIds(['orderId' => $allOrderIds]);
- $orderReceiveData = [];//订单收货信息
- if (!$dbResult->isSuccess()) {
- return ResultWrapper::fail($dbResult->getData(),$dbResult->getErrorCode());
- }
- $orderReceiveData = self::formatSysArea($dbResult->getData());
- foreach ($orderReceiveData as $key => $value) {
- $allOrderReceiveData[$value['orderId']] = $value;
- }
- unset($dbResult);
- /*********************************订单操作记录*********************************/
- $objMOrderLog = new MOrderLog($this->onlineEnterpriseId);
- $orderLog = $objMOrderLog->getOrderLog(['no' => $allOrderNo]);
- /**********************************获取基本配置*********************************/
- $objMBasicSetup = new MBasicSetup($this->onlineEnterpriseId);
- $setupResult = $objMBasicSetup->getBasicField('allowReturnDay');
- if (!$setupResult->isSuccess()) {
- return ResultWrapper::fail($setupResult->getData(),$setupResult->getErrorCode());
- }
- $setupResult = $setupResult->getData();
- $allowReturnDay = empty($setupResult['allowReturnDay']) ? 0 : $setupResult['allowReturnDay'];
- /********************************映射数据 start******************************/
- $nowTime = time();
- foreach ($data as $key => $value) {
- $data[$key]['no'] = StatusCode::$noPrefix[1].'-'.$value['no'];
- $data[$key]['extends'] = !empty($value['extends']) ? json_decode($value['extends'], true) : (object)[];
- $data[$key]['goodsData'] = isset($allOrderGoodsData[$value['id']]) ? $allOrderGoodsData[$value['id']] : [];
- $data[$key]['receiveData'] = isset($allOrderReceiveData[$value['id']]) ? $allOrderReceiveData[$value['id']] : [];
- $data[$key]['deliveryNo'] = isset($value['deliveryNo']) ? $value['deliveryNo'] : '';
- $data[$key]['payAmount'] = bcsub($value['payAmount'],$value['retMoney'],2);
- $data[$key]['expressMoney'] = isset($value['expressMoney']) ? $value['expressMoney'] : '';
- $data[$key]['expressName'] = isset($value['expressName']) ? $value['expressName'] : '';
- $data[$key]['deliveryName'] = isset(StatusCode::$deliveryType[$value['deliveryType']]) ? StatusCode::$deliveryType[$value['deliveryType']] : '';//配送方式名称
- $data[$key]['orderPreferential'] = bcsub($data[$key]['totalMoney'], bcsub($data[$key]['payAmount'], $data[$key]['expressMoney'], 2), 2);//订单优惠
- $data[$key]['goodsPreferential'] = isset($goods[$value['id']]['goodsPreferential']) ? $goods[$value['id']]['goodsPreferential'] : '';//商品优惠
- $data[$key]['coupon'] = '0.00';
- $data[$key]['salesman'] = $value['salesManName'];
- $data[$key]['shopName'] = isset($shopData[$value['shopId']]['name']) ? $shopData[$value['shopId']]['name'] : '';
- $data[$key]['shopLogo'] = isset($shopData[$value['shopId']]['logo']) ? $shopData[$value['shopId']]['logo'] : '';
- $data[$key]['orderLog'] = isset($orderLog[$value['no']]) ? $orderLog[$value['no']] : [];
- $data[$key]['allowReturn'] = StatusCode::$standard;//允许退货
- if ($allowReturnDay == 0) {
- //TODO(没有设置可退货时间,默认都可以退)
- $data[$key]['allowReturn'] = StatusCode::$standard;//允许退货
- } else {
- $expire = ($allowReturnDay * 86400) + $value['successFullyTime'];
- if ($nowTime > $expire) {
- $data[$key]['allowReturn'] = StatusCode::$delete;//不允许退货
- }
- }
- $data[$key]['allowReturnDay'] = $allowReturnDay;
- if ($value['source'] == StatusCode::$source['manage']){
- $data[$key]['orderPreferential'] = isset($value['totalReduceMoney']) ? $value['totalReduceMoney'] : 0;
- }else{
- $data[$key]['orderPreferential'] = bcsub($value['totalMoney'], bcsub($value['payAmount'], $value['expressMoney'], 2), 2);//订单总优惠
- }
- $data[$key]['paidAmount'] = $value['payStatus'] == StatusCode::$standard ? $value['payAmount'] : '0';//已付款金额
- $data[$key]['customerTypeName'] = isset($customerTypeMap[$value['customerType']]) ? $customerTypeMap[$value['customerType']] : '';
- $data[$key]['cashierName'] = $value['cashierName'];
- $data[$key]['customerMobile'] = $value['customerMobile'];//客户手机号码
- $data[$key]['guideName'] = $value['guideName'];
- $data[$key]['changeAmount'] = $value['changeSubMoney'];
- $data[$key]['accountList'] = empty($value['accountList']) ? [] : json_decode($value['accountList'], true);
- $data[$key]['receivedName'] = isset($allOrderReceiveData[$value['id']]['realName']) ? $allOrderReceiveData[$value['id']]['realName'] : '';//收货人
- $data[$key]['receivedMobile'] = isset($allOrderReceiveData[$value['id']]['mobile']) ? $allOrderReceiveData[$value['id']]['mobile'] : '';//收货电话
- $data[$key]['reservoir'] = !empty($value['reservoir']) ? json_decode($value['reservoir'],true) : [];
- //$data[$key]['selfRuleData'] = empty($value['selfRuleData']) ? (object)[] : json_decode($value['selfRuleData'],true);
- }
- $data = array_shift($data);
- if ($this->isFront === false) {
- $data['expressData'] = (object)[];
- if ($data['deliveryType'] == StatusCode::$deliveryType['goodsDelivery'] && $data['deliveryNo']) {
- $expressResult = self::getExpressInfoByOrderId($data['id']);
- if ($expressResult->isSuccess()) {
- $data['expressData'] = $expressResult->getData();
- }
- }
- }
- return ResultWrapper::success($data);
- }
- /**
- * 地区
- * @param $data
- * @return mixed
- */
- public function formatSysArea($data)
- {
- if (empty($data)) {
- return $data;
- }
- $objMSysAreaChina = new MSysAreaChina();
- foreach ($data as $key => $val) {
- if (isset($val['provinceCode']) && isset($val['cityCode']) && isset($val['districtCode'])) {
- $areaName = $objMSysAreaChina->getNameByCode([
- $val['provinceCode'],
- $val['cityCode'],
- $val['districtCode']
- ]);
- $data[$key]['area']['provinceName'] = isset($areaName[$val['provinceCode']]) ? $areaName[$val['provinceCode']] : '';
- $data[$key]['area']['cityName'] = isset($areaName[$val['cityCode']]) ? $areaName[$val['cityCode']] : '';
- $data[$key]['area']['districtName'] = isset($areaName[$val['districtCode']]) ? $areaName[$val['districtCode']] : '';
- }
- }
- return $data;
- }
- /**
- * 查询订单
- * 全部 {"page": 1,"pageSize": 10,"orderStatus": 0}
- * 待付款 {"page": 1,"pageSize": 10,"orderStatus": 2}
- * 待发货 {"page": 1,"pageSize": 10,"orderStatus": 3}
- * 待收货 {"page": 1,"pageSize": 10,"orderStatus": 4}
- * @param $selectParams
- * @return ResultWrapper
- * @throws \Exception
- */
- public function getOrderSelect($selectParams)
- {
- $limit = $selectParams['limit'];
- unset($selectParams['limit']);
- $offset = $selectParams['offset'];
- unset($selectParams['offset']);
- unset($selectParams['page']);
- unset($selectParams['pageSize']);
- $objMCustomer = new MCustomer($this->onlineEnterpriseId, $this->onlineUserId);
- $customerId = $objMCustomer->getCustomerIdByUserCenterId($this->onlineUserId);
- if (empty($customerId)) {
- return ResultWrapper::fail('没有找到客户信息', ErrorCode::$paramError);
- }
- $selectParams['customerId'] = $customerId;
- $selectParams['deleteStatus'] = StatusCode::$standard;
- $dbResult = $this->objDOrder->select($selectParams, 'id,payType,outerTradeNo,payStatus,outStatus,verifyCode,totalMoney,payAmount,notPayMoney,shopId,no,orderStatus,createTime,deliveryType,auditStatus,isRet', 'createTime DESC,updateTime DESC', $limit, $offset);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- $total = $this->objDOrder->count($selectParams);
- $return = [
- 'data' => self::formatAndGoods($dbResult),
- 'total' => ($total) ? intval($total) : 0,
- ];
- return ResultWrapper::success($return);
- }
- /**
- * 格式化商品数据
- *
- * @param $data
- * @return mixed
- * @throws \Exception
- */
- private function formatAndGoods($data)
- {
- $allOrderIds = [];
- $allShopIds = [];
- foreach ($data as $key => $value) {
- $allShopIds[] = $value['shopId'];
- $allOrderIds[] = $value['id'];
- }
- $objMOrderGoods = new MOrderGoods($this->onlineUserId, $this->onlineEnterpriseId);
- $selectParams = [
- 'orderId' => $allOrderIds,
- 'deleteStatus' => StatusCode::$standard,
- ];
- $dbResult = $objMOrderGoods->getOrderGoodsByOrderIds($selectParams);
- $orderGoodsData = [];//订单商品信息
- if ($dbResult->isSuccess()) {
- $orderGoodsData = $dbResult->getData();
- }
- $allGoodsIds = array_unique(array_column($orderGoodsData, 'goodsId'));
- unset($dbResult);
- $objMGoods = new MGoods($this->onlineEnterpriseId, false, $this->onlineUserId);
- $goodsData = $objMGoods->getGoodsNames($allGoodsIds);
- if (empty($goodsData)) {
- return $data;
- }
- $allOrderGoodsData = [];
- foreach ($orderGoodsData as $key => &$value) {
- $value['extends'] = !empty($value['extends']) ? json_decode($value['extends'], true) : [];
- $value['images'] = isset($goodsData[$value['goodsId']]['images']) ? json_decode($goodsData[$value['goodsId']]['images'], true) : '';
- // 如果是抄码商品,订单商品购买数量按照件算
- if( $value['isEq'] == StatusCode::$standard){
- $value['buyNum'] = isset($value['extends']['u_1_buy']) ? $value['extends']['u_1_buy'] : $value['buyNum'];
- }
- $allOrderGoodsData[$value['orderId']][] = $value;
- }
- $objMShop = new MShop($this->onlineEnterpriseId, $this->onlineUserId);
- $shopData = $objMShop->getShopName($allShopIds);
- foreach ($data as $key => $val) {
- $data[$key]['deliveryTypeMsg'] = isset(StatusCode::$deliveryType[$val['deliveryType']]) ? StatusCode::$deliveryType[$val['deliveryType']] : '';
- $data[$key]['goodsNum'] = isset($allOrderGoodsData[$val['id']]) ? array_sum(array_column($allOrderGoodsData[$val['id']], 'buyNum')) : '';
- $data[$key]['shopName'] = isset($shopData[$val['shopId']]['name']) ? $shopData[$val['shopId']]['name'] : '';
- $data[$key]['shopLogo'] = isset($shopData[$val['shopId']]['logo']) ? $shopData[$val['shopId']]['logo'] : '';
- $data[$key]['goodsData'] = isset($allOrderGoodsData[$val['id']]) ? array_values($allOrderGoodsData[$val['id']]) : '';
- }
- return $data;
- }
- /**
- * Doc: (des="订单检索条件")
- * User: XMing
- * Date: 2020/7/11
- * Time: 9:48 上午
- * @param $selectParams
- * @param bool $is_export
- * @return ResultWrapper
- * @throws \Exception
- */
- public function search($selectParams, $is_export = false)
- {
- $defaultDSL = [
- 'sort' => [
- 'createTime' => [
- 'order' => 'desc'
- ],
- ],
- ];
- if ($is_export === false) {
- $defaultDSL['from'] = $selectParams['offset'];
- $defaultDSL['size'] = $selectParams['limit'];
- }
- $dsl = [];
- $dsl['query']['bool']['must'][] = [
- 'term' => ['enterpriseId' => $this->onlineEnterpriseId],
- ];
- //订单编号,收货人,商品名称
- if (!empty($selectParams['keyword'])) {
- $dsl['query']['bool']['must'][] = [
- 'multi_match' => [
- 'fields' => ['no', 'verifyCode', 'mobile', 'goodsName', 'salesManName', 'customerName', 'remark'],
- 'query' => $selectParams['keyword'],
- //'fuzziness' => 'AUTO',
- "type" => "best_fields",
- "tie_breaker" => 0.3,
- "minimum_should_match" => "100%"
- ],
- ];
- }
- //销售单/订单
- if (isset($selectParams['orderType']) && !empty($selectParams['orderType'])) {
- $dsl['query']['bool']['filter'][] =
- ['term' => ['orderType' => $selectParams['orderType']]];
- }
- //订单状态
- if (isset($selectParams['orderStatus']) && !empty($selectParams['orderStatus'])) {
- $dsl['query']['bool']['filter'][] =
- ['term' => ['orderStatus' => $selectParams['orderStatus']]];
- }
- //出库状态
- if (isset($selectParams['outStatus']) && !empty($selectParams['outStatus'])) {
- $dsl['query']['bool']['filter'][] =
- ['term' => ['outStatus' => $selectParams['outStatus']]];
- }
- //退货状态
- if (isset($selectParams['returnStatus']) && !empty($selectParams['returnStatus'])) {
- $dsl['query']['bool']['filter'][] =
- ['term' => ['returnStatus' => $selectParams['returnStatus']]];
- }
- //配送方式
- if (isset($selectParams['deliveryType']) && !empty($selectParams['deliveryType'])) {
- $dsl['query']['bool']['filter'][] =
- ['term' => ['deliveryType' => $selectParams['deliveryType']]];
- }
- //支付状态
- if (isset($selectParams['payType']) && !empty($selectParams['payType'])) {
- $dsl['query']['bool']['filter'][] =
- ['term' => ['payType' => $selectParams['payType']]];
- }
- //店铺id
- parent::getAccessShopIds();
- if (parent::$shopIds) {
- $dsl['query']['bool']['filter'][] = [
- 'terms' => ['shopId' => parent::$shopIds]
- ];
- }
- //省code
- if (isset($selectParams['provinceCode']) && !empty($selectParams['provinceCode'])) {
- $dsl['query']['bool']['filter'][] =
- ['term' => ['provinceCode' => $selectParams['provinceCode']]];
- }
- //市code
- if (isset($selectParams['cityCode']) && !empty($selectParams['cityCode'])) {
- $dsl['query']['bool']['filter'][] =
- ['term' => ['cityCode' => $selectParams['cityCode']]];
- }
- //区code
- if (isset($selectParams['districtCode']) && !empty($selectParams['districtCode'])) {
- $dsl['query']['bool']['filter'][] =
- ['term' => ['districtCode' => $selectParams['districtCode']]];
- }
- if (!empty($selectParams['start']) && !empty($selectParams['end'])) {
- $dsl['query']['bool']['must'][] = [
- 'range' => [
- 'createTime' => [
- 'gte' => $selectParams['start'],
- 'lte' => $selectParams['end'],
- ]
- ]
- ];
- } else {
- if (isset($selectParams['start']) && !empty($selectParams['start'])) {
- $dsl['query']['bool']['must'][] = [
- 'range' => [
- 'createTime' => [
- 'gte' => $selectParams['start'],
- ]
- ]
- ];
- }
- if (isset($selectParams['end']) && !empty($selectParams['end'])) {
- $dsl['query']['bool']['must'][] = [
- 'range' => [
- 'createTime' => [
- 'lte' => $selectParams['end'],
- ]
- ]
- ];
- }
- }
- //店铺id
- if (isset($selectParams['shopId']) && !empty($selectParams['shopId'])) {
- $dsl['query']['bool']['filter'][] =
- ['term' => ['shopId' => $selectParams['shopId']]];
- }
- //客户id
- if (isset($selectParams['customerId']) && !empty($selectParams['customerId'])) {
- $dsl['query']['bool']['filter'][] =
- ['term' => ['customerId' => $selectParams['customerId']]];
- }
- //客户类型
- if (isset($selectParams['customerType']) && !empty($selectParams['customerType'])) {
- $dsl['query']['bool']['filter'][] =
- ['term' => ['customerType' => $selectParams['customerType']]];
- }
- $flag = true;
- //业务员id
- if (isset($selectParams['salesManId']) && !empty($selectParams['salesManId'])) {
- $dsl['query']['bool']['filter'][] =
- ['term' => ['salesManId' => $selectParams['salesManId']]];
- }
- //销售员id
- parent::getAccessSalesManIds();
- if (!empty(parent::$salesManIds) && empty($selectParams['salesManId'])) {
- $dsl['query']['bool']['filter'][] = [
- 'terms' => ['salesManId' => parent::$salesManIds]
- ];
- }
- if (!empty(parent::$salesManIds) && !empty($selectParams['salesManId'])) {
- if (!in_array($selectParams['salesManId'], parent::$salesManIds)) {
- $flag = false;
- }
- }
- //订单来源
- if (isset($selectParams['source']) && !empty($selectParams['source'])) {
- $dsl['query']['bool']['filter'][] =
- ['term' => ['source' => $selectParams['source']]];
- }
- //按照标示进行检索,等级最高
- if (isset($selectParams['state']) && !empty($selectParams['state'])) {
- $dsl = self::setOrderStatusDslAttr($dsl, $selectParams['state']);
- }
- $dsl = array_merge($defaultDSL, $dsl);
- //导出
- if ($is_export === true) self::exportSearch($dsl);
- //V($dsl);
- $result = $flag ? $this->objDOrder->getSearchQueryDsl($dsl) : [];
- if (isset($result['status']) && $result['status'] == 400) {
- //return ResultWrapper::fail('获取数据失败' . $result['error']['reason'], ErrorCode::$apiNotResult);
- return ResultWrapper::success([
- 'data' => [],
- 'total' => 0
- ]);
- }
- if (!isset($result['hits']) || $result['hits']['total'] == 0) {
- return ResultWrapper::success([
- 'data' => [],
- 'total' => 0
- ]);
- }
- $total = $result['hits']['total'];
- $dbResult = $result['hits']['hits'];
- $list = [];
- foreach ($dbResult as $key => &$value) {
- $data = [];
- $data = $value['_source'];
- //$data['id'] = $value['_id'];
- $data['receiveData'] = [
- 'realName' => $data['realName'],
- 'mobile' => $data['mobile']
- ];
- unset($data['realName']);
- unset($data['mobile']);
- $list[] = $data;
- }
- $buildData = self::shiftEsReceiveData($list);
- $formatResult = self::formatManageOrderList($buildData['allOrderData'], $buildData['allOrderReceiveData']);
- if (!$formatResult->isSuccess()) {
- return ResultWrapper::fail($formatResult->getData(), $formatResult->getErrorCode());
- }
- $return = [
- 'data' => $formatResult->getData(),
- 'total' => ($total) ? intval($total) : 0,
- ];
- return ResultWrapper::success($return);
- }
- /**
- * Doc: (des="将es中查询出来的数据,统一转化为标准格式进行格式化")
- * User: XMing
- * Date: 2020/7/11
- * Time: 6:13 下午
- * @param $data
- * @return array
- */
- private static function shiftEsReceiveData($data)
- {
- $orderData = [];
- $orderReceiveData = [];
- foreach ($data as $item) {
- $orderData[] = $item;
- $orderReceiveData[] = [
- 'orderId' => $item['id'],
- 'customerId' => $item['customerId'],
- 'address' => $item['address'],
- 'realName' => $item['receiveData']['realName'],
- 'mobile' => $item['receiveData']['mobile'],
- 'provinceCode' => $item['provinceCode'],
- 'cityCode' => $item['cityCode'],
- 'districtCode' => $item['districtCode']
- ];
- }
- return [
- 'allOrderData' => $orderData,
- 'allOrderReceiveData' => $orderReceiveData
- ];
- }
- /**
- * 格式化订单状态
- * @param $data
- * @return mixed
- */
- private static function formatOrderStatus($data)
- {
-
- if (empty($data)) return $data;
- foreach ($data as $key => $value) {
- if ($value['auditStatus'] == StatusCode::$auditStatus['auditing']) {
- $data[$key]['orderMsg'] = '待审核';
- }
- if ($value['auditStatus'] == StatusCode::$auditStatus['auditPass']) {
- $data[$key]['orderMsg'] = '待出库';
- if ($value['orderStatus'] == StatusCode::$orderStatus['waitReceive']) {
- $data[$key]['orderMsg'] = '已出库';
- if ($value['outStatus'] == 6 && $value['isRet'] != StatusCode::$standard){
- $data[$key]['orderMsg'] = '部分出库';
- }
- }
- if ($value['orderStatus'] == StatusCode::$orderStatus['finish']) {
- $data[$key]['orderMsg'] = '已完成';
- }
- }
- switch ($value['orderStatus']){
- case StatusCode::$orderStatus['close']:
- $data[$key]['orderMsg'] = '已关闭';
- break;
- case StatusCode::$orderStatus['cancelIng'];
- $data[$key]['orderMsg'] = '待取消';
- break;
- // case StatusCode::$orderStatus['waitReceive'];
- // $data[$key]['orderMsg'] = '待收货';
- // break;
- }
- if (isset($value['payStatus'])) {
- $data[$key]['payMsg'] = $value['payStatus'] == StatusCode::$standard ? '已支付' : '未支付';
- }
- if (isset($value['deliveryType'])) {
- $data[$key]['deliveryMsg'] = isset(StatusCode::$deliveryType[$value['deliveryType']]) ? StatusCode::$deliveryType[$value['deliveryType']] : '';
- }
- if (isset($value['payType'])) {
- $payTypeMsg = '';
- if( isset(StatusCode::$payType[$value['payType']]) ){
- $payTypeMsg = StatusCode::$payType[$value['payType']];
- }else{// 组合支付渲染金额
- if($value['extends']){
- $admixPayData = json_decode($value['extends'],true);
- $payTypeMsg = '组合支付(';
- if(!empty($admixPayData)){
- foreach ($admixPayData['admixPayData'] as $admixKey => $admixValue){
- $payTypeMsg .= $admixValue['title'].'支付'.$admixValue['payMoney'].',';
- }
- }
- $payTypeMsg .= ")";
- }
- }
- $data[$key]['payTypeMsg'] = $payTypeMsg;
- //$data[$key]['payTypeMsg'] = isset(StatusCode::$payType[$value['payType']]) ? StatusCode::$payType[$value['payType']] : '组合支付';
- }
- if (isset($value['source'])) {
- $data[$key]['sourceMsg'] = isset(StatusCode::$source[$value['source']]) ? StatusCode::$source[$value['source']] : '';
- }
- if (isset($value['auditStatus'])) {
- $data[$key]['auditMsg'] = isset(StatusCode::$auditStatus[$value['auditStatus']]) ? StatusCode::$auditStatus[$value['auditStatus']] : '';
- }
- }
- return $data;
- }
- /**
- * Doc: (des="订单标示的dsl拼接")
- * User: XMing
- * Date: 2020/7/11
- * Time: 9:15 上午
- * @param array $dsl
- *
- * @waitAudit:等待审核 orderStatus != 6 auditStatus = 1
- * @waitOutStock:待出库 orderStatus != 6 auditPass = 2
- * @hasOutStock:已出库 orderStatus = 4 auditPass = 2
- * @finish:已完成 orderStatus = 5 auditPass 2
- * @close:已关闭 orderStatus = 6
- * @param string $states
- * @return array|mixed
- */
- public static function setOrderStatusDslAttr(array $dsl, $states)
- {
- if (is_array($states)) {
- $allAuditStatus = [];
- $allOrderStatus = [];
- foreach ($states as $state) {
- $auditStatus = self::auditStatusAttrDsl($state);
- $orderStatus = self::orderStatusAttrDsl($state);
- $allAuditStatus = array_merge($auditStatus, $allAuditStatus);
- $allOrderStatus = array_merge($orderStatus, $allOrderStatus);
- }
- } else {
- $allAuditStatus = self::auditStatusAttrDsl($states);
- $allOrderStatus = self::orderStatusAttrDsl($states);
- }
- if (!empty($allAuditStatus)) {
- $dsl['query']['bool']['filter'][] = [
- 'terms' => [
- 'auditStatus' => $allAuditStatus
- ]
- ];
- }
- if (!empty($allOrderStatus)) {
- $dsl['query']['bool']['filter'][] = [
- 'terms' => [
- 'orderStatus' => $allOrderStatus
- ]
- ];
- }
- return $dsl;
- }
- /**
- * Doc: (des="state对应审核状态映射")
- * User: XMing
- * Date: 2020/7/13
- * Time: 10:36 上午
- * @param string $state
- * @return array|mixed
- */
- public static function auditStatusAttrDsl(string $state)
- {
- $map = [
- 'waitAudit' => [StatusCode::$auditStatus['auditing']],
- 'waitOutStock' => [StatusCode::$auditStatus['auditPass']],
- 'hasOutStock' => [StatusCode::$auditStatus['auditPass']],
- 'finish' => [StatusCode::$auditStatus['auditPass']],
- 'close' => [],
- 'all' => []
- ];
- return isset($map[$state]) ? $map[$state] : [];
- }
- /**
- * Doc: (des="state对应订单状态映射")
- * User: XMing
- * Date: 2020/7/13
- * Time: 10:43 上午
- * @param string $state
- * @return array|mixed
- */
- public static function orderStatusAttrDsl(string $state)
- {
- $map = [
- 'waitAudit' => [StatusCode::$orderStatus['waitPay'], StatusCode::$orderStatus['waitDelivery']],
- 'waitOutStock' => [StatusCode::$orderStatus['waitPay'], StatusCode::$orderStatus['waitDelivery']],
- 'hasOutStock' => [StatusCode::$orderStatus['waitReceive']],
- 'finish' => [StatusCode::$orderStatus['finish']],
- 'close' => [StatusCode::$orderStatus['close']],
- 'all' => []
- ];
- return isset($map[$state]) ? $map[$state] : [];
- }
- /**
- * 再次支付
- *
- * @param $params
- * @param $ip
- * @return ResultWrapper
- * @throws \Exception
- */
- public function payOrder($params, $ip)
- {
- // file_put_contents('/www/wwwroot/logs/api.junhailan.com/pay_params.log', date('Y-m-d H:i:s') . '再次支付订单数据:' . var_export($params, true) . PHP_EOL, FILE_APPEND);
- //order表切表
- $fix = 1;
- $this->objDOrder->setTable('qianniao_order_'.$this->onlineEnterpriseId.'_'.$fix);
- $this->objDOrderIndex->setTable('qianniao_order_index_'.$this->onlineEnterpriseId);
- $status = $this->objDOrder->beginTransaction();
- //再次支付更新extend值
- $extend = [];
- // 处理混合支付数据
- if( !empty($params['admixPayData']) ){
- $extend['admixPayData'] = $params['admixPayData'];
- }
- // 处理银行打款数据
- if( !empty($params['bankData']) ){
- $extend['bankData'] = $params['bankData'];
- }
- $extend = json_encode($extend);
- //再次付款更新extend(付款信息)
- $updateExtend = $this->objDOrder->update(['extends'=>$extend],['no' => $params['no']]);
- if ($updateExtend === false) {
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- if($status){
- $this->objDOrder->commit();
- }
- $orderData = $this->objDOrder->get(['no' => $params['no']]);
- if ($orderData === false) {
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- if (empty($orderData)) {
- return ResultWrapper::fail('没有找到订单', ErrorCode::$paramError);
- }
- $params['payType'] = explode(',', $params['payType']);
- $this->objDOrder->beginTransaction();
- //再次支付时订单支付方式改为了货到付款
- //if ($params['payType'] == StatusCode::$payType['cashPay']) {
- if ( in_array(StatusCode::$payType['cashPay'], $params['payType']) || in_array(StatusCode::$payType['bankLoans'],$params['payType'])) {
- //修改订单的支付方式
- if(in_array(StatusCode::$payType['cashPay'], $params['payType'])){//货到付款 订单状态为待发货
- $update = [
- 'payType' => StatusCode::$payType['cashPay'],
- 'orderStatus' => StatusCode::$orderStatus['waitDelivery']
- ];
- } else{//银行打款 订单状态为代发货
- $update = [
- 'payType' => StatusCode::$payType['bankLoans'],
- 'orderStatus' => StatusCode::$orderStatus['waitPay'],
- 'payStatus' => StatusCode::$delete
- ];
- }
- $dbResult = $this->objDOrder->update($update, ['no' => $params['no']]);
- if ($dbResult === false) {
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- unset($dbResult);
- //修改索引表支付方式
- $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId);
- $dbResult = $this->objDOrderIndex->update($update, ['id' => $orderData['id']]);
- if ($dbResult === false) {
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
- }
- /*
- //修改ES,支付方式
- $_id = self::createEsDocumentId($orderData['id']);
- $this->objDOrder->esupdateTypeFieldVaule(['payType' => StatusCode::$payType['cashPay']], $_id);*/
- $this->objDOrder->commit();
- //订单是否自动审核
- $objMBasicSetup = new MBasicSetup($this->onlineEnterpriseId);
- //获取基本配置
- $setupResult = $objMBasicSetup->getBasicField('autoAuditOrder');
- $autoAuditOrder = [];
- if ($setupResult->isSuccess()) {
- $autoAuditOrder = $setupResult->getData();//自动审核配置数据
- $autoAuditOrder = isset($autoAuditOrder['autoAuditOrder']) ? $autoAuditOrder['autoAuditOrder'] : [];
- }
- //货到付款是否开启了自动审核
- $autoAudit = isset($autoAuditOrder['cashPay']) ? $autoAuditOrder['cashPay'] : StatusCode::$delete;
- if ($autoAudit == StatusCode::$standard) {
- //开启了自动审核,审核订单
- $auditResult = self::updateAuditStatus([
- 'id' => $orderData['id'],
- 'audit' => '自动审核',
- 'auditId' => $this->onlineUserId,
- 'auditStatus' => StatusCode::$auditStatus['auditPass']
- ]);
- }
- return ResultWrapper::success($dbResult);
- }
- //获取客户信息
- $objMCustomer = new MCustomer($this->onlineEnterpriseId, $this->onlineUserId);
- $customerData = $objMCustomer->getCustomerInfoByUserCenterId($this->onlineUserId);
- if (!$customerData->isSuccess()) {
- return ResultWrapper::fail($customerData->getData(), $customerData->getErrorCode());
- }
- $customerData = $customerData->getData();
- $payType = $params['payType'];
- rsort($payType);
- $payment = [];
- $payParams = '';
- $payStatus = StatusCode::$partion;
- $orderStatus = StatusCode::$orderStatus['waitPay'];
- if( in_array(StatusCode::$payType['bankLoans'],$payType) ){
- $payStatus = StatusCode::$delete;
- $orderStatus = StatusCode::$orderStatus['waitPay'];
- }
- foreach($payType as $k => $v){
- // 除了余额支付其他方式都要获取支付配置
- if($v != StatusCode::$payType['balance']){
- $objMPaymentSetting = new MPaymentSetting($this->onlineUserId, $this->onlineEnterpriseId);
- $result = $objMPaymentSetting->getPayData($v);
- if (!$result->isSuccess() || empty($result->getData())) {
- return ResultWrapper::fail('获取微信配置错误', ErrorCode::$configEroor);
- }
- $payment = $result->getData();
- }
- switch (true){
- case in_array(StatusCode::$payType['balance'], $payType):
- //余额支付
- //$objMCustomer = new MCustomer($this->onlineEnterpriseId,$this->onlineUserId);
- //减少余额()
- $status = $this->objDOrderIndex->beginTransaction();
- //新增会员流水记录
- $memberBalanceDetailData = [
- 'customerId' => $orderData['customerId'],
- 'type' => StatusCode::$delete,
- 'userCenterId' => $this->onlineUserId,
- 'purpose' => '创建订单消费',
- 'orderIds' =>implode(',',[$orderData['id']]),
- 'remark' => '订单id'.implode(',',[$orderData['id']]),
- 'financeType' => '会员余额消费'
- ];
- // 组合支付方式
- if( !empty($params['admixPayData']) ) {
- foreach ($params['admixPayData'] as $key => $value) {
- if ($value['payType'] == StatusCode::$payType['balance']) {
- // 本次混合支付余额支付金额
- $memberBalanceDetailData['money'] = $value['payMoney'];
- // 总金额 - 余额支付金额 = 剩余需要搭配支付金额
- $orderData['payAmount'] = bcsub($orderData['payAmount'], $value['payMoney'], 2);
- }
- }
- }else{
- $payStatus = StatusCode::$standard;
- $orderStatus = StatusCode::$orderStatus['waitDelivery'];
- $memberBalanceDetailData['money'] = $orderData['payAmount'];
- }
- $objMMemberBalanceDetail = new MMemberBalanceDetail($this->onlineEnterpriseId,$this->onlineUserId);
- $memberBalanceDbResult = $objMMemberBalanceDetail->addMemberBalanceDetail($memberBalanceDetailData);
- if (!$memberBalanceDbResult->isSuccess()) {
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($memberBalanceDbResult->getData(), $memberBalanceDbResult->getErrorCode());
- }
- //扣除失败->订单未支付
- if ($memberBalanceDbResult->isSuccess()){
- $time = time();
- //扣除成功->订单支付成功\
- foreach ([$orderData['id']] as $orderId){
- $updateIndexResult = $this->objDOrderIndex->update(['payStatus' => $payStatus,'orderStatus' => $orderStatus,'updateTime' => $time],$orderId);
- if ($updateIndexResult === false){
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($this->objDOrderIndex->error(),ErrorCode::$dberror);
- }
- $updateIndex = $this->objDOrder->update(['payStatus' => $payStatus,'orderStatus' => $orderStatus,'payTime'=> $time,'updateTime' => $time,'payAmount'=>$memberBalanceDetailData['money']],$orderId);
- if ($updateIndex === false){
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror);
- }
- }
- }
- $status && $this->objDOrderIndex->commit();
- $payParams = ResultWrapper::success([]);
- break;
- case in_array(StatusCode::$payType['aliPay'], $payType):
- //ali
- /*********读取支付宝支付参数(原配置)*********/
- /**$aliPayConfigData = Factory::config()->get('alipay');
- * if (empty($aliPayConfigData)) {
- * return ResultWrapper::fail('支付宝配置错误', ErrorCode::$configEroor);
- * }*/
- $payOrderData = [
- 'subject' => '千鸟云商',
- 'out_trade_no' => $orderData['no'],
- 'total_amount' => $orderData['payAmount'],
- 'passback_params' => $this->onlineEnterpriseId . '|' . $this->onlineUserId . '|' . implode('|', [$orderData['id']]),
- ];
- $aliPayConfigData = [
- 'appid' => $payment['appid'],
- 'rsaPrivateKey' => $payment['rsaPrivateKey'],
- 'alipayrsaPublicKey' => $payment['alipayrsaPublicKey'],
- ];
- $objAliPay = new aliPay($aliPayConfigData['appid'], $aliPayConfigData['rsaPrivateKey'], $aliPayConfigData['alipayrsaPublicKey']);
- $payParams = $objAliPay->appPay($payOrderData);
- break;
- case in_array(StatusCode::$payType['wxPay'], $payType):
- //wx
- /********************生成小程序唤起支付用到的参数(原配置)*****/
- /**$weixinConfigData = Factory::config()->get('weixin');
- * if (empty($weixinConfigData)) {
- * return ResultWrapper::fail('微信配置错误', ErrorCode::$configEroor);
- * }*/
- // 获取当前登录企业的小程序配置
- $objSystemCache = new SystemCache();
- $miniprogramSetting = $objSystemCache->getAppIdByEnterpriseId($this->onlineEnterpriseId);
- if (empty($miniprogramSetting)) {
- return ResultWrapper::fail('后台小程序配置项为空', ErrorCode::$configEroor);
- }
- $miniprogramSetting = json_decode($miniprogramSetting, true);//获取小程序appid
- // 获取配置文件微信公众号
- /**$weixinConfigData = Factory::config()->get('weixin');
- * if (empty($weixinConfigData)) {
- * return ResultWrapper::fail('微信配置错误', ErrorCode::$configEroor);
- * }*/
- switch ($params['source']) {
- case StatusCode::$source['ByteProgram'];
- //$appid = $weixinConfigData['offiaccount']['appid'];
- $appid = $miniprogramSetting['appid'];
- $paySource = 'byteDanceH5';
- break;
- case StatusCode::$source['miniProgram'];
- $appid = $miniprogramSetting['appid'];
- $paySource = 'miniProgram';
- break;
- default :
- $appid = $payment['mobileAppid'];
- $paySource = 'APP';
- break;
- }
- $weixinConfigData = [
- 'mch_id' => $payment['mchId'],
- 'apiPartnerKey' => $payment['apiPartnerKey'],
- 'appid' => $appid
- ];
- $attach = $this->onlineEnterpriseId . '|' . $this->onlineUserId . '|' . implode('|', [$orderData['id']]);
- //$objPay = new Pay($appid, $weixinConfigData['pay']['mch_id'], $weixinConfigData['pay']['apiPartnerKey']);//old
- $objPay = new Pay($appid, $weixinConfigData['mch_id'], $weixinConfigData['apiPartnerKey']);
- $payParams = $objPay->unifiedorder($orderData['no'],$orderData['payAmount'], $ip, $paySource, '千鸟云商', $customerData['openId'], $attach);
- break;
- case in_array(StatusCode::$payType['byte'],$payType):
- //字节跳动
- $mweb_url = '';
- //读取缓存配置
- //$objSystemCache->getByteDanceSetting($this->onlineEnterpriseId);
- // 获取配置文件字节小程序
- $byteDanceConfigData = Factory::config()->getAppoint('byteDance', 'pay');
- if (empty($byteDanceConfigData)) {
- return ResultWrapper::fail('字节跳动配置错误', ErrorCode::$configEroor);
- }
- $objbytePay = new bytePay($byteDanceConfigData['appid'], $byteDanceConfigData['merchant_id'], $byteDanceConfigData['app_secret']);
- unset($payParams);
- $payParams = $objbytePay->pay($orderData['no'],$orderData['payAmount'], '千鸟云商', $ip, $mweb_url);
- break;
- case in_array(StatusCode::$payType['bankLoans'], $payType):
- $payParams = ResultWrapper::success([$orderData['id']]);
- break;
- default:
- //TODO
- return ResultWrapper::fail('暂未开放的支付方式',ErrorCode::$paramError);
- break;
- }
- unset($payType[$k]);
- if (!$payParams->isSuccess()) {
- return ResultWrapper::fail($payParams->getData(), $payParams->getErrorCode());
- }
- }
- return ResultWrapper::success($payParams->getData());
- }
- /**
- * 增加打印次数
- * @param $id
- * @return ResultWrapper
- */
- public function printIncr($id)
- {
- $dbResult = $this->objDOrder->set_inc('printingNum', ['id' => $id]);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- return ResultWrapper::success($dbResult);
- }
- /**
- * todo(保存编辑(废弃))
- *
- * @param $params
- * @return ResultWrapper
- * @throws \Exception
- */
- public function saveEdit($params)
- {
- $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId);
- $objMOrderGoods = new MOrderGoods($this->onlineUserId, $this->onlineEnterpriseId);
- $objMShippingAddress = new MShippingAddress($this->onlineEnterpriseId);
- $objMOrderReceive = new MOrderReceive($this->onlineUserId, $this->onlineEnterpriseId);
- $order = $this->objDOrder->get(['id' => $params['orderId']]);
- if ($order === false) {
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- if (empty($order)) {
- return ResultWrapper::fail('订单不存在', ErrorCode::$paramError);
- }
- if (!isset($order['auditStatus'])
- || $order['auditStatus'] == StatusCode::$auditStatus['auditPass']
- || $order['payStatus'] == StatusCode::$standard
- ) {
- return ResultWrapper::fail('订单不能编辑', ErrorCode::$paramError);
- }
- //根据地址id获取地址信息
- $dbResult = $objMShippingAddress->getShippingAddressInfo($params['receiveAddressId']);
- if (!$dbResult->isSuccess()) {
- return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror);
- }
- $addressData = $dbResult->getData();
- if (empty($addressData)) {
- return ResultWrapper::fail('收货地址信息不存在', ErrorCode::$dberror);
- }
- //锁定库存 查询商铺对应的仓库
- $objMWarehouse = new MWarehouse($this->onlineEnterpriseId);
- $warehouseData = $objMWarehouse->getWarehouseInfo(['shopId' => $params['goodsData']['goodsData'][0]['shopId']]);
- if (!$warehouseData->isSuccess()) {
- return ResultWrapper::fail($params['goodsData']['goodsData'][0]['shopId'] . $warehouseData->getData(), $warehouseData->getErrorCode());
- }
- $warehouse = $warehouseData->getData();
- $commonData = $params['goodsData'];
- $this->objDOrder->beginTransaction();
- //先解锁库存
- // $objMInventory = new MInventory($this->onlineEnterpriseId, $this->onlineUserId);
- // $unlockResult = $objMInventory->unlockInventory([$order['id']], StatusCode::$orderType['saleOrder'], $order['createTime']);
- // if (!$unlockResult->isSuccess()) {
- // $this->objDOrder->rollBack();
- // return ResultWrapper::fail($unlockResult->getData(), ErrorCode::$dberror);
- // }
- $dbResult = $this->objDOrderIndex->update(['deliveryType' => $params['deliveryType']], ['id' => $params['orderId']]);
- if ($dbResult === false) {
- $this->objDOrder->rollBack();
- return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
- }
- //修改Order表中的数据
- $dbResult = $this->objDOrder->update([
- 'totalMoney' => $commonData['totalMoney'],
- 'payAmount' => $commonData['payMoney'],
- 'deliveryType' => $params['deliveryType'],
- 'buyTotal' => array_sum(array_column($commonData['goodsData'], 'buyNum'))
- ], ['id' => $params['orderId']]);
- if ($dbResult === false) {
- $this->objDOrder->rollBack();
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- unset($dbResult);
- //修改OrderGoods表中的数据
- if (!empty($params['delOrderGoodsIds'])) {
- $dbResult = $objMOrderGoods->updateDetails(['deleteStatus' => StatusCode::$delete], ['id' => $params['delOrderGoodsIds']]);
- if (!$dbResult->isSuccess()) {
- $this->objDOrder->rollBack();
- return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror);
- }
- unset($dbResult);
- }
- //查询当前订单商品,进行比对
- $dbResult = $objMOrderGoods->getDetails([
- 'orderId' => $params['orderId'],
- 'deleteStatus' => StatusCode::$standard,
- ]);
- if (!$dbResult->isSuccess()) {
- $this->objDOrder->rollBack();
- return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror);
- }
- $oldGoodsData = $dbResult->getData();
- $hash = [];
- foreach ($oldGoodsData as $goods) {
- $hash[] = md5($goods['goodsId'] . $goods['skuId']);
- }
- $lockInventoryData = [];
- foreach ($commonData['goodsData'] as $value) {
- foreach ($value['shopGoodsData'] as $key => $val) {
- $rowHash = md5($val['goodsId'] . $val['skuId']);
- if (in_array($rowHash, $hash)) {
- //update
- $dbResult = $objMOrderGoods->updateDetails(
- [
- 'buyNum' => $val['buyNum'],
- 'price' => $val['price'],
- 'originPrice' => $val['originPrice'],
- 'totalMoney' => $val['totalMoney'],
- ],
- ['orderId' => $params['orderId'], 'goodsId' => $val['goodsId'], 'skuId' => $val['skuId']]
- );
- if (!$dbResult->isSuccess()) {
- $this->objDOrder->rollBack();
- return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror);
- }
- } else {
- //insert
- $dbResult = $objMOrderGoods->addOrderGoods([
- 'no' => $order['no'],
- 'orderId' => $params['orderId'],
- 'goodsId' => $val['goodsId'],
- 'goodsName' => $val['goodsName'],
- 'shopId' => $val['shopId'],//商铺id
- 'shopName' => $val['shopName'],//商铺名称
- 'originPrice' => $val['originPrice'],
- 'price' => $val['price'],
- 'buyNum' => $val['buyNum'],
- 'totalMoney' => $val['totalMoney'],
- 'skuId' => $val['skuId'],
- 'goodsBasicId' => $val['goodsBasicId'],
- 'goodsCode' => $val['goodsCode'],
- 'deliverNum' => $val['buyNum'],//发货数量=购买数量
- 'unitName' => $val['unitName'],//单位名称
- 'conversion' => $val['conversion'],//换算比率
- 'preferential' => $val['preferential'],//优惠券优惠金额
- 'vipDiscount' => $val['vipDiscount'],//会员卡优惠金额
- ]);
- if (!$dbResult->isSuccess()) {
- $this->objDOrder->rollBack();
- return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror);
- }
- }
- //锁定库存数据
- $lockInventoryData[] = [
- 'warehouseId' => $warehouse['id'],
- 'materielId' => $val['goodsBasicId'],
- 'lockingNum' => empty((float)($val['conversion'])) ? $val['buyNum'] : bcdiv($val['buyNum'], $val['conversion']),
- 'originId' => $params['orderId'],
- 'originNo' => $order['no'],
- 'source' => StatusCode::$orderType['saleOrder'],
- 'sourceNo' => $order['no'],
- 'operatorId' => $order['customerId'],
- 'operatorName' => $order['customerName'],
- 'skuId' => $val['skuId'],
- ];
- }
- }
- //锁定库存
- // $lockInventoryResult = $objMInventory->updateLockInventory($lockInventoryData);
- // if (!$lockInventoryResult->isSuccess()) {
- // $this->objDOrder->rollBack();
- // return ResultWrapper::fail($lockInventoryResult->getData(), $lockInventoryResult->getErrorCode());
- // }
- //修改收货人
- $dbResult = $objMOrderReceive->updateReceive(
- [
- 'customerCode' => $addressData['customerCode'],//客户编码
- 'realName' => $addressData['name'],//收货人姓名
- 'mobile' => $addressData['mobile'],//收货人电话
- 'address' => $addressData['address'],//收货人详细地址
- 'provinceCode' => $addressData['provinceCode'],
- 'cityCode' => $addressData['cityCode'],
- 'districtCode' => $addressData['districtCode'],
- ],
- [
- 'orderId' => $params['orderId']
- ]
- );
- if (!$dbResult->isSuccess()) {
- $this->objDOrder->rollBack();
- return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror);
- }
- $this->objDOrder->commit();
- /*
- $_id = self::createEsDocumentId($params['orderId']);
- $this->objDOrder->esupdateTypeFieldVaule([
- 'totalMoney' => $commonData['totalMoney'],
- 'payAmount' => $commonData['payMoney'],
- 'buyTotal' => array_sum(array_column($commonData['goodsData'], 'buyNum')),//购买总数
- 'deliveryType' => $params['deliveryType'],
- 'realName' => $addressData['name'],//收货人姓名
- 'mobile' => $addressData['mobile'],//收货人电话
- 'address' => $addressData['address'],//收货详细地址
- 'provinceCode' => $addressData['provinceCode'],//收货人省份编码
- 'cityCode' => $addressData['cityCode'],//收货人城市编码
- 'districtCode' => $addressData['districtCode'],//收货人区编码
- ], $_id);
- //修改es中的数据*/
- return ResultWrapper::success('操作成功');
- }
- /**
- * 订单编辑(现在只能编辑订单支付金额)
- * @param $params
- * @return ResultWrapper
- */
- public function orderEdit($params)
- {
- $order = $this->objDOrder->get(['id' => $params['orderId']]);
- if ($order === false) {
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- if (empty($order)) {
- return ResultWrapper::fail('订单不存在', ErrorCode::$paramError);
- }
- if (!isset($order['auditStatus'])
- || $order['auditStatus'] == StatusCode::$auditStatus['auditPass']
- || $order['payStatus'] == StatusCode::$standard
- ) {
- return ResultWrapper::fail('订单不能编辑', ErrorCode::$paramError);
- }
- //修改payAmount,将payAmount复制到字段originPayAmount
- $update = [
- 'payAmount' => sprintf("%.2f", $params['editAmount']),
- 'originPayAmount' => $order['payAmount'],//原付款金额
- ];
- $dbResult = $this->objDOrder->update($update, ['id' => $params['orderId']]);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- /*
- //修改es中的数据
- $_id = self::createEsDocumentId($params['orderId']);
- $this->objDOrder->esupdateTypeFieldVaule([
- 'payAmount' => $update['payAmount'],
- 'originPayAmount' => $update['originPayAmount'],//原付款金额
- ], $_id);*/
- return ResultWrapper::success('操作成功');
- }
- /**
- * Doc: (des="")
- * User: XMing
- * Date: 2020/9/2
- * Time: 9:16 上午
- * @param array $params
- * @return ResultWrapper
- *
- * @throws \Exception
- */
- public function cashierOrder(array $params)
- {
- $objMUserCoupon = new MUserCoupon($this->onlineUserId, $this->onlineEnterpriseId);
- $objMCustomer = new MCustomer($this->onlineEnterpriseId, $this->onlineUserId);
- $objMCustomerBalance = new MCustomerBalance($this->onlineEnterpriseId, $this->onlineUserId);
- $objMCart = new MCart($this->onlineUserId, $this->onlineEnterpriseId);
- $objMOrderGoods = new MOrderGoods($this->onlineUserId, $this->onlineEnterpriseId);
- $objDStaff = new DStaff();
- $objStockCache = new Stock($this->onlineEnterpriseId);
- $objDStaff->setTable('qianniao_staff_' . $this->onlineEnterpriseId);
- $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId);
- $goodsCommonData = $params['goodsData'];
- //锁定库存 查询商铺对应的仓库
- $objMShop = new MShop($this->onlineEnterpriseId, $this->onlineUserId);
- $modelResult = $objMShop->getShopDataByShopIds(array_column($goodsCommonData['goodsData'], 'shopId'));
- if (!$modelResult->isSuccess()) {
- return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
- }
- $shopData = $modelResult->getData();
- if (empty($shopData)) {
- return ResultWrapper::fail('获取店铺数据失败', ErrorCode::$paramError);
- }
- //获取收银员信息
- $allUids = [$this->loginUserCenterId];
- if (isset($params['guideUids']) && !empty($params['guideUids'])) {
- $ids = explode(',', $params['guideUids']);
- $allUids = array_merge($allUids, $ids);
- }
- $userMap = [];
- if (!empty($allUids)) {
- $staffList = $objDStaff->select(['userCenterId' => $allUids], 'userCenterId,staffName');
- if ($staffList === false) {
- return ResultWrapper::fail($objDStaff->error(), ErrorCode::$dberror);
- }
- foreach ($staffList as $value) {
- $userMap[$value['userCenterId']] = $value['staffName'];
- }
- }
- $params['cashierName'] = isset($userMap[$this->loginUserCenterId]) ? $userMap[$this->loginUserCenterId] : '超级管理员';
- $nameStr = '';
- if (!empty($ids)) {
- foreach ($ids as $uid) {
- if (!empty($nameStr)) {
- $nameStr .= ',';
- }
- $nameStr .= isset($userMap[$uid]) ? $userMap[$uid] : '';
- }
- }
- $params['guideName'] = $nameStr;
- $params['customerMobile'] = '';
- //获取客户信息
- $customerOwe = 0;
- if ($this->onlineUserId == StatusCode::$noneUserCenter) {
- $customerData = [
- 'id' => StatusCode::$noneCustomer,
- 'name' => '匿名客户'
- ];
- } else {
- $customerDataResult = $objMCustomer->getCustomerInfoByUserCenterId($this->onlineUserId);
- if (!$customerDataResult->isSuccess()) {
- return ResultWrapper::fail($customerDataResult->getData(), $customerDataResult->getErrorCode());
- }
- $customerData = $customerDataResult->getData();
- //获取客户当前欠款
- if (isset($customerData['id'])) {
- $customerOwe = $objMCustomerBalance->getCustomerBalance($customerData['id']);
- }
- //获取客户手机号
- $objDUserCenter = new DUserCenter();
- $userInfo = $objDUserCenter->get(['id' => $this->onlineUserId], 'mobile');
- if ($userInfo === false) {
- return ResultWrapper::fail($objDUserCenter->error(), ErrorCode::$dberror);
- }
- $params['customerMobile'] = isset($userInfo['mobile']) ? $userInfo['mobile'] : '';
- }
- // 生成一个临时三方流水号,用来支持多个子订单作为一个订单支付,支付成功之后更新为对应的实际外部支付流水号
- $tmpOuterTradeNo = 'tmp' . createOrderSn($params['source'], StatusCode::$orderType['cashierOrder'], $this->onlineUserId);
- $lockInventoryData = [];//锁定库存物料
- $goodsSaleData = [];//销售数据
- $allSn = [];//所有单号
- $allOrderIds = [];//所有订单
- $mapDetails = [];//订单商品
- $createTime = time();
- $allCartIds = [];
- $shopName = '';
- $shopId = 0;//目前只有一个
- $this->objDOrder->beginTransaction();
- foreach ($goodsCommonData['goodsData'] as $key => $val) {
- $sn = createOrderSn($params['source'], StatusCode::$orderType['saleOrder'], $this->onlineUserId);
- //将数据写入索引表
- $shopId = $val['shopId'];
- $orderIndexData = [
- 'shopId' => $val['shopId'],
- 'userCenterId' => $params['userCenterId'],
- 'salesManId' => isset($customerData['salesManId']) ? $customerData['salesManId'] : 0,
- 'createTime' => time(),
- 'updateTime' => time(),
- 'deleteStatus' => StatusCode::$standard,
- 'auditStatus' => StatusCode::$auditStatus['auditing'],
- 'payStatus' => StatusCode::$delete,
- 'orderStatus' => StatusCode::$orderStatus['waitPay'],
- 'outStatus' => StatusCode::$delete,
- 'returnStatus' => StatusCode::$orderReturn['notReturn'],
- 'deliveryType' => $params['deliveryType'],
- 'payType' => $params['payType'],
- 'customerId' => isset($customerData['id']) ? $customerData['id'] : 0,
- 'no' => $sn,
- 'orderType' => StatusCode::$orderType['cashierOrder'],
- 'selfRuleId' => 0,
- 'cashierUid' => $this->loginUserCenterId,
- 'guideUids' => $params['guideUids']
- ];
- //1. 先写索引表
- $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId);
- $orderId = $this->objDOrderIndex->insert($orderIndexData);
- if ($orderId === false) {
- $this->objDOrder->rollBack();
- return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
- }
- //3。上门自提订单,生成核销码
- $verifyCode = self::createVerifyCode($orderId);
- //兼容以前代码
- $updateRes = $this->objDOrderIndex->update(['verifyCode' => $verifyCode], ['id' => $orderId]);
- if ($updateRes === false) {
- $this->objDOrder->rollBack();
- return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
- }
- //订单数据
- $shopName = $val['shopName'];//现在就一个店铺
- $masterOrder = [
- 'id' => $orderId,//订单id
- 'customerId' => isset($customerData['id']) ? $customerData['id'] : 0,
- 'userCenterId' => $params['userCenterId'],
- 'shopId' => $val['shopId'],
- 'shopName' => $val['shopName'],
- 'no' => $sn,
- 'outerTradeNo' => $tmpOuterTradeNo,
- 'totalMoney' => $goodsCommonData['totalMoney'],
- 'payAmount' => $goodsCommonData['payMoney'],
- 'customerName' => isset($customerData['name']) ? $customerData['name'] : '',
- 'remark' => $params['remark'],
- 'deliveryType' => $params['deliveryType'],//配送方式
- 'payType' => $params['payType'],//支付方式
- 'salesManId' => isset($customerData['salesManId']) ? $customerData['salesManId'] : 0,
- 'salesManName' => isset($customerData['salesManName']) ? $customerData['salesManName'] : '',
- 'customerType' => isset($customerData['type']) ? $customerData['type'] : 0,
- 'buyTotal' => array_sum(array_column($val['shopGoodsData'], 'buyNum')),
- 'source' => $params['source'],//来源
- 'orderStatus' => StatusCode::$orderStatus['waitPay'],
- 'returnStatus' => StatusCode::$orderReturn['notReturn'],
- 'outStatus' => StatusCode::$delete,
- 'createTime' => time(),
- 'updateTime' => time(),
- 'customerOwe' => $customerOwe,//客户当前欠款
- 'auditStatus' => StatusCode::$auditStatus['auditing'],
- 'preferential' => $goodsCommonData['preferential'],//优惠券优惠金额
- 'vipDiscount' => isset($goodsCommonData['vipDiscount']) ? $goodsCommonData['vipDiscount'] : 0,//会员卡优惠金额
- 'vipDoubleDiscount' => isset($goodsCommonData['vipDoubleDiscount']) ? $goodsCommonData['vipDoubleDiscount'] : 0,//会员卡折上折优惠金额
- 'originPayAmount' => $goodsCommonData['payMoney'],//原支付金额,
- 'orderType' => StatusCode::$orderType['cashierOrder'],
- 'verifyCode' => $verifyCode,
- 'expressMoney' => isset($goodsCommonData['expressMoney']) ? $goodsCommonData['expressMoney'] : 0,
- 'cashierUid' => $this->loginUserCenterId,
- 'guideUids' => $params['guideUids'],
- 'cashierName' => $params['cashierName'],
- 'guideName' => $params['guideName'],
- 'remMoney' => isset($goodsCommonData['rem_money']) ? $goodsCommonData['rem_money'] : 0,
- 'changeSubMoney' => isset($goodsCommonData['subPrice']) ? $goodsCommonData['subPrice'] : 0,
- 'isNoneUser' => $this->onlineUserId == StatusCode::$noneUserCenter ? StatusCode::$standard : StatusCode::$delete,
- 'customerMobile' => $params['customerMobile'],
- 'serialNum' => $objStockCache->createSerialSn(0,'Order'),
- 'operatorName' => isset($params['operatorName']) ? $params['operatorName'] : '',
- 'operatorId' => isset($params['operatorId']) ? $params['operatorId'] : 0,
- ];
- $allOrderIds[] = $orderId;
- //2。订单表
- $orderId = $this->objDOrder->insert($masterOrder);
- if ($orderId === false) {
- $this->objDOrder->rollBack();
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- $masterOrder['goodsName'] = '';
- foreach ($val['shopGoodsData'] as $k => &$v) {
- $addOrderGoods = [
- 'no' => $sn,
- 'orderId' => $orderId,
- 'goodsId' => $v['goodsId'],
- 'goodsName' => $v['goodsName'],
- 'shopId' => $val['shopId'],//商铺id
- 'shopName' => $val['shopName'],//商铺名称
- 'originPrice' => $v['originPrice'],
- 'price' => $v['price'],
- 'buyNum' => $v['buyNum'],
- 'totalMoney' => $v['totalMoney'],
- 'skuId' => $v['skuId'],
- 'goodsBasicId' => $v['goodsBasicId'],
- 'goodsCode' => $v['goodsCode'],
- 'deliverNum' => $v['buyNum'],//发货数量=购买数量
- 'unitName' => $v['unitName'],//单位名称
- 'conversion' => $v['conversion'],//换算比率
- 'preferential' => $v['preferential'],//优惠券优惠金额
- 'vipDiscount' => $v['vipDiscount'],//会员卡优惠金额
- 'categoryPath' => isset($v['categoryPath']) ? $v['categoryPath'] : '',//分类路径
- 'brandId' => isset($v['brandId']) ? $v['brandId'] : 0,//品牌id
- 'specGroup' => isset($v['specGroup']) && !empty($v['specGroup']) ? json_encode($v['specGroup']) : NULL,
- 'goodsImages' => isset($v['goodsImages']) && is_string($v['goodsImages']) ? $v['goodsImages'] : '',
- 'barCode' => isset($v['barCode']) ? $v['barCode'] : '',
- 'storageCode' => isset($v['storageCode']) ? $v['storageCode'] : '',
- 'categoryName' => isset($v['categoryName']) ? $v['categoryName'] : '',
- 'brandName' => isset($v['brandName']) ? $v['brandName'] : '',
- 'expressMoney' => isset($v['expressMoney']) ? $v['expressMoney'] : 0,
- 'outNum' => 0,//已出库数量
- 'outOfNum' => getArrayItem($v, 'buyNum', 0),//未出库数量
- 'isEq' => getArrayItem($v,'isEq',StatusCode::$delete),
- 'extends' => json_encode(getArrayItem($v, 'extends', null)),
- ];
- $lockInventoryData[] = [
- 'warehouseId' => $shopData[$v['shopId']]['warehouseId'],
- 'materielId' => $v['goodsBasicId'],
- 'materielCode' => $v['goodsCode'],
- 'lockingNum' => $v['buyNum'],
- 'originId' => $orderId,
- 'originNo' => $sn,
- 'source' => StatusCode::$orderType['saleOrder'],
- 'sourceNo' => $sn,
- 'operatorId' => $masterOrder['customerId'],
- 'operatorName' => $masterOrder['customerName'],
- 'skuId' => $v['skuId'],
- ];
- $goodsSaleData [] = [
- 'goodsId' => $addOrderGoods['goodsId'],
- 'skuId' => $addOrderGoods['skuId'],
- 'buyNum' => $addOrderGoods['buyNum'],
- ];
- //活动商品数据
- if ($this->isFront) {
- if (isset($v['activityId']) && $v['activityId'] != 0) {
- $activityData[] = [
- 'goodsId' => $v['goodsId'],
- 'skuId' => $v['skuId'],
- 'activityId' => $v['activityId'],
- 'buyNum' => $v['buyNum']
- ];
- }
- }
- $masterOrder['goodsName'] .= $v['goodsName'] . ' ';
- $result = $objMOrderGoods->addOrderGoods($addOrderGoods);
- if (!$result->isSuccess()) {
- $this->objDOrder->rollBack();
- return ResultWrapper::fail($result->getData(), ErrorCode::$dberror);
- }
- $allCartIds[] = $v['cartId'];
- }
- //存入ES
- $masterOrder['verifyCode'] = isset($verifyCode) ? $verifyCode : '';
- self::updateEsData($orderId, $masterOrder, [], $masterOrder['goodsName']);
- $allSn[] = $sn;//所有订单号
- }
- $this->objDOrder->commit();
- $this->objDOrder->beginTransaction();
- //删除购物车内已生成订单商品
- $objMCashierCart = new MCashierCart($this->onlineUserId, $this->onlineEnterpriseId, $this->loginUserCenterId);
- $result = $objMCashierCart->delCart($allCartIds, true);
- if (!$result->isSuccess()) {
- $this->objDOrder->rollBack();
- return ResultWrapper::fail($result->getData(), ErrorCode::$dberror);
- }
- //将优惠券改为已使用
- if (isset($goodsCommonData['useCoupon']) && !empty($goodsCommonData['useCoupon'])) {
- $result = $objMUserCoupon->updateIsUse(['id' => $goodsCommonData['useCoupon']['id']], ['isUse' => StatusCode::$delete, 'useTime' => time()]);
- if (!$result->isSuccess()) {
- $this->objDOrder->rollBack();
- return ResultWrapper::fail($result->getData(), ErrorCode::$dberror);
- }
- }
- //锁定库存商品数量
- $objMInventory = new MInventory($this->onlineEnterpriseId, $this->onlineUserId);
- $lockInventoryResult = $objMInventory->updateLockInventory($shopId,$lockInventoryData);
- if (!$lockInventoryResult->isSuccess()) {
- $this->objDOrder->rollBack();
- return ResultWrapper::fail($lockInventoryResult->getData(), $lockInventoryResult->getErrorCode());
- }
- //增加销量
- $objMGoods = new MGoods($this->onlineEnterpriseId, false, $this->onlineUserId);
- if (!empty($goodsSaleData)) {
- foreach ($goodsSaleData as $value) {
- $res = $objMGoods->updateSalesNum($value['goodsId'], $value['skuId'], $value['buyNum']);
- if ($res === false) {
- Logger::logs(E_USER_ERROR, '错误', __CLASS__, __LINE__, '商品增加销量失败');
- }
- }
- }
- //file_put_contents('/www/wwwroot/logs/api.junhailan.com/MSaleOrder_error.log', date('Y-m-d H:i:s') . '数据:' . var_export($mapDetails, true) . PHP_EOL, FILE_APPEND);
- $this->objSaleOrder->setGoodsDetails($mapDetails);
- //统计订单信息
- self::noticeStatistics([
- 'userCenterId' => $params['userCenterId'],
- 'enterpriseId' => $this->onlineEnterpriseId,
- 'customerId' => $params['customerId'],
- 'no' => $allSn,
- 'noticeType' => 'create',
- ], 'MOrderStatistics');
- //写日志
- foreach ($allSn as $sn) {
- parent::saveLog([
- 'no' => $sn,
- 'actionType' => '创建订单',//创建订单
- 'operationData' => '',
- 'userCenterId' => $params['userCenterId'],
- 'enterpriseId' => $this->onlineEnterpriseId,
- 'createTime' => time(),
- ]);
- }
- //自动审核订单
- $objMInventoryOut = new MInventoryOut($this->onlineEnterpriseId, $this->onlineUserId);
- foreach ($allOrderIds as $key => $id) {
- //自动审核订单
- $auditResult = self::updateAuditStatus([
- 'id' => $id,
- 'audit' => '自动审核',
- 'auditId' => $this->onlineUserId,
- 'auditStatus' => StatusCode::$auditStatus['auditPass']
- ]);
- if (!$auditResult->isSuccess()) {
- $this->objDOrder->rollBack();
- return ResultWrapper::fail($auditResult->getData(), $auditResult->getErrorCode());
- }
- $outId = $auditResult->getData();//出库单id
- //自动出库
- $dbResult = $objMInventoryOut->updateInventoryOutStatus(['id' => $outId, 'auditId' => $this->loginUserCenterId, 'auditName' => '销售自动审核']);
- if (!$dbResult->isSuccess()) {
- $this->objDOrder->rollBack();
- return ResultWrapper::fail($dbResult->getData(), $dbResult->getErrorCode());
- }
- }
- //确认收款
- $dbResult = self::updateOrderPayData(['payStatus' => StatusCode::$standard, 'payTime' => time()], ['id' => $allOrderIds]);
- if (!$dbResult->isSuccess()) {
- $this->objDOrder->rollBack();
- return ResultWrapper::fail($dbResult->getData(), $dbResult->getErrorCode());
- }
- //确认收货
- foreach ($allOrderIds as $orderId) {
- $dbResult = self::updateOrderStatus($orderId, ['orderStatus' => StatusCode::$orderStatus['finish']], []);
- if (!$dbResult->isSuccess()) {
- $this->objDOrder->rollBack();
- return ResultWrapper::fail($dbResult->getData(), $dbResult->getErrorCode());
- }
- $objMCashier = new MCashier($this->onlineUserId, $this->onlineEnterpriseId);
- $cashierResult = $objMCashier->calculatePushMoney($orderId);
- if (!$cashierResult->isSuccess()) {
- Logger::logs(E_USER_ERROR, '订单提成计算失败', __CLASS__, __LINE__, $cashierResult->getData());
- }
- }
- //创建收款单
- $received = [
- 'currentAccountName' => $params['currentAccountName'],
- 'financeType' => '销售收款',
- 'financeTypeId' => 2,
- 'shopId' => $shopId,
- 'shopName' => $shopName,
- 'receiptTime' => time(),
- 'operatorId' => $this->loginUserCenterId,
- 'accountList' => $params['accountList'],
- 'customerId' => $customerData['id'],
- 'customerName' => $customerData['name'],
- 'sourceNo' => $sn,
- 'sourceNoMoney' => $goodsCommonData['payMoney'],
- 'createTime' => time(),
- 'auditStatus' => StatusCode::$auditStatus['auditing'],
- 'updateTime' => time(),
- ];
- $objMReceived = new MReceived($this->onlineEnterpriseId, $this->loginUserCenterId);
- $receivedResult = $objMReceived->addReceived($received, true);
- if (!$receivedResult->isSuccess()) {
- $this->objDOrder->rollBack();
- return ResultWrapper::fail($receivedResult->getData(), $receivedResult->getErrorCode());
- }
- $this->objDOrder->commit();
- if ($this->onlineUserId == StatusCode::$noneUserCenter) {
- $objDCashierCustomerPrice = new DCashierCustomerPrice();
- $objDCashierCustomerPrice->setTable('qianniao_cashier_customer_price_' . $this->onlineEnterpriseId);
- $objDCashierCustomerPrice->delete(['cashierUid' => $this->loginUserCenterId, 'customerUid' => StatusCode::$noneUserCenter]);
- }
- return ResultWrapper::success($orderId);
- }
- /**
- * 订单打印小票
- */
- public function printOrder()
- {
- $data = [];
- $goodsDetails = $this->objSaleOrder->getGoodsDetails();
- foreach ($goodsDetails as $value) {
- $data[$value['goodsId']]['title'] = $value['goodsName'];
- $data[$value['goodsId']]['skuData'][] = [
- 'skuName' => isset($value['specName']) ? $value['specName'] : '',
- 'unitName' => isset($value['unitName']) ? $value['unitName'] : '',
- 'unitPrice' => isset($value['unitPrice']) ? $value['unitPrice'] : 0.00,
- 'num' => isset($value['buyNum']) ? $value['buyNum'] : 0,
- 'amountPrice' => isset($value['totalMoney']) ? $value['totalMoney'] : 0
- ];
- }
- $printData = [
- 'createTime' => $this->objSaleOrder->getCreateTime(),
- 'shopName' => $this->objSaleOrder->getShopName(),
- 'title' => $this->objSaleOrder->getReceiptTitle(),
- 'codeName' => $this->objSaleOrder->getCodeName(),
- 'code' => $this->objSaleOrder->getNo(),
- 'userName' => $this->objSaleOrder->getCustomerName(),
- 'mobile' => $this->objSaleOrder->getCustomerMobile(),
- 'preferential' => $this->objSaleOrder->getPreferentialAmount(), //优惠金额
- 'totalMoney' => $this->objSaleOrder->getTotalAmount(),
- 'payAmount' => $this->objSaleOrder->getPayAmount(),
- 'address' => $this->objSaleOrder->getAddress(),
- 'details' => $data
- ];
- $formatPrint = parent::formatMsg($printData);
- $objCloudPrint = new CloudPrint();
- $objCloudPrint->sendMsg($formatPrint, $this->onlineEnterpriseId);
- }
- /**
- * 将所有商品库存转换为主单位sku
- * @param $data
- * @return array|ResultWrapper
- * @throws \Exception
- */
- public function formatMerge($data)
- {
- //将相同的商品合并到一起并启用到主单位的
- $allMapping = [];
- if (empty($data)) return $data;
- $allMapping = [];
- $all = [];
- $objMSku = new MSku($this->onlineUserId, $this->onlineEnterpriseId);
- $res = $objMSku->getMaterSkuId(['goodsId' => array_values(array_unique(array_column($data, 'goodsBasicId'))), 'isMaster' => StatusCode::$standard, 'deleteStatus' => StatusCode::$standard]);
- if (!$res->isSuccess()) {
- return ResultWrapper::fail($res->getData(), ErrorCode::$dberror);
- }
- $skuData = $res->getData();
- foreach ($data as &$goods) {
- $goods['masterSkuId'] = $skuData[$goods['goodsBasicId']];
- $allMapping[$goods['goodsId']][] = [
- 'buyNum' => $goods['conversion'] == 0 ? $goods['buyNum'] : bcdiv($goods['buyNum'], $goods['conversion'], 2),
- 'skuId' => $goods['skuId'],
- 'conversion' => $goods['conversion'],
- 'goodsId' => $goods['goodsId'],
- 'masterSkuId' => $goods['masterSkuId']
- ];
- }
- unset($goods);
- foreach ($allMapping as $key => $goods) {
- $all[] = [
- 'buyNum' => array_sum(array_column($allMapping[$key], 'buyNum')),
- 'goodsId' => $goods[0]['goodsId'],
- 'skuId' => $goods[0]['masterSkuId'],//都换算成主单位的
- ];
- }
- return ResultWrapper::success($all);
- }
- /**
- * 确认收款检测出库状态
- * @param $id
- * @return ResultWrapper
- */
- public function checkOutOrderStatus($id)
- {
- $dbResult = $this->objDOrder->get_field('outStatus', ['id' => $id]);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- if (empty($dbResult)) {
- return ResultWrapper::fail('没有找到订单信息', ErrorCode::$paramError);
- }
- if ($dbResult == StatusCode::$delete) {
- return ResultWrapper::fail('订单未出库暂时不能确认收款', ErrorCode::$paramError);
- }
- return ResultWrapper::success($dbResult);
- }
- /**
- * 销售订单毛利明细
- * @param $params
- * @return ResultWrapper
- * @throws \Exception
- */
- public function getOrderProfit($params,$export = 0)
- {
- $limit = $params['limit'];
- unset($params['limit']);
- $offset = $params['offset'];
- unset($params['offset']);
- if($export){
- $limit = 999;
- $offset = 0;
- }
- $modelResult = self::formatOrderTableName($params);
- if (!$modelResult->isSuccess()) {
- return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
- }
- $tables = $modelResult->getData();
- if (empty($tables)) {
- return ResultWrapper::fail('表后缀计算失败', ErrorCode::$paramError);
- }
- $whereSql = ' where o.shopId = ' . $params['shopId'] . ' and g.goodsId = ' . $params['goodsId'] . ' and o.createTime between ' . $params['start'] . ' and ' . $params['end'];
- if (isset($params['customerId']) && !empty($params['customerId'])) {
- $whereSql .= ' and customerId = ' . $params['customerId'];
- }
- $field = 'o.id as orderId,o.no,o.customerId,o.customerName,o.createTime,o.shopId,o.shopName,o.orderStatus,o.outStatus,o.orderType,g.goodsId,g.goodsCode,g.goodsName,g.price,g.buyNum,(g.preferential + g.vipDiscount) as discount, g.outCostPrice,g.goodsBasicId,g.skuId,g.totalMoney';
- $sql = '';
- foreach ($tables as $value) {
- !empty($sql) && $sql = $sql . ' union all ';
- $orderTableName = 'qianniao_order_' . $this->onlineEnterpriseId . '_' . $value;
- $orderGoodsTableName = 'qianniao_order_goods_' . $this->onlineEnterpriseId . '_' . $value;
- $sql = '(select ' . $field . ' from ' . $orderGoodsTableName . ' g left join ' . $orderTableName . ' o on o.id = g.orderId ' . $whereSql . ')';
- }
- $twoField = 'orderId,no,customerId,customerName,createTime,shopId,shopName,orderStatus,outStatus,orderType,goodsId,goodsCode,goodsName,price,buyNum,discount,outCostPrice,goodsBasicId,skuId,totalMoney';
- $sql = 'select ' . $twoField . ' from (' . $sql . ') as details ';
- $selectSql = $sql . 'order by createTime desc limit ' . $offset . ',' . $limit;
- $dbResult = $this->objDOrder->query($selectSql);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$paramError);
- }
- //提取客户数据
- if (empty($dbResult)) {
- return ResultWrapper::fail('查询结果为空', ErrorCode::$dberror);
- }
- $customerData = [];
- foreach ($dbResult as &$value) {
- if (!isset($customerData[$value['customerId']])) {
- $customerData[$value['customerId']] = [
- 'id' => $value['customerId'],
- 'name' => $value['customerName'],
- ];
- }
- //销售成本
- $value['saleCostAmount'] = bcmul($value['buyNum'], $value['outCostPrice'], 4);
- //销售毛利
- $value['saleProfitAmount'] = bcsub($value['totalMoney'], $value['saleCostAmount'], 8);
- //毛利率
- $value['saleProfitRate'] = "0.00";
- if ($value['saleProfitAmount'] > 0 && $value['saleCostAmount'] > 0) {
- $value['saleProfitRate'] = bcmul(bcdiv($value['saleProfitAmount'], $value['totalMoney'], 8), 100, 4);
- }
- }
- unset($value);
- if($export){
- self::exportOrderProfit($dbResult);
- exit;
- }
- $countSql = 'select count(orderId) as count from ( ' . $sql . ' ) as selectDetails';
- $totalDbResult = $this->objDOrder->query($countSql);
- if ($totalDbResult === false) {
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- $total = array_shift($totalDbResult)['count'];
- $return['data']['customerData'] = array_values($customerData);
- $return['data']['data'] = $dbResult;
- $return['total'] = ($total) ? intval($total) : 0;
- return ResultWrapper::success($return);
- }
- /**
- * 计算表名后缀
- * @param $params
- * @return ResultWrapper
- * @throws \Exception
- */
- public function formatOrderTableName($params)
- {
- $whereSql = '';
- if (isset($params['shopId']) && !empty($params['shopId'])) {
- $whereSql = empty($whereSql) ? $whereSql . ' where ' : $whereSql . ' and ';
- $whereSql .= ' shopId = ' . $params['shopId'];
- }
- if (isset($params['customerId']) && !empty($params['customerId'])) {
- $whereSql = empty($whereSql) ? $whereSql . ' where ' : $whereSql . ' and ';
- $whereSql .= ' customerId = ' . $params['customerId'];
- }
- if (isset($params['start']) && !empty($params['start']) && isset($params['end']) && !empty($params['end'])) {
- $whereSql = empty($whereSql) ? $whereSql . ' where ' : $whereSql . ' and ';
- $whereSql .= ' createTime between ' . $params['start'] . ' and ' . $params['end'];
- }
- $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId);
- $indexSql = 'select userCenterId from ' . $this->objDOrderIndex->get_Table() . $whereSql;
- $dbResult = $this->objDOrderIndex->query($indexSql);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$paramError);
- }
- if (empty($dbResult)) {
- return ResultWrapper::success([]);
- }
- $tables = [];
- foreach ($dbResult as $value) {
- //格式化数据 根据userCenterId 计算所有goods表名
- $num = (int)ceil($value['userCenterId'] / $this->cutTable);
- $tableName = 'qianniao_order_' . $this->onlineEnterpriseId . '_' . $num;
- $existsTable = $this->objDOrder->existsTable($tableName);
- if ($existsTable && !in_array($num, $tables)) {
- $tables[] = $num;
- }
- }
- return ResultWrapper::success($tables);
- }
- /************************************************统计项 start******************************************************/
- /**
- * @param $key
- * @param $shopId
- * @return ResultWrapper
- */
- public function businessOverview($key, $shopId)
- {
- $result = $this->objOverviewCache->getBusinessOverview($this->onlineEnterpriseId, $key, $shopId);
- return $result;
- }
- /**
- * 客单价
- * @param $key
- * @param $shopId
- * @return int|string
- */
- public function customerAverageMoney($key, $shopId)
- {
- $objCustomerCache = new CustomerCache();
- $orderConfirmedMoney = $this->objOverviewCache->getBusinessOverview($this->onlineEnterpriseId, 'orderConfirmedMoney', $shopId);//营业额
- $customerNum = array_sum($objCustomerCache->getTodayCustomerOrderInfo($this->onlineEnterpriseId, null, $shopId));
- if ($orderConfirmedMoney == 0 || $customerNum == 0) return 0;
- return bcdiv($orderConfirmedMoney, $customerNum, 2);
- }
- /**
- * 后置操作
- */
- public function __destruct()
- {
- // TODO: Implement __destruct() method.
- if ($this->isEnablePrint) self::printOrder();
- }
- /**
- * 今日下单客户数量
- * @param $shopId
- * @return int
- */
- public function getTodayCustomerOrderNum($shopId = null)
- {
- $todayStart = date('Y-m-d 00:00:00', time());
- $todayEnd = date('Y-m-d 23:59:59', time());
- $fields = 'id';
- $sql = 'SELECT ' . $fields . ' FROM qianniao_order_index_' . $this->onlineEnterpriseId . '
- WHERE auditStatus = ' . StatusCode::$auditStatus['auditPass'] . ' AND
- createTime BETWEEN ' . strtotime($todayStart) . ' AND ' . strtotime($todayEnd);
- if (!empty($shopId)) {
- $sql .= ' and shopId = ' . $shopId;
- }
- $sql .= ' GROUP BY customerId';
- $result = $this->objDOrder->query($sql);
- if ($result === false) {
- Logger::logs(E_USER_ERROR, '查询错误', __CLASS__, __LINE__, $this->objDOrder->error());
- return 0;
- }
- return count((array)$result);
- }
- /**
- * 今日客单价
- * @param null $shopId
- * @return int|string|null
- */
- public function getTodayOrder($shopId = null)
- {
- $todayStart = date('Y-m-d 00:00:00', time());
- $todayEnd = date('Y-m-d 23:59:59', time());
- $fields = 'userCenterId';
- if (!empty($shopId)) {
- $shopId = ' and shopId = ' . $shopId;
- }else{
- $shopId = '';
- }
- $sql = 'select count(distinct '.$fields.') as num ,sum(payAmount) as money from qianniao_order_'. $this->onlineEnterpriseId .'_1' .
- ' where auditStatus = ' . StatusCode::$auditStatus['auditPass'] .'
- and createTime BETWEEN '.strtotime($todayStart). ' and '. strtotime($todayEnd).$shopId;
- $result = $this->objDOrder->query($sql);
- if ($result === false) {
- return 0;
- }
- $num = $result[0]['num'];
- $money = $result[0]['money'];
- if (empty($money) || empty($num)) {
- return 0;
- }
- return bcdiv($money, $num, 2);
- }
- /**
- * Doc: (des="订单分配业务员")
- * User: XMing
- * Date: 2020/8/26
- * Time: 3:39 下午
- * @param array $params
- * @return ResultWrapper
- * @throws \Exception
- */
- public function setSalesMan(array $params)
- {
- //在索引表中查询订单
- $orderIndex = $this->objDOrderIndex->get(['id' => $params['orderId']]);
- if ($orderIndex === false) {
- return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
- }
- if (empty($orderIndex)) {
- return ResultWrapper::fail('未查询到指定订单', ErrorCode::$paramError);
- }
- if (!empty($orderIndex['salesManId'])) {
- return ResultWrapper::fail('已分配过业务员', ErrorCode::$paramError);
- }
- $dbResult = $this->objDCustomer->get(['id' => $orderIndex['customerId']]);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- $customerInfo = $dbResult;
- if (empty($customerInfo)) {
- return ResultWrapper::fail('未查询到指定客户', ErrorCode::$dberror);
- }
- if($params['ifSalesMan'] == StatusCode::$delete){
- if ( !empty($customerInfo['salesManId']) && $customerInfo['salesManId'] != $params['salesManId'] ) {
- return ResultWrapper::fail('客户只能分配当前 -'.$customerInfo['salesManName'].' -业务员', ErrorCode::$paramError);
- }
- $salesManId = $params['salesManId'];
- $salesManName = $params['salesManName'];
- }else{
- $salesManId = $customerInfo['salesManId'];
- $salesManName = $customerInfo['salesManName'];
- }
- //更新数据
- $time = time();
- $beginStatus = $this->objDOrderIndex->beginTransaction();
- //给客户分配业务员
- if($params['ifSalesMan'] == StatusCode::$delete){
- $dbResult = $this->objDCustomer->update(['salesManId' => $salesManId, 'salesManName' => $salesManName], ['id' => $orderIndex['customerId']]);
- if ($dbResult === false) {
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- }
- //更新订单表
- //只更新该订单
- $dbResult = $this->objDOrderIndex->update(['salesManId' => $salesManId, 'updateTime' => $time], ['id' => $params['orderId']]);
- if($dbResult === false){
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
- }
- $updateData = ['salesManId' => $salesManId, 'salesManName' => $salesManName, 'updateTime' => $time];
- $dbResult = $this->objDOrder->update($updateData, ['id' => $params['orderId']]);
- if($dbResult === false){
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- /* //获取此客户未分配业务员的订单
- $orderIndexLists = $this->objDOrderIndex->select(['salesManId' => 0, 'customerId' => $orderIndex['customerId']]);
- if ($orderIndexLists === false) {
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
- }
- if (empty($orderIndexLists)) {
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail('未查询到需要更新的数据', ErrorCode::$paramError);
- }
- //计算数据的分表
- $updateData = ['salesManId' => $params['salesManId'], 'salesManName' => $params['salesManName'], 'updateTime' => $time];
- $allGroupData = [];
- $allOrderIds = [];
- foreach ($orderIndexLists as $key => $val) {
- $tableNum = ceil($val['userCenterId'] / $this->cutTable);
- $allGroupData[$tableNum][] = $val['id'];
- $allOrderIds[] = $val['id'];
- }
- //更新订单索引表
- $updateOrderIndex = $this->objDOrderIndex->update(['salesManId' => $params['salesManId'], 'updateTime' => $time], ['id' => $allOrderIds]);
- if ($updateOrderIndex === false) {
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
- }
- //在对应分表中更新数据
- foreach ($allGroupData as $k => $orderIds) {
- $this->objDOrder->setTable('qianniao_order_' . $this->onlineEnterpriseId . '_' . $k);
- $updateOrder = $this->objDOrder->update($updateData, ['id' => $orderIds]);
- if ($updateOrder === false) {
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- }*/
- /*
- //修改es
- foreach ($allOrderIds as $orderId) {
- $_id = self::createEsDocumentId($orderId);
- $this->objDOrder->esupdateTypeFieldVaule($updateData, $_id);
- }*/
- $beginStatus && $this->objDOrderIndex->commit();
- return ResultWrapper::success('操作成功');
- }
- /**
- * Doc: (des="")
- * User: XMing
- * Date: 2020/9/4
- * Time: 12:21 下午
- * @param string $verifyCode
- * @return ResultWrapper
- * @throws \Exception
- */
- public function getOrderByVerifyCode(string $verifyCode)
- {
- $orderId = $this->objDOrderIndex->get_field('id', ['verifyCode' => $verifyCode]);
- if ($orderId === false) {
- return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
- }
- if (empty($orderId)) {
- return ResultWrapper::fail('核销码已失效或不存在', ErrorCode::$paramError);
- }
- $orderInfoResult = self::getOrderInfoById($orderId);
- if (!$orderInfoResult->isSuccess()) {
- return ResultWrapper::fail($orderInfoResult->getData(), $orderInfoResult->getErrorCode());
- }
- return ResultWrapper::success($orderInfoResult->getData());
- }
- /**
- * Doc: (des="核销订单")
- * User: XMing
- * Date: 2020/9/4
- * Time: 2:34 下午
- * @param int $id
- * @param array $header
- * @return ResultWrapper
- * @throws \Exception
- */
- public function verification(int $id, $header)
- {
- $orderInfo = $this->objDOrderIndex->get(['id' => $id]);
- if ($orderInfo === false) {
- return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
- }
- if (empty($orderInfo)) {
- return ResultWrapper::fail('未获取到指定订单', ErrorCode::$paramError);
- }
- if ($orderInfo['orderStatus'] == StatusCode::$orderStatus['close']) {
- return ResultWrapper::fail('订单已取消', ErrorCode::$paramError);
- }
- if ($orderInfo['orderStatus'] == StatusCode::$orderStatus['finish']) {
- return ResultWrapper::fail('订单已经核销过了', ErrorCode::$paramError);
- }
- if ($orderInfo['auditStatus'] != StatusCode::$auditStatus['auditPass']) {
- return ResultWrapper::fail('订单尚未审核', ErrorCode::$paramError);
- }
- if ($orderInfo['outStatus'] != StatusCode::$standard) {
- return ResultWrapper::fail('订单还没有出库,不能进行核销操作', ErrorCode::$paramError);
- }
- $orderResult = self::updateOrderStatus($id, ['orderStatus' => StatusCode::$standard], $header);
- if (!$orderResult->isSuccess()) {
- return ResultWrapper::fail($orderResult->getData(), $orderResult->getErrorCode());
- }
- return ResultWrapper::success($orderResult->getData());
- }
- /**
- * Doc: (des="")
- * User: XMing
- * Date: 2020/9/8
- * Time: 7:14 下午
- * @param int $id
- * @return ResultWrapper
- */
- public function getExpressInfoByOrderId(int $id)
- {
- $orderIndex = $this->objDOrderIndex->get(['id' => $id]);
- if ($orderIndex === false) {
- return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
- }
- if (empty($orderIndex)) {
- return ResultWrapper::fail('为获取到指定订单', ErrorCode::$paramError);
- }
- if (empty($orderIndex['deliveryNo']) || empty($orderIndex['expressId'])) {
- return ResultWrapper::success([]);
- }
- $objDExpressCode = new DExpressCode();
- $expressCode = $objDExpressCode->get(['id' => $orderIndex['expressId']]);
- if ($expressCode === false) {
- return ResultWrapper::fail($objDExpressCode->error(), ErrorCode::$dberror);
- }
- if (empty($expressCode)) {
- return ResultWrapper::fail('获取物流信息失败', ErrorCode::$paramError);
- }
- $objMBasicSetup = new MBasicSetup($this->onlineEnterpriseId);
- $basicSetupResult = $objMBasicSetup->getBasicField('logistics_form');
- if (!$basicSetupResult->isSuccess()) {
- return ResultWrapper::fail($basicSetupResult->getData(), $basicSetupResult->getErrorCode());
- }
- $basicSetup = $basicSetupResult->getData();
- $basicSetup = isset($basicSetup['logistics_form']) ? $basicSetup['logistics_form'] : [];
- if (!isset($basicSetup['express_type']) || empty($basicSetup['express_type'])) {
- return ResultWrapper::fail('未配置物流接口', ErrorCode::$paramError);
- }
- $map = [];
- $return = [
- 'list' => [],
- 'stateMsg' => '',
- 'nu' => $orderIndex['deliveryNo'],
- 'expressName' => $expressCode['name']
- ];
- switch ($basicSetup['express_type']) {
- case 'express_hundred':
- $fix = ceil($orderIndex['userCenterId'] / $this->cutTable);
- $this->objDOrderReceive->setTable('qianniao_order_receive_' . $this->onlineEnterpriseId . '_' . $fix);
- $mobile = $this->objDOrderReceive->get_field('mobile', ['orderId' => $orderIndex['id']]);
- if ($mobile === false) {
- return ResultWrapper::fail($this->objDOrderReceive->error(), ErrorCode::$dberror);
- }
- if (!isset($basicSetup['express_hundred'])) {
- return ResultWrapper::fail('快递100未进行配置', ErrorCode::$paramError);
- }
- $express_hundred = $basicSetup['express_hundred'];
- if (!isset($express_hundred['customerCode']) || empty($express_hundred['customerCode']) ||
- !isset($express_hundred['accessKey']) || empty($express_hundred['accessKey'])) {
- return ResultWrapper::fail('快递100配置有误', ErrorCode::$paramError);
- }
- /*$kuaidi100Config = Factory::config()->get('kuaidi100');
- if(empty($kuaidi100Config) || !isset($kuaidi100Config['customer']) || !isset($kuaidi100Config['key']) ){
- return ResultWrapper::fail('快递100配置有误',ErrorCode::$paramError);
- }*/
- //$objQuery = new Query($kuaidi100Config['customer'], $kuaidi100Config['key']);
- /*$kuaidiData = [
- 'com' => 'yunda',
- 'num' => '3103922659603',
- 'phone' => 17600105150,
- ];*/
- $objQuery = new Query($express_hundred['customerCode'], $express_hundred['accessKey']);
- $kuaidiData = [
- 'com' => $expressCode['kuaidi100'],
- 'num' => $orderIndex['deliveryNo'],
- 'phone' => $mobile,
- ];
- $result = $objQuery->pollQuery($kuaidiData);
- if (!$result->isSuccess()) {
- return ResultWrapper::fail('获取物流信息失败', ErrorCode::$paramError);
- }
- $resultData = $result->getData();
- $list = isset($resultData['data']) ? $resultData['data'] : [];
- $return['stateMsg'] = $objQuery->getState(isset($resultData['state']) ? $resultData['state'] : 0);
- $map = self::formatExpressList($list, 'express_hundred');
- break;
- case 'express_bird':
- if (!isset($basicSetup['express_bird'])) {
- return ResultWrapper::fail('快递鸟未进行配置', ErrorCode::$paramError);
- }
- $express_bird = $basicSetup['express_bird'];
- if (!isset($express_bird['userId']) || empty($express_bird['userId']) ||
- !isset($express_bird['apiKey']) || empty($express_bird['apiKey'])) {
- return ResultWrapper::fail('快递鸟配置有误', ErrorCode::$paramError);
- }
- /*$kdniaoConfig = Factory::config()->get('kdniao');
- if(empty($kdniaoConfig) || !isset($kdniaoConfig['EBusinessID']) || !isset($kdniaoConfig['key']) ){
- return ResultWrapper::fail('快递鸟配置错误', ErrorCode::$configEroor);
- }*/
- //$objQuery = new KDNiaoQuery($kdniaoConfig['EBusinessID'], $kdniaoConfig['key']);
- /*$kuaidiData = [
- 'com' => 'HTKY',
- 'num' => '557021498255630',
- ];*/
- $objQuery = new KDNiaoQuery($express_bird['userId'], $express_bird['apiKey']);
- $kuaidiData = [
- 'com' => $expressCode['kdniao'],
- 'num' => $orderIndex['deliveryNo'],
- ];
- $result = $objQuery->EbusinessOrderHandle($kuaidiData);
- if (!$result->isSuccess()) {
- return ResultWrapper::fail('获取物流信息失败', ErrorCode::$paramError);
- }
- $resultData = $result->getData();
- $list = isset($resultData['Traces']) ? $resultData['Traces'] : [];
- $return['stateMsg'] = $objQuery->getState(isset($resultData['State']) ? $resultData['State'] : 0);
- $map = self::formatExpressList($list, 'express_bird');
- break;
- }
- $return['list'] = $map;
- return ResultWrapper::success($return);
- }
- /**
- * Doc: (des="修改订单的发货信息")
- * User: XMing
- * Date: 2020/9/9
- * Time: 11:12 上午
- * @param string $no
- * @param array $params
- * @param int $orderId
- * @return ResultWrapper
- * @throws \Exception
- */
- public function editOrderExpress(string $no, array $params, int $orderId = 0)
- {
- if (empty($orderId)) {
- $orderIndex = $this->objDOrderIndex->get(['no' => $no]);
- } else {
- $orderIndex = $this->objDOrderIndex->get(['id' => $orderId]);
- }
- if ($orderIndex === false) {
- return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
- }
- if (empty($orderIndex)) {
- return ResultWrapper::fail('未获取到指定订单信息' . $no, ErrorCode::$paramError);
- }
- $fix = ceil($orderIndex['userCenterId'] / $this->cutTable);
- $this->objDOrder->setTable('qianniao_order_' . $this->onlineEnterpriseId . '_' . $fix);
- $this->objDOrderIndex->beginTransaction();
- if (isset($params['deliveryType']) && $params['deliveryType'] == StatusCode::$deliveryType['logistics']){
- $update = [
- 'logisticsData' => json_encode($params['logisticsData']),
- 'updateTime' => time(),
- ];
- }else{
- $update = [
- 'deliveryNo' => isset($params['deliveryNo']) ? $params['deliveryNo'] : '',
- 'expressName' => isset($params['expressName']) ? $params['expressName'] : '',
- 'expressId' => isset($params['expressId']) ? $params['expressId'] : 0,
- 'updateTime' => time(),
- ];
- $updateIndex = $this->objDOrderIndex->update($update, ['id' => $orderIndex['id']]);
- if ($updateIndex === false) {
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
- }
- }
- $updateOrder = $this->objDOrder->update($update, ['id' => $orderIndex['id']]);
- if ($updateOrder === false) {
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- //记录司机id
- $driverId = isset($params['logisticsData']['id']) ? $params['logisticsData']['id'] : '';
- $updatedriverId = $this->objDOrder->update(['driverId'=>$driverId],['id' => $orderIndex['id']]);
- if ($updatedriverId === false) {
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- /*
- $_id = self::createEsDocumentId($orderIndex['id']);
- $this->objDOrder->esupdateTypeFieldVaule($update, $_id);*/
- $this->objDOrderIndex->commit();
- return ResultWrapper::success(true);
- }
- /**
- * Doc: (des="")
- * User: XMing
- * Date: 2020/9/8
- * Time: 8:47 下午
- * @param array $list
- * @param string $type
- * @return array
- */
- private function formatExpressList(array $list, string $type)
- {
- $map = [];
- switch ($type) {
- case 'express_hundred':
- foreach ($list as $value) {
- $map[] = [
- 'context' => $value['context'],
- 'time' => $value['time']
- ];
- }
- break;
- case 'express_bird':
- foreach ($list as $value) {
- $map[] = [
- 'context' => $value['AcceptStation'],
- 'time' => $value['AcceptTime']
- ];
- }
- $map = array_reverse($map);
- break;
- }
- return $map;
- }
- /**
- * Doc: (des="")
- * User: XMing
- * Date: 2020/10/12
- * Time: 5:31 下午
- * @param array $params
- * @return ResultWrapper
- * @throws \Exception
- */
- public function create(array $params)
- {
- $objMUserCoupon = new MUserCoupon($this->onlineUserId, $this->onlineEnterpriseId);
- $objMCustomer = new MCustomer($this->onlineEnterpriseId, $this->onlineUserId);
- $objMCustomerBalance = new MCustomerBalance($this->onlineEnterpriseId, $this->onlineUserId);
- $objMCart = new MCart($this->onlineUserId, $this->onlineEnterpriseId);
- $objMOrderGoods = new MOrderGoods($this->onlineUserId, $this->onlineEnterpriseId);
- $objDStaff = new DStaff();
- $objStockCache = new Stock($this->onlineEnterpriseId);
- $objDStaff->setTable('qianniao_staff_' . $this->onlineEnterpriseId);
- $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId);
- $goodsCommonData = $params['goodsData'];
- //锁定库存 查询商铺对应的仓库
- $objMShop = new MShop($this->onlineEnterpriseId, $this->onlineUserId);
- $modelResult = $objMShop->getShopDataByShopIds(array_column($goodsCommonData['goodsData'], 'shopId'));
- if (!$modelResult->isSuccess()) {
- return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
- }
- $shopData = $modelResult->getData();
- if (empty($shopData)) {
- return ResultWrapper::fail('获取店铺数据失败', ErrorCode::$paramError);
- }
- $paramsResult = self::getIdsCashierMap($params);
- if (!$paramsResult->isSuccess()) {
- return ResultWrapper::fail($paramsResult->getData(), $paramsResult->getErrorCode());
- }
- $params = $paramsResult->getData();
- //获取客户信息
- $customerOwe = 0;
- if ($this->onlineUserId == StatusCode::$noneUserCenter) {
- $customerData = [
- 'id' => StatusCode::$noneCustomer,
- 'name' => '匿名客户'
- ];
- } else {
- $customerDataResult = $objMCustomer->getCustomerInfoByUserCenterId($this->onlineUserId);
- if (!$customerDataResult->isSuccess()) {
- return ResultWrapper::fail($customerDataResult->getData(), $customerDataResult->getErrorCode());
- }
- $customerData = $customerDataResult->getData();
- //获取客户当前欠款
- if (isset($customerData['id'])) {
- $customerOwe = $objMCustomerBalance->getCustomerBalance($customerData['id']);
- }
- //获取客户手机号
- $objDUserCenter = new DUserCenter();
- $userInfo = $objDUserCenter->get(['id' => $this->onlineUserId], 'mobile');
- if ($userInfo === false) {
- return ResultWrapper::fail($objDUserCenter->error(), ErrorCode::$dberror);
- }
- $params['customerMobile'] = isset($userInfo['mobile']) ? $userInfo['mobile'] : '';
- }
- // 生成一个临时三方流水号,用来支持多个子订单作为一个订单支付,支付成功之后更新为对应的实际外部支付流水号
- $tmpOuterTradeNo = 'tmp' . createOrderSn($params['source'], StatusCode::$orderType['cashierOrder'], $this->onlineUserId);
- $lockInventoryData = [];//锁定库存物料
- $goodsSaleData = [];//销售数据
- $allSn = [];//所有单号
- $allOrderIds = [];//所有订单
- $mapDetails = [];//订单商品
- $createTime = time();
- $allCartIds = [];
- $shopName = '';
- $shopId = 0;//目前只有一个
- $this->objDOrder->beginTransaction();
- foreach ($goodsCommonData['goodsData'] as $key => $val) {
- $sn = createOrderSn($params['source'], StatusCode::$orderType['saleOrder'], $this->onlineUserId);
- //将数据写入索引表
- $shopId = $val['shopId'];
- $orderIndexData = [
- 'shopId' => $val['shopId'],
- 'userCenterId' => $params['userCenterId'],
- 'salesManId' => isset($customerData['salesManId']) ? $customerData['salesManId'] : 0,
- 'createTime' => time(),
- 'updateTime' => time(),
- 'deleteStatus' => StatusCode::$standard,
- 'auditStatus' => StatusCode::$auditStatus['auditing'],
- 'payStatus' => StatusCode::$delete,
- 'orderStatus' => StatusCode::$orderStatus['waitPay'],
- 'outStatus' => StatusCode::$delete,
- 'returnStatus' => StatusCode::$orderReturn['notReturn'],
- 'deliveryType' => $params['deliveryType'],
- 'payType' => $params['payType'],
- 'customerId' => isset($customerData['id']) ? $customerData['id'] : 0,
- 'no' => $sn,
- 'orderType' => StatusCode::$orderType['cashierOrder'],
- 'selfRuleId' => 0,
- 'cashierUid' => $this->loginUserCenterId,
- 'guideUids' => isset($params['guideUids']) ? $params['guideUids'] : '',
- ];
- //1. 先写索引表
- $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId);
- $orderId = $this->objDOrderIndex->insert($orderIndexData);
- if ($orderId === false) {
- $this->objDOrder->rollBack();
- return ResultWrapper::fail($$this->objDOrderIndex->error(), ErrorCode::$dberror);
- }
- //3。上门自提订单,生成核销码
- $verifyCode = self::createVerifyCode($orderId);
- //兼容以前代码
- $updateRes = $this->objDOrderIndex->update(['verifyCode' => $verifyCode], ['id' => $orderId]);
- if ($updateRes === false) {
- $this->objDOrder->rollBack();
- return ResultWrapper::fail($$this->objDOrderIndex->error(), ErrorCode::$dberror);
- }
- //订单数据
- $shopName = $val['shopName'];//现在就一个店铺
- $masterOrder = [
- 'id' => $orderId,//订单id
- 'customerId' => isset($customerData['id']) ? $customerData['id'] : 0,
- 'userCenterId' => $params['userCenterId'],
- 'shopId' => $val['shopId'],
- 'shopName' => $val['shopName'],
- 'no' => $sn,
- 'outerTradeNo' => $tmpOuterTradeNo,
- 'totalMoney' => $goodsCommonData['totalMoney'],
- 'payAmount' => $goodsCommonData['payMoney'],
- 'customerName' => isset($customerData['name']) ? $customerData['name'] : '',
- 'remark' => $params['remark'],
- 'deliveryType' => $params['deliveryType'],//配送方式
- 'payType' => $params['payType'],//支付方式
- 'salesManId' => isset($customerData['salesManId']) ? $customerData['salesManId'] : 0,
- 'salesManName' => isset($customerData['salesManName']) ? $customerData['salesManName'] : '',
- 'customerType' => isset($customerData['type']) ? $customerData['type'] : 0,
- 'buyTotal' => array_sum(array_column($val['shopGoodsData'], 'buyNum')),
- 'source' => $params['source'],//来源
- 'orderStatus' => StatusCode::$orderStatus['waitPay'],
- 'returnStatus' => StatusCode::$orderReturn['notReturn'],
- 'outStatus' => StatusCode::$delete,
- 'createTime' => time(),
- 'updateTime' => time(),
- 'customerOwe' => $customerOwe,//客户当前欠款
- 'auditStatus' => StatusCode::$auditStatus['auditing'],
- 'preferential' => $goodsCommonData['preferential'],//优惠券优惠金额
- 'vipDiscount' => isset($goodsCommonData['vipDiscount']) ? $goodsCommonData['vipDiscount'] : 0,//会员卡优惠金额
- 'vipDoubleDiscount' => isset($goodsCommonData['vipDoubleDiscount']) ? $goodsCommonData['vipDoubleDiscount'] : 0,//会员卡折上折优惠金额
- 'originPayAmount' => $goodsCommonData['payMoney'],//原支付金额,
- 'orderType' => StatusCode::$orderType['cashierOrder'],
- 'verifyCode' => $verifyCode,
- 'expressMoney' => isset($goodsCommonData['expressMoney']) ? $goodsCommonData['expressMoney'] : 0,
- 'cashierUid' => $this->loginUserCenterId,
- 'guideUids' => isset($params['guideUids']) ? $params['guideUids'] : '',
- 'cashierName' => $params['cashierName'],
- 'guideName' => $params['guideName'],
- 'remMoney' => isset($goodsCommonData['rem_money']) ? $goodsCommonData['rem_money'] : 0,
- 'changeSubMoney' => isset($goodsCommonData['subPrice']) ? $goodsCommonData['subPrice'] : 0,
- 'isNoneUser' => $this->onlineUserId == StatusCode::$noneUserCenter ? StatusCode::$standard : StatusCode::$delete,
- 'customerMobile' => $params['customerMobile'],
- 'serialNum' => $objStockCache->createSerialSn(0,'Order'),
- 'operatorName' => isset($params['operatorName']) ? $params['operatorName'] : '',
- 'operatorId' => isset($params['operatorId']) ? $params['operatorId'] : 0,
- ];
- $allOrderIds[] = $orderId;
- //2。订单表
- $orderId = $this->objDOrder->insert($masterOrder);
- if ($orderId === false) {
- $this->objDOrder->rollBack();
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- $masterOrder['goodsName'] = '';
- foreach ($val['shopGoodsData'] as $k => &$v) {
- $addOrderGoods = [
- 'no' => $sn,
- 'orderId' => $orderId,
- 'goodsId' => $v['goodsId'],
- 'goodsName' => $v['goodsName'],
- 'shopId' => $val['shopId'],//商铺id
- 'shopName' => $val['shopName'],//商铺名称
- 'originPrice' => $v['originPrice'],
- 'price' => $v['price'],
- 'buyNum' => $v['buyNum'],
- 'totalMoney' => $v['totalMoney'],
- 'skuId' => $v['skuId'],
- 'goodsBasicId' => $v['goodsBasicId'],
- 'goodsCode' => $v['goodsCode'],
- 'deliverNum' => $v['buyNum'],//发货数量=购买数量
- 'unitName' => $v['unitName'],//单位名称
- 'conversion' => $v['conversion'],//换算比率
- 'preferential' => $v['preferential'],//优惠券优惠金额
- 'vipDiscount' => $v['vipDiscount'],//会员卡优惠金额
- 'categoryPath' => isset($v['categoryPath']) ? $v['categoryPath'] : '',//分类路径
- 'brandId' => isset($v['brandId']) ? $v['brandId'] : 0,//品牌id
- 'specGroup' => isset($v['specGroup']) && !empty($v['specGroup']) ? json_encode($v['specGroup']) : NULL,
- 'goodsImages' => isset($v['goodsImages']) && is_string($v['goodsImages']) ? $v['goodsImages'] : '',
- 'barCode' => isset($v['barCode']) ? $v['barCode'] : '',
- 'storageCode' => isset($v['storageCode']) ? $v['storageCode'] : '',
- 'categoryName' => isset($v['categoryName']) ? $v['categoryName'] : '',
- 'brandName' => isset($v['brandName']) ? $v['brandName'] : '',
- 'expressMoney' => isset($v['expressMoney']) ? $v['expressMoney'] : 0,
- ];
- $lockInventoryData[] = [
- 'warehouseId' => $shopData[$v['shopId']]['warehouseId'],
- 'materielId' => $v['goodsBasicId'],
- 'materielCode' => $v['goodsCode'],
- 'lockingNum' => $v['buyNum'],
- 'originId' => $orderId,
- 'originNo' => $sn,
- 'source' => StatusCode::$orderType['saleOrder'],
- 'sourceNo' => $sn,
- 'operatorId' => $masterOrder['customerId'],
- 'operatorName' => $masterOrder['customerName'],
- 'skuId' => $v['skuId'],
- ];
- $goodsSaleData [] = [
- 'goodsId' => $addOrderGoods['goodsId'],
- 'skuId' => $addOrderGoods['skuId'],
- 'buyNum' => $addOrderGoods['buyNum'],
- ];
- //活动商品数据
- if ($this->isFront) {
- if (isset($v['activityId']) && $v['activityId'] != 0) {
- $activityData[] = [
- 'goodsId' => $v['goodsId'],
- 'skuId' => $v['skuId'],
- 'activityId' => $v['activityId'],
- 'buyNum' => $v['buyNum']
- ];
- }
- }
- $masterOrder['goodsName'] .= $v['goodsName'] . ' ';
- $result = $objMOrderGoods->addOrderGoods($addOrderGoods);
- if (!$result->isSuccess()) {
- $this->objDOrder->rollBack();
- return ResultWrapper::fail($result->getData(), ErrorCode::$dberror);
- }
- $allCartIds[] = $v['cartId'];
- }
- //存入ES
- $masterOrder['verifyCode'] = isset($verifyCode) ? $verifyCode : '';
- self::updateEsData($orderId, $masterOrder, [], $masterOrder['goodsName']);
- $allSn[] = $sn;//所有订单号
- }
- //将优惠券改为已使用
- if (isset($goodsCommonData['useCoupon']) && !empty($goodsCommonData['useCoupon'])) {
- $result = $objMUserCoupon->updateIsUse(['id' => $goodsCommonData['useCoupon']['id']], ['isUse' => StatusCode::$delete, 'useTime' => time()]);
- if (!$result->isSuccess()) {
- $this->objDOrder->rollBack();
- return ResultWrapper::fail($result->getData(), ErrorCode::$dberror);
- }
- }
- //锁定库存商品数量
- $objMInventory = new MInventory($this->onlineEnterpriseId, $this->onlineUserId);
- $lockInventoryResult = $objMInventory->updateLockInventory($lockInventoryData);
- if (!$lockInventoryResult->isSuccess()) {
- $this->objDOrder->rollBack();
- return ResultWrapper::fail($lockInventoryResult->getData(), $lockInventoryResult->getErrorCode());
- }
- //增加销量
- $objMGoods = new MGoods($this->onlineEnterpriseId, false, $this->onlineUserId);
- if (!empty($goodsSaleData)) {
- foreach ($goodsSaleData as $value) {
- $res = $objMGoods->updateSalesNum($value['goodsId'], $value['skuId'], $value['buyNum']);
- if ($res === false) {
- Logger::logs(E_USER_ERROR, '错误', __CLASS__, __LINE__, '商品增加销量失败');
- }
- }
- }
- //file_put_contents('/www/wwwroot/logs/api.junhailan.com/MSaleOrder_error.log', date('Y-m-d H:i:s') . '数据:' . var_export($mapDetails, true) . PHP_EOL, FILE_APPEND);
- $this->objSaleOrder->setGoodsDetails($mapDetails);
- //统计订单信息
- self::noticeStatistics([
- 'userCenterId' => $params['userCenterId'],
- 'enterpriseId' => $this->onlineEnterpriseId,
- 'customerId' => $params['customerId'],
- 'no' => $allSn,
- 'noticeType' => 'create',
- ], 'MOrderStatistics');
- //写日志
- foreach ($allSn as $sn) {
- parent::saveLog([
- 'no' => $sn,
- 'actionType' => '创建订单',//创建订单
- 'operationData' => '',
- 'userCenterId' => $params['userCenterId'],
- 'enterpriseId' => $this->onlineEnterpriseId,
- 'createTime' => time(),
- ]);
- }
- $this->objDOrder->commit();
- return ResultWrapper::success(['orderId' => $orderId, 'shopName' => $shopName, 'out_trade_no' => $tmpOuterTradeNo, 'total_fee' => $goodsCommonData['payMoney']]);
- }
- /**
- * Doc: (des="订单确认收款")
- * User: XMing
- * Date: 2020/10/12
- * Time: 4:11 下午
- * @param array $params
- * @return ResultWrapper
- * @throws \Exception
- */
- public function confirm(array $params)
- {
- $orderIndex = $this->objDOrderIndex->get(['id' => $params['orderId']]);
- if ($orderIndex === false) {
- return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
- }
- if (empty($orderIndex)) {
- return ResultWrapper::fail('获取订单信息失败', ErrorCode::$paramError);
- }
- if ($orderIndex['payStatus'] != StatusCode::$delete) {
- return ResultWrapper::fail('订单已付款', ErrorCode::$paramError);
- }
- $fix = $fix = ceil($orderIndex['userCenterId'] / $this->cutTable);;
- $this->objDOrder->setTable('qianniao_order_' . $this->onlineEnterpriseId . '_' . $fix);
- $orderData = $this->objDOrder->get(['id' => $params['orderId']]);
- if ($orderData === false) {
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- if (empty($orderData)) {
- return ResultWrapper::fail('获取订单信息失败', ErrorCode::$paramError);
- }
- $paramsResult = self::getIdsCashierMap($params);
- if (!$paramsResult->isSuccess()) {
- return ResultWrapper::fail($paramsResult->getData(), $paramsResult->getErrorCode());
- }
- $params = $paramsResult->getData();
- $this->objDOrderIndex->beginTransaction();
- //修稿订单信息
- $update = [
- 'payType' => $params['payType'],
- 'updateTime' => time(),
- 'cashierUid' => $this->loginUserCenterId,
- 'guideUids' => $params['guideUids'],
- ];
- $updateIndex = $this->objDOrderIndex->update($update, ['id' => $params['orderId']]);
- if ($updateIndex === false) {
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
- }
- $update['guideName'] = $params['guideName'];
- $updateOrder = $this->objDOrder->update($update, ['id' => $params['orderId']]);
- if ($updateOrder === false) {
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
- }
- /*
- //更新es
- $_id = self::createEsDocumentId($params['orderId']);
- $this->objDOrder->esupdateTypeFieldVaule($update, $_id);*/
- //清空此收银员的购物车
- $objMCashierCart = new MCashierCart($this->onlineUserId, $this->onlineEnterpriseId, $this->loginUserCenterId);
- $result = $objMCashierCart->clearCart();
- if (!$result->isSuccess()) {
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($result->getData(), ErrorCode::$dberror);
- }
- //自动审核订单
- $objMInventoryOut = new MInventoryOut($this->onlineEnterpriseId, $this->onlineUserId);
- $auditResult = self::updateAuditStatus([
- 'id' => $params['orderId'],
- 'audit' => '自动审核',
- 'auditId' => $this->onlineUserId,
- 'auditStatus' => StatusCode::$auditStatus['auditPass']
- ]);
- if (!$auditResult->isSuccess()) {
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($auditResult->getData(), $auditResult->getErrorCode());
- }
- $outId = $auditResult->getData();//出库单id
- //自动出库
- $dbResult = $objMInventoryOut->updateInventoryOutStatus(['id' => $outId, 'auditId' => $this->loginUserCenterId, 'auditName' => '销售自动审核']);
- if (!$dbResult->isSuccess()) {
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($dbResult->getData(), $dbResult->getErrorCode());
- }
- //确认收款
- $dbResult = self::updateOrderPayData(['payStatus' => StatusCode::$standard, 'payTime' => time()], ['id' => [$params['orderId']]]);
- if (!$dbResult->isSuccess()) {
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($dbResult->getData(), $dbResult->getErrorCode());
- }
- //确认收货
- $dbResult = self::updateOrderStatus($params['orderId'], ['orderStatus' => StatusCode::$orderStatus['finish']], []);
- if (!$dbResult->isSuccess()) {
- $this->objDOrder->rollBack();
- return ResultWrapper::fail($dbResult->getData(), $dbResult->getErrorCode());
- }
- $objMCashier = new MCashier($this->onlineUserId, $this->onlineEnterpriseId);
- $cashierResult = $objMCashier->calculatePushMoney($params['orderId']);
- if (!$cashierResult->isSuccess()) {
- Logger::logs(E_USER_ERROR, '订单提成计算失败', __CLASS__, __LINE__, $cashierResult->getData());
- }
- //创建收款单
- $received = [
- 'currentAccountName' => $params['currentAccountName'],
- 'financeType' => '销售收款',
- 'financeTypeId' => 2,
- 'shopId' => $orderData['shopId'],
- 'shopName' => $orderData['shopName'],
- 'receiptTime' => time(),
- 'operatorId' => $this->loginUserCenterId,
- 'accountList' => $params['accountList'],
- 'customerId' => $orderData['customerId'],
- 'customerName' => $orderData['customerName'],
- 'sourceNo' => $orderData['no'],
- 'sourceNoMoney' => $orderData['payAmount'],
- 'createTime' => time(),
- 'auditStatus' => StatusCode::$auditStatus['auditing'],
- 'updateTime' => time(),
- ];
- $objMReceived = new MReceived($this->onlineEnterpriseId, $this->loginUserCenterId);
- $receivedResult = $objMReceived->addReceived($received, true);
- if (!$receivedResult->isSuccess()) {
- $this->objDOrderIndex->rollBack();
- return ResultWrapper::fail($receivedResult->getData(), $receivedResult->getErrorCode());
- }
- $this->objDOrderIndex->commit();
- if ($this->onlineUserId == StatusCode::$noneUserCenter) {
- $objDCashierCustomerPrice = new DCashierCustomerPrice();
- $objDCashierCustomerPrice->setTable('qianniao_cashier_customer_price_' . $this->onlineEnterpriseId);
- $objDCashierCustomerPrice->delete(['cashierUid' => $this->loginUserCenterId, 'customerUid' => StatusCode::$noneUserCenter]);
- }
- return ResultWrapper::success(true);
- }
- /**
- * Doc: (des="获取收银员工信息")
- * User: XMing
- * Date: 2020/10/12
- * Time: 5:50 下午
- * @param array $params
- * @return ResultWrapper
- * @throws \Exception
- */
- private function getIdsCashierMap(array $params)
- {
- $objDStaff = new DStaff();
- $objDStaff->setTable('qianniao_staff_' . $this->onlineEnterpriseId);
- //获取收银员信息
- $allUids = [$this->loginUserCenterId];
- if (isset($params['guideUids']) && !empty($params['guideUids'])) {
- $ids = explode(',', $params['guideUids']);
- $allUids = array_merge($allUids, $ids);
- }
- $userMap = [];
- if (!empty($allUids)) {
- $staffList = $objDStaff->select(['userCenterId' => $allUids], 'userCenterId,staffName');
- if ($staffList === false) {
- return ResultWrapper::fail($objDStaff->error(), ErrorCode::$dberror);
- }
- foreach ($staffList as $value) {
- $userMap[$value['userCenterId']] = $value['staffName'];
- }
- }
- $params['cashierName'] = isset($userMap[$this->loginUserCenterId]) ? $userMap[$this->loginUserCenterId] : '超级管理员';
- $nameStr = '';
- if (!empty($ids)) {
- foreach ($ids as $uid) {
- if (!empty($nameStr)) {
- $nameStr .= ',';
- }
- $nameStr .= isset($userMap[$uid]) ? $userMap[$uid] : '';
- }
- }
- $params['guideName'] = $nameStr;
- $params['customerMobile'] = '';
- return ResultWrapper::success($params);
- }
- public function fix_ex()
- {
- $_id = self::createEsDocumentId(144);
- $this->objDOrder->esupdateTypeFieldVaule(['salesManId' => 1, 'salesManName' => '杨明霞', 'updateTime' => time()], $_id);
- }
- /**
- * 查询索引表信息
- */
- public function getOrderIndexData($where)
- {
- $dbResult = $this->objDOrderIndex->get($where);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
- }
- return ResultWrapper::success($dbResult);
- }
- /**
- * Doc: (des="根据订单id获取订单信息")
- * User: XMing
- * Date: 2020/12/7
- * Time: 4:05 下午
- * @param int $id
- * @return ResultWrapper
- * @throws \Exception
- */
- public function getOrderByOrderId(int $id): ResultWrapper
- {
- $orderIndex = $this->objDOrderIndex->get($id);
- if ($orderIndex === false){
- return ResultWrapper::fail($this->objDOrderIndex->error,ErrorCode::$dberror);
- }
- if (empty($orderIndex)){
- return ResultWrapper::fail('未获取到订单信息',ErrorCode::$paramError);
- }
- $fix = ceil($orderIndex['userCenterId'] / $this->cutTable);
- $this->objDOrder->setTable('qianniao_order_'.$this->onlineEnterpriseId.'_'.$fix);
- $order = $this->objDOrder->get($id);
- if ($order === false){
- return ResultWrapper::fail($this->objDOrder->error,ErrorCode::$paramError);
- }
- if (empty($order)){
- return ResultWrapper::fail('未获取到订单信息',ErrorCode::$paramError);
- }
- return ResultWrapper::success($order);
- }
- /**
- * Doc: (des="")
- * User: XMing
- * Date: 2020/12/8
- * Time: 10:43 上午
- * @param int $id
- * @return ResultWrapper
- * @throws \Exception
- */
- public function updateSettel(int $id): ResultWrapper
- {
- $orderIndex = $this->objDOrderIndex->get($id);
- if ($orderIndex === false){
- return ResultWrapper::fail($this->objDOrderIndex->error,ErrorCode::$dberror);
- }
- if (empty($orderIndex)){
- return ResultWrapper::fail('未获取到订单信息',ErrorCode::$paramError);
- }
- $fix = ceil($orderIndex['userCenterId'] / $this->cutTable);
- $this->objDOrder->setTable('qianniao_order_'.$this->onlineEnterpriseId.'_'.$fix);
- $order = $this->objDOrder->update(['isSettel' => StatusCode::$standard],$id);
- if ($order === false){
- return ResultWrapper::fail($this->objDOrder->error,ErrorCode::$paramError);
- }
- return ResultWrapper::success(true);
- }
-
- /**
- * Doc: (des="")
- * User: XMing
- * Date: 2021/2/4
- * Time: 12:06 下午
- * @param array $selectParams
- * @return ResultWrapper
- */
- public function getStatistics(array $selectParams):ResultWrapper
- {
- //默认今日的
- $todayStart = strtotime(date('Y-m-d 00:00:00', time()));
- $todayEnd = strtotime(date('Y-m-d 23:59:59', time()));
- if (isset($selectParams['start']) && !empty($selectParams['start'])){
- $todayStart = $selectParams['start'];
- }
- if (isset($selectParams['end']) && !empty($selectParams['end'])){
- $todayEnd = $selectParams['end'];
- }
- $sql = "SELECT SUM(order_view.returnTotalPrice) as returnTotalPrice,order_view.goodsId,order_view.outCostPrice,SUM(order_view.totalMoney) as totalMoney,order_view.specGroup,order_view.unitName,order_view.skuId,order_view.title,SUM(order_view.num) as rnum,SUM(order_view.o_num) as onum ,SUM(order_view.otherNum) AS otherNum, order_view.goodsBasicId FROM
- (
- SELECT g.goodsId,g.specGroup,g.unitName,g.goodsName as title,g.skuId,@c:=0 as num,@a:=1 as isOrder,g.buyNum as o_num,g.totalMoney,(g.outCostPrice * g.buyNum) as outCostPrice,@d:=0 as returnTotalPrice ,JSON_EXTRACT(g.extends,'$.u_1_buy') AS otherNum,g.goodsBasicId AS goodsBasicId FROM qianniao_order_".$this->onlineEnterpriseId.'_1 as o
- LEFT JOIN qianniao_order_goods_'.$this->onlineEnterpriseId.'_1 as g ON g.orderId = o.id
- WHERE o.outStatus in(5,6) AND g.deleteStatus = 5 AND o.createTime BETWEEN '.$todayStart.' AND '.$todayEnd.'
- UNION ALL
- SELECT d.goodsId,d.skuName as specGroup,d.unitName,d.goodsName as title,d.skuId,d.num as num,@a:=2 as isOrder,@b:=0 as o_num,@c:= 0 as totalMoney,@d:= 0 as outCostPrice,d.returnTotalPrice, @g:= 0 as otherNum ,@g:= 0 as goodsBasicId FROM qianniao_order_return_'.$this->onlineEnterpriseId.' as r
- LEFT JOIN qianniao_order_return_details_'.$this->onlineEnterpriseId.' as d ON d.linkId=r.id
- WHERE r.auditStatus = 2 AND d.deleteStatus = 5 AND r.updateTime BETWEEN '.$todayStart.' AND '. $todayEnd.'
- )
- AS order_view GROUP BY skuId';
- $countSql = 'SELECT order_view.id as id FROM
- (
- SELECT o.id,g.skuId FROM qianniao_order_'.$this->onlineEnterpriseId.'_1 as o
- LEFT JOIN qianniao_order_goods_'.$this->onlineEnterpriseId.'_1 as g ON g.orderId = o.id
- WHERE o.outStatus in(5,6) AND g.deleteStatus = 5 AND o.createTime BETWEEN '.$todayStart.' AND '.$todayEnd.'
- UNION ALL
- SELECT r.id,d.skuId FROM qianniao_order_return_'.$this->onlineEnterpriseId.' as r
- LEFT JOIN qianniao_order_return_details_'.$this->onlineEnterpriseId.' as d ON d.linkId=r.id
- WHERE r.auditStatus = 2 AND d.deleteStatus = 5 AND r.updateTime BETWEEN '.$todayStart.' AND '. $todayEnd.'
- ) AS order_view GROUP BY skuId';
- $sql .= ' LIMIT '.$selectParams['offset'].','.$selectParams['limit'];
- $lists = $this->objDOrderIndex->query($sql);
- if ($lists === false){
- return ResultWrapper::fail($this->objDOrderIndex->error(),ErrorCode::$dberror);
- }
- $goodsBasicDate = [];
- //获取商品资料
- $goodsBasicIds = array_column($lists,'goodsBasicId');
- $objGoodsDate = new MGoodsBasic($this->onlineUserId,$this->onlineEnterpriseId);
- $result = $objGoodsDate->getBasicGoodsFieldByIds($goodsBasicIds);
- if ( !$result->isSuccess() ){
- return ResultWrapper::fail($result->getData(),$result->getErrorCode());
- }
- $goodsBasicDate = $result->getData();
- $skuIds = [];
- foreach ($lists as &$list){
- $list['isEq'] = isset($goodsBasicDate[$list['goodsBasicId']]['isEq']) ? $goodsBasicDate[$list['goodsBasicId']]['isEq'] : 4;
- $list['specGroup'] = json_decode($list['specGroup'],true);
- if (is_array($list['specGroup'])){
- $arr = array_column($list['specGroup'],'specValueName');
- $str = implode('_',$arr);
- $list['specGroup'] = $str;
- }
- $list['subProMoney'] = floatval(bcsub($list['totalMoney'],$list['outCostPrice'],2));//毛利
- $skuIds[] = $list['skuId'];
- }
- unset($list);
- $thisRetMap = [];//本期
- $lastRetMap = [];//上期
- if (!empty($skuIds)){
- $str = implode(',',$skuIds);
- //本期退货数量
- $fields = ' SUM(d.num) as thisRetNum,d.skuId as skuId,SUM(d.returnTotalPrice) as thisReturnTotalPrice ';
- $sql = 'SELECT '.$fields.' FROM qianniao_order_' . $this->onlineEnterpriseId . '_1 AS o
- LEFT JOIN qianniao_order_return_'.$this->onlineEnterpriseId.' AS r
- ON r.originId = o.id LEFT JOIN qianniao_order_return_details_'.$this->onlineEnterpriseId.' AS d
- ON d.linkId = r.id
- WHERE r.auditStatus = 2 AND d.deleteStatus = 5 AND
- o.createTime BETWEEN '.$todayStart.' AND '. $todayEnd.' AND
- r.updateTime BETWEEN '.$todayStart.' AND '. $todayEnd.' AND
- d.skuId IN('.$str.') GROUP BY d.skuId';
- $retLists = $this->objDOrderIndex->query($sql);
- if ($retLists === false){
- return ResultWrapper::fail($this->objDOrderIndex->error(),ErrorCode::$dberror);
- }
- unset($sql);
- //上期退货
- $fields = ' SUM(d.num) as lastRetNum,d.skuId as skuId,SUM(d.returnTotalPrice) as lastReturnTotalPrice ';
- $sql = 'SELECT '.$fields.' FROM qianniao_order_' . $this->onlineEnterpriseId . '_1 AS o
- LEFT JOIN qianniao_order_return_'.$this->onlineEnterpriseId.' AS r
- ON r.originId = o.id LEFT JOIN qianniao_order_return_details_'.$this->onlineEnterpriseId.' AS d
- ON d.linkId = r.id
- WHERE r.auditStatus = 2 AND d.deleteStatus = 5 AND
- o.createTime < '.$todayStart.' AND
- r.updateTime BETWEEN '.$todayStart.' AND '. $todayEnd.' AND
- d.skuId IN('.$str.') GROUP BY d.skuId';
- $lastRetLists = $this->objDOrderIndex->query($sql);
- if ($lastRetLists === false){
- return ResultWrapper::fail($this->objDOrderIndex->error(),ErrorCode::$dberror);
- }
- unset($sql);
- foreach ($retLists as $val){
- $thisRetMap[$val['skuId']] = [
- 'thisRetNum' => $val['thisRetNum'],
- 'thisReturnTotalPrice' => $val['thisReturnTotalPrice'],
- ];
- }
- foreach ($lastRetLists as $val){
- $lastRetMap[$val['skuId']] = [
- 'lastRetNum' => $val['lastRetNum'],
- 'lastReturnTotalPrice' => $val['lastReturnTotalPrice']
- ];
- }
- }
- foreach ($lists as &$item){
- if (!isset($thisRetMap[$item['skuId']])){
- $item['thisRetNum'] = 0;
- $item['thisReturnTotalPrice'] = 0;
- }else{
- $item['thisRetNum'] = floatval($thisRetMap[$item['skuId']]['thisRetNum']);
- $item['thisReturnTotalPrice'] = floatval($thisRetMap[$item['skuId']]['thisReturnTotalPrice']);
- }
- if (!isset($lastRetMap[$item['skuId']])){
- $item['lastRetNum'] = 0;
- $item['lastReturnTotalPrice'] = 0;
- }else{
- $item['lastRetNum'] = floatval($lastRetMap[$item['skuId']]['lastRetNum']);
- $item['lastReturnTotalPrice'] = floatval($lastRetMap[$item['skuId']]['lastReturnTotalPrice']);
- }
- $item['retNum'] = bcadd($item['thisRetNum'],$item['lastRetNum'],2);
- $item['returnTotalPrice'] = bcadd($item['thisReturnTotalPrice'],$item['lastReturnTotalPrice'],2);
- }
- unset($item);
- $count = $this->objDOrderIndex->query($countSql);
- if ($count === false){
- return ResultWrapper::fail($this->objDOrderIndex->error(),ErrorCode::$dberror);
- }
- $data = [
- 'total' => count($count),
- 'data' => $lists
- ];
- return ResultWrapper::success($data);
- }
- /**
- * Doc: (des="")
- * User: XMing
- * Date: 2021/3/10
- * Time: 11:05 上午
- * @param array $params
- * @return ResultWrapper
- * @throws \Exception
- */
- public function getGoodsListsByUserCenterId(array $params): ResultWrapper
- {
- $fix = 1;
- if (isset($params['userCenterId']) && !empty($params['userCenterId'])){
- $fix = ceil($params['userCenterId'] / $this->cutTable);
- }
- $this->objDOrder->setTable('qianniao_order_'.$this->onlineEnterpriseId.'_'.$fix);
- $fields = ' id,customerName,customerId ';
- $where = '';
- if (isset($params['startTime']) && !empty($params['startTime']) && isset($params['endTime']) && !empty($params['endTime'])){
- $where .= ' AND `createTime` BETWEEN '.$params['startTime'].' AND '.$params['endTime'];
- }
- $sql = 'SELECT '.$fields.' FROM qianniao_order_'.$this->onlineEnterpriseId.'_'.$fix.' WHERE deleteStatus = '.StatusCode::$standard.$where;
- if (isset($params['userCenterId']) && !empty($params['userCenterId'])){
- $sql .= ' AND userCenterId = '.$params['userCenterId'];
- }
- $sql .= ' order by createTime desc';
- $lists = $this->objDOrder->query($sql);
- if ($lists === false){
- return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror);
- }
- if (empty($lists)){
- return ResultWrapper::success(['data' => [],'total' => 0]);
- }
- unset($sql);
- unset($where);
- unset($fields);
- $orderIds = [];
- $orderRelMap = [];
- foreach ($lists as $item){
- $orderIds[] = $item['id'];
- $orderRelMap[$item['id']] = $item;
- }
- $fields = ' goodsBasicId,createTime,orderId,goodsName,goodsCode,goodsImages,unitName,specGroup,shopId,shopName,price,SUM(buyNum) AS buyNum,(price * SUM(buyNum)) AS totalMoney,categoryName,brandName,barCode,outNum ,SUM(JSON_EXTRACT(extends,"$.u_1_buy")) AS otherNum ';
- $where = '';
- if (!empty($orderIds)){
- $str = trim(implode(',',$orderIds),',');
- $where .= ' AND `orderId` IN ('.$str.')';
- }
- if (isset($params['categoryId']) && !empty($params['categoryId'])){
- $categoryId = (int)$params['categoryId'];
- $where .= ' AND FIND_IN_SET('.$categoryId.',`categoryPath`) ';
- }
- if (isset($params['brandId']) && !empty($params['brandId'])){
- $brandId = (int)$params['brandId'];
- $where .= ' AND `brandId` = '.$brandId;
- }
- if (isset($params['barCode']) && !empty($params['barCode'])){
- $barCode = (string)$params['barCode'];
- $where .= ' AND `barCode` = "'.$barCode.'"';
- }
- if (isset($params['shopId']) && !empty($params['shopId'])){
- $shopId = (int)$params['shopId'];
- $where .= ' AND `shopId` = '.$shopId;
- }
- if (isset($params['keyword']) && !empty($params['keyword'])){
- $keyword = '"%'.$params['keyword'].'%"';
- $where .= ' AND (`goodsName` LIKE '.$keyword.' OR `goodsCode` LIKE '.$keyword.') ';
- }
- $sql = 'SELECT '.$fields.' FROM qianniao_order_goods_'.$this->onlineEnterpriseId.'_'.$fix.'
- WHERE `deleteStatus` = '.StatusCode::$standard.$where.'
- GROUP BY skuId ORDER BY createTime DESC ';
- $count = $this->objDOrderGoods->query($sql);
- if ($count === false){
- return ResultWrapper::fail($this->objDOrderGoods->error(),ErrorCode::$dberror);
- }
- if (isset($params['limit']) && !empty($params['limit'])){
- $sql .= ' LIMIT '.$params['offset'].','.$params['limit'];
- }
- $lists = $this->objDOrderGoods->query($sql);
- if ($lists === false){
- return ResultWrapper::fail($this->objDOrderGoods->error(),ErrorCode::$dberror);
- }
- if (empty($lists)){
- return ResultWrapper::success(['data'=>[],'total'=>0]);
- }
- if ($lists === false){
- return ResultWrapper::fail($this->objDOrderGoods->error(),ErrorCode::$dberror);
- }
- $goodsBasicDate = [];
- //获取商品资料
- $goodsBasicIds = array_column($lists,'goodsBasicId');
- $objGoodsDate = new MGoodsBasic($this->onlineUserId,$this->onlineEnterpriseId);
- $result = $objGoodsDate->getBasicGoodsFieldByIds($goodsBasicIds);
- if ( !$result->isSuccess() ){
- return ResultWrapper::fail($result->getData(),$result->getErrorCode());
- }
- $goodsBasicDate = $result->getData();
- foreach ($lists as &$item){
- if (isset($item['specGroup']) && !empty($item['specGroup'])){
- $item['specGroup'] = json_decode($item['specGroup'],true);
- }
- $item['customerName'] = isset($orderRelMap[$item['orderId']]) ? $orderRelMap[$item['orderId']]['customerName'] : '';
- $item['customerId'] = isset($orderRelMap[$item['orderId']]) ? $orderRelMap[$item['orderId']]['customerId'] : 0;
- $item['isEq'] = isset($goodsBasicDate[$item['goodsBasicId']]['isEq']) ? $goodsBasicDate[$item['goodsBasicId']]['isEq'] : 4;
- }
- return ResultWrapper::success([
- 'data' => $lists,
- 'total' => (int)count($count)
- ]);
- }
- /**
- * Doc: (des="缺货单列表")
- * User: XMing
- * Date: 2021/3/11
- * Time: 6:44 下午
- * @param array $selectParams
- * @return ResultWrapper
- * @throws \Exception
- */
- public function getDistributionAll(array $selectParams): ResultWrapper
- {
- //{"page":1,"pageSize":10,"search":{},"state":"all"}
- $selectParams['state'] = 'state';
- $selectParams['outStatus'] = 6;
- $orderListsResult = self::getAllOrder($selectParams,[]);
- if (!$orderListsResult->isSuccess()){
- return ResultWrapper::fail($orderListsResult->getData(),$orderListsResult->getErrorCode());
- }
- $total = $orderListsResult->getData()['total'];
- $orderLists = $orderListsResult->getData()['data'];
- if (empty($orderLists)){
- return ResultWrapper::success(['data' => [],'total' => 0]);
- }
- $arrayLists = [];
- $orderIds = [];
- foreach ($orderLists as $item){
- $infoResult = self::getOrderInfoById($item['id']);
- if (!$infoResult->isSuccess()){
- return ResultWrapper::fail($infoResult->getData(),$infoResult->getErrorCode());
- }
- $infoResult = $infoResult->getData();
- $goodsData = $infoResult['goodsData'];
- foreach ($goodsData as $key => $item){
- if ($item['outOfNum'] == 0){
- unset($goodsData[$key]);
- continue;
- }
- $infoResult['goodsData'] = array_values($goodsData);
- }
- $arrayLists[] = $infoResult;
- }
- return ResultWrapper::success(['data' => $arrayLists,'total' => $total]);
- }
- /**
- * Doc: (des="业务员销售排行")
- * User: XMing
- * Date: 2021/3/15
- * Time: 10:09 上午
- * @param array $params
- * @param $export
- * @return ResultWrapper
- */
- public function salesManRank(array $params,$export = 0): ResultWrapper
- {
- $sortFields = ['dealCustomerNum','orderNum','dealAmount','skuNum','buyNum'];
- $sort = ['ASC','DESC'];
- if (!in_array($params['sortField'],$sortFields)){
- return ResultWrapper::fail('sortField字段异常',ErrorCode::$paramError);
- }
- if (!in_array($params['sort'],$sort)){
- return ResultWrapper::fail('sort字段异常',ErrorCode::$paramError);
- }
- $where = '';
- $fields = ' o.salesManName,o.salesManId,COUNT(DISTINCT o.id) as orderNum,COUNT(DISTINCT o.customerId) as dealCustomerNum,SUM(DISTINCT o.payAmount) as dealAmount,COUNT(DISTINCT g.skuId) as skuNum,SUM(g.buyNum) as buyNum ';
- if (isset($params['startTime']) && !empty($params['startTime']) && isset($params['endTime']) && !empty($params['endTime'])){
- $where .= ' AND o.createTime BETWEEN '.$params['startTime'].' AND '.$params['endTime'];
- }
- if ( !empty($params['orderStatus'])&& isset($params['orderStatus']) ){//删选
- $orderStatus = implode(',',$params['orderStatus']);
- $where .= ' AND o.orderStatus IN ('.$orderStatus.')';
- }
- $sql = 'SELECT '.$fields.' FROM qianniao_order_'.$this->onlineEnterpriseId.'_1 as o
- LEFT JOIN qianniao_order_goods_'.$this->onlineEnterpriseId.'_1 as g ON g.orderId = o.id
- WHERE o.deleteStatus = 5
- AND o.salesManId IS NOT NULL
- AND o.salesManId != 0 '.$where;
- $sql .= ' GROUP BY o.salesManName ';
- if (isset($params['sortField']) && !empty($params['sortField']) && isset($params['sort']) && !empty($params['sort'])){
- $sql .= ' ORDER BY '.$params['sortField'].' '.$params['sort'];
- }
- $count = $this->objDOrder->query($sql);
- if ($count === false){
- return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror);
- }
- if (count((array)$count) == 0){
- return ResultWrapper::success(['data' => [],'total' => 0]);
- }
- if($export){
- $params['limit'] = null;
- $params['offset'] = null;
- }
- if (isset($params['limit']) && !empty($params['limit'])){
- $sql .= ' LIMIT '.$params['offset'].','.$params['limit'];
- }
- //导出
- if($export){
- $lists = $this->objDOrder->query($sql);
- if ($lists === false){
- return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror);
- }
- self::exportsalesManRank($lists);
- exit;
- }else{
- $lists = $this->objDOrder->query($sql);
- if ($lists === false){
- return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror);
- }
- foreach ($lists as &$list){
- $list['dealAmount'] = sprintf('%.2f', $list['dealAmount']);
- }
- }
- return ResultWrapper::success(['data' => $lists,'total' => count($count)]);
- }
- /**
- * Doc: (des="")
- * User: XMing
- * Date: 2021/3/17
- * Time: 10:47 上午
- * @param array $orderIds
- * @param array $params
- * @return ResultWrapper
- * @throws \Exception
- */
- public function updateCostPriceBySku(array $orderIds,array $params): ResultWrapper
- {
- Logger::logs(E_USER_ERROR,'params',__CLASS__,__LINE__,$params);
- Logger::logs(E_USER_ERROR,'orderIds',__CLASS__,__LINE__,$orderIds);
- if (empty($orderIds)){
- return ResultWrapper::success();
- }
- $lists = $this->objDOrderIndex->select($orderIds,'id,userCenterId');
- if ($lists === false){
- return ResultWrapper::fail($this->objDOrderIndex->error(),ErrorCode::$dberror);
- }
- $tables = [];
- foreach ($lists as $list){
- $fix = ceil($list['userCenterId'] / $this->cutTable);
- $tables[$fix][] = $list['id'];
- }
- if (empty($tables)){
- return ResultWrapper::success('没有更新的表');
- }
- $status = $this->objDOrderGoods->beginTransaction();
- foreach ($params as $value){
- $where = $value['where'];
- $update = $value['update'];
- foreach ($tables as $fix => $orderIds){
- $this->objDOrderGoods->setTable('qianniao_order_goods_'.$this->onlineEnterpriseId.'_'.$fix);
- Logger::logs(E_USER_ERROR,'update',__CLASS__,__LINE__,$update);
- Logger::logs(E_USER_ERROR,'where',__CLASS__,__LINE__,$where);
- $updateResult = $this->objDOrderGoods->update($update,$where);
- if ($updateResult === false){
- $this->objDOrderGoods->rollBack();
- return ResultWrapper::fail($this->objDOrderGoods->error(),ErrorCode::$dberror);
- }
- }
- }
- $status && $this->objDOrderGoods->commit();
- return ResultWrapper::success(true);
- }
- /*
- * 设置物流信息
- * */
- public function addLogistics($params)
- {
- $logisticsData = $params['logisticsData'];
- if(empty($logisticsData['id'])){
- $objMDriver = new MDriver($this->onlineEnterpriseId, $this->onlineUserId);
- $paramsDriver = [
- 'enterpriseId'=> $this->onlineEnterpriseId,
- 'driverName' => $logisticsData['name'],
- 'phone' => $logisticsData['truckTel'],
- 'plateNumber' => $logisticsData['truckName'],
- 'remark' => $logisticsData['remark']
- ];
- $addDriver = $objMDriver->addDriver($paramsDriver);
- if ( !$addDriver->isSuccess() ){
- return ResultWrapper::fail($addDriver->getData(),$addDriver->getErrorCode());
- }
- $driverId = $addDriver->getData();
- $params['logisticsData']['id']= $driverId;
- }
- //去掉订单id剩下的数据就是物流数据
- $orderId = $params['orderId'];
- unset($params['orderId']);
- $orderNo = $params['no'];
- unset($params['no']);
- $updateLogistics = self::editOrderExpress($orderNo,$params,$orderId);
- if (!$updateLogistics->isSuccess()){
- $this->objDOrder->rollBack();
- return ResultWrapper::fail($updateLogistics->getData(),$updateLogistics->getErrorCode());
- }
- return ResultWrapper::success($updateLogistics);
- }
-
- /**
- * 业务员订单表导出方法
- * @param $result
- * @return void
- * @throws Exception
- */
- public function exportsalesManRank($result)
- {
- //导出到本地
- header("Content-type:application/vnd.ms-excel");
- header("Content-Disposition:filename=业务员订单记录表.csv");
- header('Cache-Control: max-age=0');
-
- $fp = fopen('php://output', 'a');
-
- $head = ['销售员','成交客户','sku数量','订单数','销售数量','成交金额']; //定义标题
-
- foreach ($head as $i => $v) {
- $head[$i] = mb_convert_encoding($v, 'GBK', 'utf-8'); //将中文标题转换编码,否则乱码
- }
-
- fputcsv($fp, $head);
-
- $limit = 10000;
- $num = 0; //计数器
- foreach ($result as $v) { //循环数据
- $num++;
- if ($num == $limit) {
- ob_flush(); //释放内存
- flush();
- }
- $rows['salesManName'] = isset($v['salesManName']) ? $v['salesManName'] : '';//销售员
- $rows['dealCustomerNum'] = isset($v['dealCustomerNum']) ? $v['dealCustomerNum'] : '';//成交客户
- $rows['skuNum'] = isset($v['skuNum']) ? $v['skuNum'] : '';//SKU数量
- $rows['orderNum'] = isset($v['orderNum']) ? $v['orderNum'] : '';//订单数
- $rows['buyNum'] = isset($v['buyNum']) ? $v['buyNum'] : '';//销售数量
- $rows['dealAmount'] = isset($v['dealAmount']) ? $v['dealAmount'] : '';//成交金额
-
- foreach ($rows as $kk => $vv) {
- $rs[$kk] = mb_convert_encoding($vv, 'GBK', 'utf-8'); //转译编码
- }
- fputcsv($fp, $rs);
-
- $rows = [];
- }
- }
-
-
- /**
- * 导出方法
- *
- * @param $orderProfit
- */
- private static function exportOrderProfit($orderProfit)
- {
- //导出到本地
- header("Content-type:application/vnd.ms-excel");
- header("Content-Disposition:filename=销售毛利明细表记录.csv");
- header('Cache-Control: max-age=0');
- $fp = fopen('php://output', 'a');
-
- $head = ['商品名','单据类型', '单据日期', '客户名', '数量','其他单位','销售价', '成本价', '销售收入','销售成本', '销售毛利', '销售毛利率']; //定义标题
-
- foreach ($head as $i => $v) {
- $head[$i] = mb_convert_encoding($v, 'GBK', 'utf-8'); //将中文标题转换编码,否则乱码
- }
- fputcsv($fp, $head);
- $limit = 10000;
- $num = 0;//计数器
- foreach ($orderProfit as $v) {
- //循环数据
- $num++;
- if ($num == $limit) {
- ob_flush();//释放内存
- flush();
- }
- $rows['goodsName'] = isset($v['goodsName']) ? $v['goodsName'] : '';//商品名
- $rows['orderType'] = $v['orderType'] === 1 ? '销售订单' : '销售单';//单据类型
- $rows['createTime'] = isset($v['createTime']) ? date('Y-m-d H:i:s',$v['createTime']) : '';//单据日期
- $rows['customerName'] = isset($v['customerName']) ? $v['customerName'] : '';//客户名
- $rows['buyNum'] = isset($v['buyNum']) ? $v['buyNum'] : '';//数量
- $rows['otherNum'] = isset($v['otherNum']) ? $v['otherNum'] : 0;//其他单位
- $rows['price'] = isset($v['price']) ? $v['price'] : '';//销售价
- $rows['outCostPrice'] = isset($v['outCostPrice']) ? $v['outCostPrice'] : '';//成本价
- $rows['totalMoney'] = isset($v['totalMoney']) ? $v['totalMoney'] : '';//销售收入
- $rows['saleCostAmount'] = isset($v['saleCostAmount']) ? $v['saleCostAmount'] : '';//销售成本
- $rows['saleProfitAmount'] = isset($v['saleProfitAmount']) ? $v['saleProfitAmount'] : '';//销售毛利
- $rows['saleProfitRate'] = isset($v['saleProfitRate']) ? $v['saleProfitRate'].'%' : '';//销售毛利率
- foreach ($rows as $kk => $vv) {
- $rs[$kk] = mb_convert_encoding($vv, 'GBK', 'utf-8'); //转译编码
- }
- fputcsv($fp, $rs);
- $rows = [];
- }
- exit;
- }
- /**
- * 拣货回写订单拣货状态
- */
- public function updateOrderPicking($orderIds,$orderPickStatus)
- {
- $tableName = $this->objDOrder->getTableName('qianniao_order_' . $this->onlineEnterpriseId, $this->onlineUserId, $this->cutTable);
- $this->objDOrder->setTable($tableName);
- if(!empty($orderIds)){
- foreach ($orderIds as $orderId){
- $dbResult = $this->objDOrder->update(['pickingStatus'=>$orderPickStatus],['id'=>$orderId]);
- if ($dbResult === false){
- return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror);
- }
- }
- }
- return ResultWrapper::success([]);
- }
- /**
- *
- *用户订单状态数量统计
- */
- public function getOrderStatusNum()
- {
- // 2待支付 3代发货 4待收货 5已完成 10退货
- $returnData = [
- '2' => 0,
- '3' => 0,
- '4' => 0,
- '5' => 0,
- '10' => 0
- ];
- // 查询订单各状态对应的总条数
- $sql = 'SELECT count(orderStatus) as total,orderStatus FROM qianniao_order_index_'.$this->onlineEnterpriseId.' WHERE deleteStatus = '.StatusCode::$standard.' AND userCenterId = '.$this->onlineUserId.' GROUP BY orderStatus';
- $dbResult = $this->objDOrderIndex->query($sql);
- if($dbResult === false){
- return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
- }
- if (!empty($dbResult)){
- foreach ($dbResult as $key => $value){
- $returnData[$value['orderStatus']] = $value['total'];
- }
- }
- // 查询退货状态总条数
- unset($dbResult);
- $sql = 'SELECT count(id) as total FROM qianniao_order_return_'.$this->onlineEnterpriseId.' WHERE deleteStatus = '.StatusCode::$standard.' AND userCenterId = '.$this->onlineUserId;
- $dbResult = $this->objDOrderIndex->query($sql);
- if($dbResult === false){
- return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
- }
- if (!empty($dbResult)){
- $returnData[10] = $dbResult[0]['total'];
- }
- return ResultWrapper::success($returnData);
- }
- }
|