MOrder.Class.php 361 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923
  1. <?php
  2. /**
  3. * 订单数据模型
  4. * Created by PhpStorm.
  5. * User: XiaoMing
  6. * Date: 2019/10/31
  7. * Time: 15:53
  8. */
  9. namespace JinDouYun\Model\Order;
  10. use JinDouYun\Controller\System\Driver;
  11. use JinDouYun\Model\System\MDriver;
  12. use Mall\Framework\Core\StatusCode;
  13. use Mall\Framework\Core\ErrorCode;
  14. use Mall\Framework\Core\ResultWrapper;
  15. use Mall\Framework\Factory;
  16. use JinDouYun\Cache\ActivityLimitCache;
  17. use JinDouYun\Cache\CustomerCache;
  18. use JinDouYun\Cache\OverviewCache;
  19. use JinDouYun\Cache\SystemCache;
  20. use JinDouYun\Cache\Stock;
  21. use JinDouYun\Cache\EnterpriseCache;
  22. use JinDouYun\Controller\Common\CloudPrint;
  23. use JinDouYun\Controller\Common\Logger;
  24. use JinDouYun\Dao\Order\DOrderReceive;
  25. use JinDouYun\Dao\Order\DOrderIndex;
  26. use JinDouYun\Dao\Order\DOrder;
  27. use JinDouYun\Dao\Order\DOrderGoods;
  28. use JinDouYun\Dao\Order\DOrderStatistics;
  29. use JinDouYun\Dao\Cashier\DCashierCustomerPrice;
  30. use JinDouYun\Dao\Customer\DCustomer;
  31. use JinDouYun\Dao\Department\DStaff;
  32. use JinDouYun\Dao\System\DCustomerSource;
  33. use JinDouYun\Dao\System\DExpressCode;
  34. use JinDouYun\Dao\UserCenter\DUserCenter;
  35. use JinDouYun\Dao\Finance\DReceivedIndex;
  36. use JinDouYun\Model\System\MBasicSetup;
  37. use JinDouYun\Model\Finance\MCustomerBalance;
  38. use JinDouYun\Model\System\MPaymentSetting;
  39. use JinDouYun\Model\Market\MUserCoupon;
  40. use JinDouYun\Model\MBaseModel;
  41. use JinDouYun\Model\Log\MOrderLog;
  42. use JinDouYun\Model\GoodsManage\MSku;
  43. use JinDouYun\Model\Shop\MShop;
  44. use JinDouYun\Model\Customer\MShippingAddress;
  45. use JinDouYun\Model\Cart\MCart;
  46. use JinDouYun\Model\Stock\MInventory;
  47. use JinDouYun\Model\Stock\MInventoryOut;
  48. use JinDouYun\Model\Stock\MWarehouse;
  49. use JinDouYun\Model\Customer\MCustomer;
  50. use JinDouYun\Model\Goods\MGoods;
  51. use JinDouYun\Model\Finance\MAccount;
  52. use JinDouYun\Model\Finance\MReceived;
  53. use JinDouYun\Model\SysAreaChina\MSysAreaChina;
  54. use JinDouYun\Model\Customer\MMemberBalanceDetail;
  55. use JinDouYun\Model\Cashier\MCashier;
  56. use JinDouYun\Model\Cashier\MCashierCart;
  57. use JinDouYun\Model\Department\MStaff;
  58. use JinDouYun\Model\Finance\MMerchantFlow;
  59. use JinDouYun\Model\Finance\MReceive;
  60. use JinDouYun\Model\Finance\MRefund;
  61. use JinDouYun\Model\System\MDeliverySetting;
  62. use JinDouYun\Model\System\MPrintNum;
  63. use JinDouYun\Model\System\MProcessSetting;
  64. use JinDouYun\Model\Order\MPay;
  65. use JinDouYun\Model\GoodsManage\MGoodsBasic;
  66. use JinDouYun\Model\Merchant\MMerchantSettlement;
  67. use JinDouYun\Model\System\MSystemPushMessage;
  68. use Util\KDNiao\KDNiaoQuery;
  69. use Util\KuaiDi100\Query;
  70. use Util\WeiXin\Pay;
  71. use Util\AliPay\Pay as aliPay;
  72. use Util\ByteDance\Pay as bytePay;
  73. //use Util\Common\PartnerTools;
  74. class MOrder extends MBaseModel
  75. {
  76. /**
  77. * @var DOrder
  78. */
  79. private $objDOrder;
  80. /**
  81. * @var int 用户id
  82. */
  83. private $onlineUserId;
  84. /**
  85. * @var int 企业id
  86. */
  87. private $onlineEnterpriseId;
  88. /**
  89. * @var int 单表数据量
  90. */
  91. private $cutTable = 500000;
  92. /**
  93. * @var DOrderIndex
  94. */
  95. private $objDOrderIndex;
  96. /**
  97. * @var DOrderGoods
  98. */
  99. private $objDOrderGoods;
  100. /**
  101. * @var DOrderStatistics
  102. */
  103. private $objDOrderStatistics;
  104. /**
  105. * @var bool
  106. */
  107. private $isFront;//是否是前台调用此Model 前台=>true
  108. /**
  109. * @var OverviewCache
  110. */
  111. private $objOverviewCache;
  112. /**
  113. * @var string
  114. */
  115. private $orderStatisticsTableName = 'order_statistics';
  116. /**
  117. * @var MAccount
  118. */
  119. private $objMAccount;
  120. /**
  121. * @var MReceived
  122. */
  123. private $objMReceived;
  124. /**
  125. * @var ActivityLimitCache
  126. */
  127. private $objActivityLimitCache;
  128. /**
  129. * @var SaleOrder 销售单
  130. */
  131. private $objSaleOrder;
  132. /**
  133. * @var bool 销售单是否打印小票
  134. */
  135. private $isEnablePrint = false;
  136. /**
  137. * @var DOrderReceive
  138. */
  139. private $objDOrderReceive;
  140. /**
  141. * @var DCustomer
  142. */
  143. private $objDCustomer;
  144. /**
  145. * @var int
  146. */
  147. private $loginUserCenterId;
  148. /**
  149. * @var array
  150. */
  151. private $expressMap = [
  152. 'express_hundred' => 'kuaidi100',
  153. 'express_bird' => 'kdniao'
  154. ];
  155. /**
  156. * @var bool
  157. */
  158. private $isCashier;
  159. /**
  160. * @var MProcessSetting
  161. */
  162. private $objMProcessSetting;
  163. use TStdOrder;
  164. /**
  165. * MOrder constructor.
  166. * @param $onlineUserId
  167. * @param $onlineEnterpriseId
  168. * @param null $loginUserCenterId
  169. * @param bool $isFront
  170. * @throws \Exception
  171. */
  172. public function __construct($onlineUserId, $onlineEnterpriseId, $loginUserCenterId = null, $isFront = false, $isCashier = false)
  173. {
  174. $this->isCashier = $isCashier;
  175. $this->isFront = $isFront;
  176. $this->onlineUserId = $onlineUserId;
  177. $this->onlineEnterpriseId = $onlineEnterpriseId;
  178. $this->loginUserCenterId = $loginUserCenterId;
  179. parent::__construct($this->onlineEnterpriseId, $loginUserCenterId);
  180. $this->objDOrder = new DOrder('default');
  181. self::orderSubTable($onlineEnterpriseId, $onlineUserId);
  182. $this->objDOrderIndex = new DOrderIndex();
  183. $this->objDOrderGoods = new DOrderGoods('default');
  184. $this->objDOrderReceive = new DOrderReceive();
  185. $this->objDOrderStatistics = new DOrderStatistics('default');
  186. $this->objMAccount = new MAccount($onlineEnterpriseId, $onlineUserId);
  187. $this->objMReceived = new MReceived($onlineEnterpriseId, $onlineUserId);
  188. $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId);
  189. $this->objDOrderStatistics->setTable($this->objDOrderStatistics->get_Table() . '_' . $this->onlineEnterpriseId);
  190. $this->objDOrder->setSearchIndex('order_search')->setType('order');
  191. $this->objActivityLimitCache = new ActivityLimitCache($this->onlineEnterpriseId);
  192. $this->objOverviewCache = new OverviewCache();
  193. $this->objSaleOrder = new SaleOrder();
  194. $this->objDCustomer = new DCustomer();
  195. $this->objDCustomer->setTable('qianniao_customer_' . $this->onlineEnterpriseId);
  196. $this->objMProcessSetting = new MProcessSetting($this->onlineEnterpriseId);
  197. }
  198. /**
  199. * 订单分表 分表规则:企业id_(客户/200000)
  200. * @param $enterpriseId (企业id)
  201. * @param $userId (用户id)
  202. * @throws \Exception
  203. */
  204. public function orderSubTable($enterpriseId, $userId)
  205. {
  206. $tableName = $this->objDOrder->getTableName('qianniao_order_' . $enterpriseId, $userId, $this->cutTable);
  207. self::existsTable($tableName);
  208. $this->objDOrder->setTable($tableName);
  209. }
  210. /**
  211. * 获取订单表表名
  212. */
  213. public function getOrderTable($enterpriseId, $userId){
  214. return $this->objDOrder->getTableName('qianniao_order_' . $enterpriseId, $userId, $this->cutTable);
  215. }
  216. /**
  217. * 统计订单信息
  218. *
  219. * @param $data
  220. * @param $className
  221. */
  222. private static function noticeStatistics($data, $className)
  223. {
  224. $i = 1;
  225. do {
  226. $postData = [
  227. 'topicName' => 'MyJob',
  228. 'topicClass' => "Jobs\Model\MTopic\Order\\" . $className,
  229. 'topicMethon' => 'push',
  230. 'topicMethonParams' => [
  231. 'userCenterId' => $data['userCenterId'],
  232. 'enterpriseId' => $data['enterpriseId'],
  233. 'customerId' => $data['customerId'],
  234. 'no' => $data['no'],
  235. 'noticeType' => $data['noticeType'],
  236. ],
  237. ];
  238. $url = QIANNIAO_QUEUE . '/CAddJob/add';
  239. $result = request($url, $postData);
  240. $i++;
  241. } while ($result['httpcode'] != 200 && $i <= 3);
  242. }
  243. /**
  244. * 分表后缀+月日+订单id
  245. * @param $orderId
  246. * @return string
  247. */
  248. private function createVerifyCode($orderId)
  249. {
  250. $fix = ceil($this->onlineUserId / $this->cutTable);
  251. return $fix . '-' . date('nj') . '-' . $orderId;
  252. }
  253. /**
  254. * Doc: (des="")
  255. * User: XMing
  256. * Date: 2020/12/25
  257. * Time: 2:11 下午
  258. * @param $data
  259. * @return ResultWrapper
  260. */
  261. public function checkLimit($data)
  262. {
  263. foreach ($data as $goods) {
  264. if (isset($goods['activityId'])) {
  265. //获取活动商品剩余数量
  266. $surplusNum = $this->objActivityLimitCache->getLen($goods['activityId'], $goods['goodsId'], $goods['skuId']);
  267. if ($surplusNum < $goods['buyNum']) {
  268. return ResultWrapper::fail($goods['title'] . '活动剩余数量不足', ErrorCode::$paramError);
  269. }
  270. }
  271. }
  272. return ResultWrapper::success($data);
  273. }
  274. /**
  275. * Doc: (des="订单编辑")
  276. * User: XMing
  277. * Date: 2020/11/5
  278. * Time: 10:07 上午
  279. * @param array $params
  280. * @param $id
  281. * @return ResultWrapper
  282. * @throws \Exception
  283. */
  284. public function edit(array $params, $id): ResultWrapper
  285. {
  286. $orderIndex = $this->objDOrderIndex->get($id);
  287. if ($orderIndex === false) {
  288. return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
  289. }
  290. if (empty($orderIndex)) {
  291. return ResultWrapper::fail('未获取到指定订单', ErrorCode::$paramError);
  292. }
  293. /*if ($orderIndex['payStatus'] == StatusCode::$standard) {
  294. return ResultWrapper::fail('订单已支付,不能编辑', ErrorCode::$paramError);
  295. }
  296. if ($orderIndex['auditStatus'] != StatusCode::$auditStatus['auditing']) {
  297. return ResultWrapper::fail('订单已审核不能编辑', ErrorCode::$paramError);
  298. }*/
  299. if (
  300. in_array($orderIndex['orderStatus'], [StatusCode::$orderStatus['waitReceive'], StatusCode::$orderStatus['finish'], StatusCode::$orderStatus['close']])
  301. ) {
  302. return ResultWrapper::fail('此订单不能编辑', ErrorCode::$paramError);
  303. }
  304. $fix = ceil((empty($params['userCenterId']) ? 1 : $params['userCenterId']) / $this->cutTable);
  305. $this->objDOrderReceive->setTable('qianniao_order_receive_' . $this->onlineEnterpriseId . '_' . $fix);
  306. $this->objDOrderGoods->setTable('qianniao_order_goods_' . $this->onlineEnterpriseId . '_' . $fix);
  307. $objMCustomerBalance = new MCustomerBalance($this->onlineEnterpriseId, $this->onlineUserId);
  308. $objMOrderGoods = new MOrderGoods($this->onlineUserId, $this->onlineEnterpriseId);
  309. $customerResult = self::getCustomerInfoByUserCenterId($params['userCenterId']);
  310. if (!$customerResult->isSuccess()) {
  311. return ResultWrapper::fail($customerResult->getData(), $customerResult->getErrorCode());
  312. }
  313. $customer = $customerResult->getData();
  314. isset($customer['customerType']) && $params['customerType'] = $customer['customerType'];
  315. isset($customer['salesManId']) && $params['salesManId'] = $customer['salesManId'];
  316. isset($customer['salesManName']) && $params['salesManName'] = $customer['salesManName'];
  317. $params['customerOwe'] = $objMCustomerBalance->getCustomerBalance($customer['id']);//获取客户当前欠款
  318. $address = [];
  319. $selfRule = [];
  320. switch ($params['deliveryType']) {
  321. case StatusCode::$deliveryType['goodsDelivery']:
  322. $addressResult = self::getAddressInfo($params['addressId']);
  323. if (!$addressResult->isSuccess()) {
  324. return ResultWrapper::fail($addressResult->getData(), $addressResult->getErrorCode());
  325. }
  326. $address = $addressResult->getData();
  327. break;
  328. case StatusCode::$deliveryType['selfMention']:
  329. $selfRuleResult = self::getSelfRuleData($params['selfRuleId']);
  330. if (!$selfRuleResult->isSuccess()) {
  331. return ResultWrapper::fail($selfRuleResult->getData(), $selfRuleResult->getErrorCode());
  332. }
  333. $selfRule = $selfRuleResult->getData();
  334. break;
  335. }
  336. $status = $this->objDOrder->beginTransaction();
  337. $updateIndexResult = $this->objDOrderIndex->update(
  338. [
  339. 'userCenterId' => isset($params['userCenterId']) ? $params['userCenterId'] : 0,
  340. 'deliveryType' => isset($params['deliveryType']) ? $params['deliveryType'] : 0,
  341. 'customerId' => isset($params['customerId']) ? $params['customerId'] : 0,
  342. 'deliveryNo' => isset($params['deliveryNo']) ? $params['deliveryNo'] : '',
  343. 'expressName' => isset($params['expressName']) ? $params['expressName'] : '',
  344. 'expressId' => isset($params['expressId']) ? $params['expressId'] : 0,
  345. 'selfRuleId' => isset($params['selfRuleId']) ? $params['selfRuleId'] : 0,
  346. 'updateTime' => time(),
  347. ],
  348. $id
  349. );
  350. if ($updateIndexResult === false) {
  351. $this->objDOrder->rollBack();
  352. return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
  353. }
  354. $updateOrder = [
  355. 'customerName' => isset($params['customerName']) ? $params['customerName'] : '',
  356. 'customerId' => isset($params['customerId']) ? $params['customerId'] : 0,
  357. 'deliveryType' => isset($params['deliveryType']) ? $params['deliveryType'] : 0,
  358. 'remark' => isset($params['remark']) ? $params['remark'] : '',
  359. 'salesManId' => isset($params['salesManId']) ? $params['salesManId'] : 0,
  360. 'salesManName' => isset($params['salesManName']) ? $params['salesManName'] : '',
  361. 'customerType' => isset($params['customerType']) ? $params['customerType'] : 0,
  362. 'userCenterId' => isset($params['userCenterId']) ? $params['userCenterId'] : 0,
  363. 'customerOwe' => isset($params['customerOwe']) ? $params['customerOwe'] : 0,
  364. 'preferential' => isset($params['preferential']) ? $params['preferential'] : 0,
  365. 'vipDiscount' => isset($params['vipDiscount']) ? $params['vipDiscount'] : 0,
  366. 'expressMoney' => isset($params['expressMoney']) ? $params['expressMoney'] : 0,
  367. 'expressName' => isset($params['expressName']) ? $params['expressName'] : '',
  368. 'expressId' => isset($params['expressId']) ? $params['expressId'] : 0,
  369. 'deliveryNo' => isset($params['deliveryNo']) ? $params['deliveryNo'] : '',
  370. 'selfRuleId' => isset($params['selfRuleId']) ? $params['selfRuleId'] : 0,
  371. 'originPayAmount' => isset($params['originPayAmount']) ? $params['originPayAmount'] : 0,
  372. 'payAmount' => isset($params['payMoney']) ? $params['payMoney'] : 0,
  373. 'totalMoney' => isset($params['totalMoney']) ? $params['totalMoney'] : 0,
  374. 'receivedMoney' => isset($params['receivedMoney']) ? $params['receivedMoney'] : 0,
  375. "accountList" => isset($params['accountList']) ? json_encode($params['accountList']) : null,
  376. "currentAccountName" => isset($params['currentAccountName']) ? $params['currentAccountName'] : '',
  377. "totalReduceMoney" => isset($params['totalReduceMoney']) ? $params['totalReduceMoney'] : 0,
  378. "selfRuleData" => empty($selfRule) ? null : json_encode($selfRule),
  379. "updateTime" => time(),
  380. ];
  381. $updateOrderResult = $this->objDOrder->update($updateOrder, $id);
  382. if ($updateOrderResult === false) {
  383. $this->objDOrder->rollBack();
  384. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  385. }
  386. if (!empty($address)) {
  387. $updateReceiveResult = $this->objDOrderReceive->update([
  388. 'customerId' => $address['customerId'],
  389. 'customerCode' => $address['customerCode'],
  390. 'realName' => $address['name'],
  391. 'mobile' => $address['mobile'],
  392. 'address' => $address['address'],
  393. 'provinceCode' => $address['provinceCode'],
  394. 'cityCode' => $address['cityCode'],
  395. 'districtCode' => $address['districtCode'],
  396. 'updateTime' => time()
  397. ], ['orderId' => $id]);
  398. if ($updateReceiveResult === false) {
  399. $this->objDOrder->rollBack();
  400. return ResultWrapper::fail($this->objDOrderReceive->error(), ErrorCode::$dberror);
  401. }
  402. }
  403. //编辑商品
  404. if ($orderIndex['payStatus'] != StatusCode::$standard || $orderIndex['auditStatus'] != StatusCode::$auditStatus['auditPass']) {
  405. //解锁库存
  406. $objMInventory = new MInventory($this->onlineEnterpriseId, $this->onlineUserId);
  407. $unlockResult = $objMInventory->unlockInventory([$id], StatusCode::$orderType['saleOrder'], $orderIndex['createTime']);
  408. if (!$unlockResult->isSuccess()) {
  409. $this->objDOrder->rollBack();
  410. Logger::logs(E_USER_ERROR, '编辑订单,库存解锁失败', __CLASS__, __LINE__, $unlockResult->getData());
  411. return ResultWrapper::fail($unlockResult->getData(), ErrorCode::$dberror);
  412. }
  413. $editResult = $objMOrderGoods->edit($params, $id,$orderIndex['no']);
  414. if (!$editResult->isSuccess()) {
  415. $this->objDOrder->rollBack();
  416. return ResultWrapper::fail($editResult->getData(), $editResult->getErrorCode());
  417. }
  418. }
  419. /*
  420. //跟新es
  421. $_id = self::createEsDocumentId($id);
  422. $this->objDOrder->esupdateTypeFieldVaule($updateOrder, $_id);*/
  423. if ($status){
  424. $this->objDOrder->commit();
  425. }
  426. return ResultWrapper::success(true);
  427. }
  428. /**
  429. * Doc: (des="代客下单,销售订单")
  430. * User: XMing
  431. * Date: 2020/12/19
  432. * Time: 2:38 下午
  433. * @param $params
  434. * @return ResultWrapper
  435. * @throws \Exception
  436. */
  437. public function add($params): ResultWrapper
  438. {
  439. $params['orderType'] = getArrayItem($params,'orderType',StatusCode::$orderType['saleOrder']);
  440. $goodsNameStr = self::createGoodsName($params['lists']);
  441. $commonParamsResult = self::formatCommonParams($params); // 格式化订单关联数据
  442. if (!$commonParamsResult->isSuccess()){
  443. return ResultWrapper::fail($commonParamsResult->getData(),$commonParamsResult->getErrorCode());
  444. }
  445. $params = $commonParamsResult->getData();
  446. $lists = $params['lists'];
  447. unset($params['lists']);
  448. $groupShopDataResult = self::buildGoodsByShop($lists,$params);
  449. if (!$groupShopDataResult->isSuccess()){
  450. return ResultWrapper::fail($groupShopDataResult->getData(),$groupShopDataResult->getErrorCode());
  451. }
  452. $shopGoodsData = $groupShopDataResult->getData();
  453. //锁定库存 查询商铺对应的仓库
  454. $objMShop = new MShop($this->onlineEnterpriseId, $this->onlineUserId);
  455. $modelResult = $objMShop->getShopDataByShopIds(array_column($shopGoodsData, 'shopId')); // 根据shopIds获取商铺数据
  456. if (!$modelResult->isSuccess()) {
  457. return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
  458. }
  459. $shopMap = $modelResult->getData();
  460. $buildGroupResult = self::groupSupplierOrderData($shopGoodsData,$params,$shopMap); // 将商品数据按照指定的字段分组
  461. if (!$buildGroupResult->isSuccess()){
  462. return ResultWrapper::fail($buildGroupResult->getData(),$buildGroupResult->getErrorCode());
  463. }
  464. $buildGroup = $buildGroupResult->getData();
  465. $insertOrderResult = self::insertOrder($buildGroup,$params);
  466. if (!$insertOrderResult->isSuccess()){
  467. return ResultWrapper::fail($insertOrderResult->getData(),$insertOrderResult->getErrorCode());
  468. }
  469. $orderIds = $insertOrderResult->getData();
  470. /* 拣货信息 */
  471. /* 功能临时屏蔽
  472. $orderNum = 0;
  473. $notOutNum = 0;
  474. $notPickingNum = 0;
  475. $otherNum = 0;
  476. foreach ($lists as $listKey => $listValue){
  477. $notOutNum = bcadd($notOutNum,$listValue['buyNum'],4);
  478. $notPickingNum = bcadd($notPickingNum,$listValue['buyNum'],4);
  479. $otherNum = bcadd($otherNum,$listValue['otherNum']);
  480. $orderNum = bcadd($orderNum,$listValue['buyNum']);
  481. }
  482. //组装订单拣货信息
  483. $orderPickingDate = [
  484. 'orderId' => $orderIds[0],
  485. 'sort' => 0,
  486. 'outNum' => 0,
  487. 'notOutNum' => $notOutNum,
  488. 'orderNum' => $orderNum,
  489. 'notPickingNum' => $notPickingNum,
  490. 'pickingNum' => 0,
  491. 'outTime' => 0,
  492. 'otherNum' => $otherNum,
  493. 'mangeId' => getArrayItem($params,'operatorId',0),
  494. 'mangeName' => getArrayItem($params,'operatorName',''),
  495. ];
  496. $objOrderPicking = new MOrderPicking($this->onlineUserId,$this->onlineEnterpriseId);
  497. $orderPickingResult = $objOrderPicking->addOrderPick($orderPickingDate); //临时注释
  498. if(!$orderPickingResult->isSuccess()){
  499. return ResultWrapper::fail($orderPickingResult->getData(), $orderPickingResult->getErrorCode());
  500. }*/
  501. parent::sendMessage($this->onlineEnterpriseId,'NewOrder');
  502. $params['orderType'] == StatusCode::$orderType['saleOrder'] && self::runProcessNextAudit($orderIds);
  503. return ResultWrapper::success($orderIds);
  504. }
  505. /**
  506. * Doc: (des="商品名称")
  507. * User: XMing
  508. * Date: 2020/11/18
  509. * Time: 3:27 下午
  510. * @param $goods
  511. * @return string
  512. */
  513. public static function createGoodsName($goods): string
  514. {
  515. $str = '';
  516. foreach ($goods as $val){
  517. if (isset($val['goodsName']) && !empty($val['goodsName'])){
  518. $str .= (string)$val['goodsName'].' ';
  519. }
  520. }
  521. return $str;
  522. }
  523. /**
  524. * Doc: (des="执行订单的下一步操作")
  525. * User: XMing
  526. * Date: 2020/11/6
  527. * Time: 5:03 下午
  528. * @param array $ids 订单ids
  529. * @return ResultWrapper
  530. * @throws \Exception
  531. */
  532. private function runProcessNextAudit(array $ids): ResultWrapper
  533. {
  534. Logger::logs(E_USER_ERROR,'订单自动审核',__CLASS__,__LINE__,$ids);
  535. if (empty($ids)){
  536. return ResultWrapper::success(true);
  537. }
  538. $setResult = $this->objMProcessSetting->getProcessSettingByType(StatusCode::$processType['sales'],'audit');
  539. if (!$setResult->isSuccess()){
  540. Logger::logs(E_USER_ERROR,'获取流程配置出错',__CLASS__,__LINE__,$setResult->getData());
  541. return ResultWrapper::fail($setResult->getData(),$setResult->getErrorCode());
  542. }
  543. $set = $setResult->getData();
  544. if (empty($set)){
  545. Logger::logs(E_USER_ERROR,'配置为空',__CLASS__,__LINE__,'');
  546. return ResultWrapper::success(true);
  547. }
  548. if (isset($set['enableStatus']) && $set['enableStatus'] == StatusCode::$standard){
  549. Logger::logs(E_USER_ERROR,'配置',__CLASS__,__LINE__,$set);
  550. return ResultWrapper::success(true);
  551. }
  552. foreach ($ids as $id){
  553. $params = [
  554. 'id' => $id,
  555. 'audit' => '自动审核',
  556. 'auditId' => $this->onlineUserId,
  557. 'auditStatus' => StatusCode::$auditStatus['auditPass'],
  558. ];
  559. $auditResult = $this->updateAuditStatus($params);
  560. if (!$auditResult->isSuccess()){
  561. Logger::logs(E_USER_ERROR,'自动审核订单出错',__CLASS__,__LINE__,$auditResult->getData());
  562. return ResultWrapper::fail($auditResult->getData(),$auditResult->getErrorCode());
  563. }
  564. }
  565. Logger::logs(E_USER_ERROR,'自动审核订单成功',__CLASS__,__LINE__,$ids);
  566. return ResultWrapper::success(true);
  567. }
  568. /**
  569. * Doc: (des="根据客户id获取客户信息")
  570. * User: XMing
  571. * Date: 2020/11/3
  572. * Time: 2:11 下午
  573. * @param int $id
  574. * @return ResultWrapper
  575. * @throws \Exception
  576. */
  577. private function getCustomerInfoByUserCenterId(int $id): ResultWrapper
  578. {
  579. $objMCustomer = new MCustomer($this->onlineEnterpriseId, $this->onlineUserId);
  580. //获取客户信息
  581. $customerData = $objMCustomer->getCustomerInfoByUserCenterId($id);
  582. if (!$customerData->isSuccess()) {
  583. return ResultWrapper::fail($customerData->getData(), $customerData->getErrorCode());
  584. }
  585. $customerData = $customerData->getData();
  586. if (empty($customerData)) {
  587. return ResultWrapper::fail('未获取到客户信息', ErrorCode::$paramError);
  588. }
  589. return ResultWrapper::success($customerData);
  590. }
  591. /**
  592. * Doc: (des="根据id查询自提点信息")
  593. * User: XMing
  594. * Date: 2020/11/3
  595. * Time: 11:49 上午
  596. * @param int $id
  597. * @return ResultWrapper
  598. * @throws \Exception
  599. */
  600. private function getSelfRuleData(int $id): ResultWrapper
  601. {
  602. $objMDeliverySetting = new MDeliverySetting($this->onlineUserId, $this->onlineEnterpriseId);
  603. $selfRuleDataResult = $objMDeliverySetting->getSelfRuleInfo($id);
  604. if (!$selfRuleDataResult->isSuccess()) {
  605. return ResultWrapper::fail($selfRuleDataResult->getData(), $selfRuleDataResult->getErrorCode());
  606. }
  607. $selfRuleData = $selfRuleDataResult->getData();
  608. $selfRuleData = isset($selfRuleData['setData']) ? $selfRuleData['setData'] : [];
  609. return ResultWrapper::success($selfRuleData);
  610. }
  611. /**
  612. * Doc: (des="根据id获取收货地址信息")
  613. * User: XMing
  614. * Date: 2020/11/3
  615. * Time: 11:52 上午
  616. * @param int $id
  617. * @return ResultWrapper
  618. */
  619. private function getAddressInfo($id): ResultWrapper
  620. {
  621. $objMShippingAddress = new MShippingAddress($this->onlineEnterpriseId);
  622. $result = $objMShippingAddress->getShippingAddressInfo($id);
  623. if (!$result->isSuccess()) {
  624. return ResultWrapper::fail($result->getData(), ErrorCode::$dberror);
  625. }
  626. $addressData = $result->getData();
  627. if (empty($addressData)) {
  628. return ResultWrapper::fail('未获取到收货地址信息', ErrorCode::$dberror);
  629. }
  630. return ResultWrapper::success($addressData);
  631. }
  632. /**
  633. * Doc: (des="小程序下单")
  634. * User: XMing
  635. * Date: 2020/12/18
  636. * Time: 11:39 上午
  637. * @param $params
  638. * @param $ip
  639. * @param $token
  640. * @param $auth
  641. * @return ResultWrapper
  642. * @throws \Exception
  643. */
  644. public function addOrder($params, $ip, $token, $auth): ResultWrapper
  645. {
  646. $goodsData = getArrayItem($params,'goodsData',[]);
  647. unset($params['goodsData']);
  648. $shopGoodsData = getArrayItem($goodsData,'goodsData',[]);//商品数据
  649. unset($goodsData['goodsData']);
  650. $common = array_merge($params,$goodsData);
  651. $params = $common;//公共数据
  652. unset($common);
  653. $params['token'] = $token;
  654. $params['auth'] = $auth;
  655. $params['orderType'] = StatusCode::$orderType['saleOrder'];
  656. $params['userCenterId'] = $this->onlineUserId;
  657. $params['orderStatus'] = StatusCode::$orderStatus['waitPay'];
  658. // 货到付款和银行打款 修改订单状态为待发货
  659. if( in_array($params['payType'],[StatusCode::$payType['cashPay']]) ){
  660. $params['orderStatus'] = StatusCode::$orderStatus['waitDelivery'];
  661. }
  662. $tmpOuterTradeNo = 'tmp' . createOrderSn($params['source'], StatusCode::$orderType['saleOrder'], $this->onlineUserId);
  663. $params['outerTradeNo'] = $tmpOuterTradeNo;
  664. // 格式化订单关联数据
  665. $commonParamsResult = self::formatCommonParams($params);
  666. if (!$commonParamsResult->isSuccess()){
  667. return ResultWrapper::fail($commonParamsResult->getData(),$commonParamsResult->getErrorCode());
  668. }
  669. $params = $commonParamsResult->getData();
  670. //查询商铺对应的仓库
  671. $objMShop = new MShop($this->onlineEnterpriseId, $this->onlineUserId);
  672. $modelResult = $objMShop->getShopDataByShopIds(array_column($shopGoodsData, 'shopId'));
  673. if (!$modelResult->isSuccess()) {
  674. return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
  675. }
  676. $shopMap = $modelResult->getData();
  677. // 将商品数据按照指定的字段分组
  678. $buildGroupResult = self::groupSupplierOrderData($shopGoodsData,$params,$shopMap);
  679. if (!$buildGroupResult->isSuccess()){
  680. return ResultWrapper::fail($buildGroupResult->getData(),$buildGroupResult->getErrorCode());
  681. }
  682. $buildGroup = $buildGroupResult->getData();
  683. //mysql写入数据
  684. $insertOrderResult = self::insertOrder($buildGroup,$params);
  685. if (!$insertOrderResult->isSuccess()){
  686. return ResultWrapper::fail($insertOrderResult->getData(),$insertOrderResult->getErrorCode());
  687. }
  688. $orderIds = $insertOrderResult->getData();
  689. // 处理支付
  690. $payResult = self::toPay($tmpOuterTradeNo,$params,$orderIds,$ip);
  691. if (!$payResult->isSuccess()){
  692. return ResultWrapper::fail($payResult->getData(),$payResult->getErrorCode());
  693. }
  694. // 发送新订单提醒
  695. // parent::sendMessage($this->onlineEnterpriseId,'NewOrder');
  696. $params['orderType'] == StatusCode::$orderType['saleOrder'] && self::runProcessNextAudit($orderIds);
  697. $customerData = $this->objDCustomer->get($buildGroup['orderIndex'][0]['customerId']);
  698. if ($customerData === false) {
  699. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  700. }
  701. if(isset($customerData['openId']) && !empty($customerData['openId'])){
  702. $orderData = $this->objDOrder->get($orderIds);
  703. if($orderData === false){
  704. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  705. }
  706. if( empty($orderData) ){
  707. return ResultWrapper::fail('查找不到该订单数据', ErrorCode::$contentNotExists);
  708. }
  709. foreach($buildGroup['order'] as $key => $value){
  710. // 发送小程序订阅消息
  711. $sendMessageData = [
  712. 'character_string6' => [ 'value' => StatusCode::$noPrefix[1].'-'.$key ], // 订单编号
  713. 'amount10' => [ 'value' => $value['payAmount'] ], // 订单金额
  714. 'thing15' => [ 'value' => $buildGroup['orderReceive'][$key]['realName'] ], // 收货人姓名
  715. 'phone_number16' => [ 'value' => $buildGroup['orderReceive'][$key]['mobile'] ], // 收货人电话
  716. 'phrase19' => [ 'value' => $orderData['payStatus'] == StatusCode::$delete ? '待支付':'已支付'], // 支付状态
  717. ];
  718. $objMSystemPushMessage = new MSystemPushMessage($this->onlineUserId, $this->onlineEnterpriseId);
  719. $result = $objMSystemPushMessage->sendWeiXinPushMessage(1, $customerData['openId'], $sendMessageData, '/pagesT/order/orderDetail?id='.array_pop($orderIds));
  720. if(!$result->isSuccess()){
  721. 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);
  722. }
  723. }
  724. }
  725. return ResultWrapper::success($payResult->getData());
  726. }
  727. /**
  728. * Doc: (des="支付")
  729. * User: XMing
  730. * Date: 2020/12/18
  731. * Time: 4:17 下午
  732. * @param string $tmpOuterTradeNo 临时订单号
  733. * @param array $params 公共参数
  734. * @param array $orderIds 所有订单号
  735. * @param $ip
  736. * @return ResultWrapper
  737. * @throws \Exception
  738. */
  739. public function toPay($tmpOuterTradeNo,$params,$orderIds,$ip): ResultWrapper
  740. {
  741. // 获取支付金额
  742. $payMoney = getArrayItem($params,'payMoney',0);
  743. if (empty($payMoney)){
  744. return ResultWrapper::fail('支付金额异常',ErrorCode::$paramError);
  745. }
  746. // 处理支付方式
  747. $payType = explode(',', $params['payType']);
  748. rsort($payType);
  749. $objSystemCache = new SystemCache();
  750. // 后台代客下单/货到付款/银行打款不需要返回支付配置
  751. if ( $params['source'] == StatusCode::$source['manage'] || in_array(StatusCode::$payType['cashPay'], $payType) ) {
  752. return ResultWrapper::success($orderIds);
  753. }
  754. $payment = [];
  755. $payParams = '';
  756. $payStatus = StatusCode::$partion;
  757. $orderStatus = StatusCode::$orderStatus['waitPay'];
  758. $notPayMoney = $payMoney;
  759. foreach($payType as $k => $v){
  760. //判断支付状态(有银行打款是5,没有直接给3)
  761. // 除了余额支付其他方式都要获取支付配置
  762. if($v != StatusCode::$payType['balance'] && $v != StatusCode::$payType['bankLoans']){
  763. $objMPaymentSetting = new MPaymentSetting($this->onlineUserId, $this->onlineEnterpriseId);
  764. $result = $objMPaymentSetting->getPayData($v);
  765. if (!$result->isSuccess() || empty($result->getData())) {
  766. return ResultWrapper::fail('获取微信配置错误', ErrorCode::$configEroor);
  767. }
  768. $payment = $result->getData();
  769. }
  770. switch (true){
  771. case in_array(StatusCode::$payType['balance'], $payType):
  772. //减少余额()
  773. $status = $this->objDOrderIndex->beginTransaction();
  774. //新增会员流水记录
  775. $memberBalanceDetailData = [
  776. 'customerId' => $params['id'],
  777. 'type' => StatusCode::$delete,
  778. 'userCenterId' => $this->onlineUserId,
  779. 'purpose' => '创建订单消费',
  780. 'orderIds' =>implode(',',$orderIds),
  781. 'remark' => '订单id'.implode(',',$orderIds),
  782. 'financeType' => '会员余额消费'
  783. ];
  784. // 组合支付方式
  785. if( !empty($params['admixPayData']) ) {
  786. foreach ($params['admixPayData'] as $key => $value) {
  787. if ($value['payType'] == StatusCode::$payType['balance']) {
  788. // 本次混合支付余额支付金额
  789. $memberBalanceDetailData['money'] = $value['payMoney'];
  790. // 总金额 - 余额支付金额 = 剩余需要搭配支付金额
  791. $payMoney = bcsub($payMoney, $value['payMoney'], 2);
  792. $notPayMoney = $payMoney;
  793. }
  794. }
  795. }else{
  796. $orderStatus = StatusCode::$orderStatus['waitDelivery'];
  797. $payStatus = StatusCode::$standard;
  798. $memberBalanceDetailData['money'] = $payMoney;
  799. $notPayMoney = 0;
  800. }
  801. $objMMemberBalanceDetail = new MMemberBalanceDetail($this->onlineEnterpriseId,$this->onlineUserId);
  802. $memberBalanceDbResult = $objMMemberBalanceDetail->addMemberBalanceDetail($memberBalanceDetailData);
  803. if (!$memberBalanceDbResult->isSuccess()) {
  804. $this->objDOrderIndex->rollBack();
  805. return ResultWrapper::fail($memberBalanceDbResult->getData(), $memberBalanceDbResult->getErrorCode());
  806. }
  807. // 查询余额对应的银行账户
  808. $defaultAccountResult = $this->objMAccount->getDefaultAccount(StatusCode::$payType['balance']);
  809. if ($defaultAccountResult->isSuccess() == false) {
  810. $this->objDOrderIndex->rollBack();
  811. return ResultWrapper::fail($defaultAccountResult->getData(), $defaultAccountResult->getErrorCode());
  812. }
  813. if(empty($defaultAccountResult->getData())){
  814. $this->objDOrderIndex->rollBack();
  815. return ResultWrapper::fail('没有默认的'.StatusCode::$payType[$payType['balance']].'账户', ErrorCode::$notAllowAccess);
  816. }
  817. $defaultAccount = $defaultAccountResult->getData();
  818. //修改订单状态
  819. $time = time();
  820. $this->objDOrderIndex->setTable('qianniao_order_index_'.$this->onlineEnterpriseId);
  821. $fix = ceil($params['userCenterId'] / $this->cutTable);
  822. $this->objDOrder->setTable('qianniao_order_'.$this->onlineEnterpriseId.'_'.$fix);
  823. foreach ($orderIds as $orderId){
  824. $updateIndexResult = $this->objDOrderIndex->update(['payStatus' => $payStatus,'orderStatus' => $orderStatus,'updateTime' => $time],$orderId);
  825. if ($updateIndexResult === false){
  826. $this->objDOrderIndex->rollBack();
  827. return ResultWrapper::fail($this->objDOrderIndex->error(),ErrorCode::$dberror);
  828. }
  829. $updateIndex = $this->objDOrder->update(['payStatus' => $payStatus,'orderStatus' => $orderStatus,'payTime'=> $time,'updateTime' => $time,'notPayMoney'=>$notPayMoney],$orderId);
  830. if ($updateIndex === false){
  831. $this->objDOrderIndex->rollBack();
  832. return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror);
  833. }
  834. $orderInfo = $this->objDOrder->get($orderId);
  835. if($orderInfo == false){
  836. $this->objDOrderIndex->rollBack();
  837. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  838. }
  839. // 生成收款单
  840. $receivedData = [
  841. 'customerId' => $orderInfo['customerId'],
  842. 'customerName' => $orderInfo['customerName'],
  843. 'currentAccountName' => $orderInfo['shopName'],
  844. 'financeType' => '销售收款',
  845. 'financeTypeId' => StatusCode::$systemFinanceType['saleReceipt'],
  846. 'shopId' => $orderInfo['shopId'],
  847. 'shopName' => $orderInfo['shopName'],
  848. 'receiptTime' => time(),
  849. 'operatorId' => $this->onlineUserId,
  850. 'originId' => $orderId,
  851. 'originNo' => $orderInfo['no'],
  852. 'sourceId' => $orderId,
  853. 'sourceNo' => $orderInfo['no'],
  854. 'sourceNoMoney' => $orderInfo['totalMoney'], //原单据订单总金额
  855. 'auditStatus' => StatusCode::$auditStatus['auditing'],
  856. 'createTime' => time(),
  857. 'updateTime' => time(),
  858. 'accountList' => [
  859. [
  860. "accountId" => isset($defaultAccount['id']) ? $defaultAccount['id'] : 0,
  861. "accountNumber" => isset($defaultAccount['accountNumber']) ? $defaultAccount['accountNumber'] : '',
  862. 'accountName' => isset($defaultAccount['name']) ? $defaultAccount['name'] : '',
  863. "money" => $memberBalanceDetailData['money'],
  864. "discountMoney" => 0,
  865. "finalMoney" => $memberBalanceDetailData['money'],
  866. "payWay" => '余额支付',
  867. "remark" => "在线余额支付自动生成收款单"
  868. ]
  869. ],
  870. ];
  871. $result = $this->objMReceived->addReceived($receivedData, true);
  872. if ($result->isSuccess() == false) {
  873. $this->objDOrderIndex->rollBack();
  874. return ResultWrapper::fail($result->getData(), $result->getErrorCode());
  875. }
  876. unset($receivedData);
  877. unset($result);
  878. }
  879. // 根据客户id (customerId) 获取 openId
  880. if(!empty($orderInfo['customerId'])){
  881. $customerId = $orderInfo['customerId'];
  882. $objDCustomer = new DCustomer('default');
  883. $objDCustomer->setTable($objDCustomer->get_Table() . '_' . $this->onlineEnterpriseId);
  884. $customerData = $objDCustomer->get($customerId);
  885. if($customerData === false){
  886. return ResultWrapper::fail($objDCustomer->error(), ErrorCode::$dberror);
  887. }
  888. if( empty($customerData) ){
  889. return ResultWrapper::fail('查找不到该客户数据', ErrorCode::$contentNotExists);
  890. }
  891. // 小程序订阅消息
  892. if (isset($customerData['openId']) && !empty($customerData['openId'])) {
  893. // 发送小程序订阅消息
  894. $sendMessageData = [
  895. 'character_string3' => ['value' => StatusCode::$noPrefix[1] . '-' . $orderInfo['no']], // 订单编号
  896. 'date10' => ['value' => date('Y-m-d H:i:s', $orderInfo['createTime'])], // 下单时间
  897. 'time4' => ['value' => date('Y-m-d H:i:s', time())], // 支付时间
  898. 'thing7' => ['value' => '余额支付'], // 支付方式
  899. 'name8' => ['value' => substr($orderInfo['shopName'],0,30)] // 商家名称
  900. ];
  901. $objMSystemPushMessage = new MSystemPushMessage($this->onlineUserId, $this->onlineEnterpriseId);
  902. $result = $objMSystemPushMessage->sendWeiXinPushMessage(3, $customerData['openId'], $sendMessageData);
  903. if (!$result->isSuccess()) {
  904. 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);
  905. }
  906. }
  907. }
  908. $status && $this->objDOrderIndex->commit();
  909. $payParams = ResultWrapper::success(['code'=>100,'msg'=>'余额支付成功']);
  910. break;
  911. case in_array(StatusCode::$payType['aliPay'], $payType):
  912. //ali
  913. /*********读取支付宝支付参数(原配置)*********/
  914. /**$aliPayConfigData = Factory::config()->get('alipay');
  915. * if (empty($aliPayConfigData)) {
  916. * return ResultWrapper::fail('支付宝配置错误', ErrorCode::$configEroor);
  917. * }*/
  918. $payOrderData = [
  919. 'subject' => '千鸟云商',
  920. 'out_trade_no' => $tmpOuterTradeNo,
  921. 'total_amount' => $payMoney,
  922. 'passback_params' => $this->onlineEnterpriseId . '|' . $this->onlineUserId . '|' . implode('|', $orderIds),
  923. ];
  924. $aliPayConfigData = [
  925. 'appid' => $payment['appid'],
  926. 'rsaPrivateKey' => $payment['rsaPrivateKey'],
  927. 'alipayrsaPublicKey' => $payment['alipayrsaPublicKey'],
  928. ];
  929. $objAliPay = new aliPay($aliPayConfigData['appid'], $aliPayConfigData['rsaPrivateKey'], $aliPayConfigData['alipayrsaPublicKey']);
  930. $payParams = $objAliPay->appPay($payOrderData);
  931. break;
  932. case in_array(StatusCode::$payType['wxPay'], $payType):
  933. //wx
  934. /********************生成小程序唤起支付用到的参数(原配置)*****/
  935. /**$weixinConfigData = Factory::config()->get('weixin');
  936. * if (empty($weixinConfigData)) {
  937. * return ResultWrapper::fail('微信配置错误', ErrorCode::$configEroor);
  938. * }*/
  939. // 获取当前登录企业的小程序配置
  940. $miniprogramSetting = $objSystemCache->getAppIdByEnterpriseId($this->onlineEnterpriseId);
  941. if (empty($miniprogramSetting)) {
  942. return ResultWrapper::fail('后台小程序配置项为空', ErrorCode::$configEroor);
  943. }
  944. $miniprogramSetting = json_decode($miniprogramSetting, true);//获取小程序appid
  945. // 获取配置文件微信公众号
  946. $weixinConfigData = Factory::config()->getAppoint('weixin', 'offiaccount');
  947. switch ($params['source']) {
  948. case StatusCode::$source['weiXinBrowser'];
  949. if (empty($weixinConfigData)) {
  950. return ResultWrapper::fail('微信公众号配置错误', ErrorCode::$configEroor);
  951. }
  952. $appid = $weixinConfigData['appid'];
  953. $paySource = 'weiXinBrowser';
  954. break;
  955. case StatusCode::$source['H5'];
  956. if (empty($weixinConfigData)) {
  957. return ResultWrapper::fail('微信公众号配置错误', ErrorCode::$configEroor);
  958. }
  959. $appid = $weixinConfigData['appid'];
  960. $paySource = 'H5';
  961. break;
  962. case StatusCode::$source['miniProgram'];
  963. $appid = $miniprogramSetting['appid'];
  964. $paySource = 'miniProgram';
  965. break;
  966. default :
  967. $appid = $payment['mobileAppid'];
  968. $paySource = 'APP';
  969. break;
  970. }
  971. $weixinConfigData = [
  972. 'mch_id' => $payment['mchId'],
  973. 'apiPartnerKey' => $payment['apiPartnerKey'],
  974. 'appid' => $appid
  975. ];
  976. $attach = $this->onlineEnterpriseId . '|' . $this->onlineUserId . '|' . implode('|', $orderIds);
  977. //$objPay = new Pay($appid, $weixinConfigData['pay']['mch_id'], $weixinConfigData['pay']['apiPartnerKey']);//old
  978. //判断是否是子商户,优先选择子商户
  979. if(isset($payment['sub_mch_id']) && !empty($payment['sub_mch_id']) && $payMoney['mch_type'] == 2 ){
  980. $sub_mch_id = $payment['sub_mch_id'];
  981. $sub_weixinConfigData = Factory::config()->get('weixin');
  982. if (empty($sub_weixinConfigData)) {
  983. return ResultWrapper::fail('微信配置错误', ErrorCode::$configEroor);
  984. }
  985. $objPay = new Pay($appid, $sub_weixinConfigData['service_pay']['mch_id'], $sub_weixinConfigData['service_pay']['apiPartnerKey']);
  986. $payParams = $objPay->unifiedorder($tmpOuterTradeNo,$payMoney, $ip, $paySource, '千鸟云商', $params['openId'], $attach,$sub_mch_id);
  987. break;
  988. }
  989. $objPay = new Pay($appid, $weixinConfigData['mch_id'], $weixinConfigData['apiPartnerKey']);
  990. $payParams = $objPay->unifiedorder($tmpOuterTradeNo,$payMoney, $ip, $paySource, '千鸟云商', $params['openId'], $attach);
  991. break;
  992. case in_array(StatusCode::$payType['byte'],$payType):
  993. //字节跳动
  994. $mweb_url = '';
  995. //读取缓存配置
  996. //$objSystemCache->getByteDanceSetting($this->onlineEnterpriseId);
  997. // 获取配置文件字节小程序
  998. $byteDanceConfigData = Factory::config()->getAppoint('byteDance', 'pay');
  999. if (empty($byteDanceConfigData)) {
  1000. return ResultWrapper::fail('字节跳动配置错误', ErrorCode::$configEroor);
  1001. }
  1002. $objbytePay = new bytePay($byteDanceConfigData['appid'], $byteDanceConfigData['merchant_id'], $byteDanceConfigData['app_secret']);
  1003. unset($payParams);
  1004. $payParams = $objbytePay->pay($tmpOuterTradeNo, $payMoney, '千鸟云商', $ip, $mweb_url);
  1005. break;
  1006. case in_array(StatusCode::$payType['bankLoans'], $payType):
  1007. foreach ($orderIds as $orderId){
  1008. $orderInfo = $this->objDOrder->get($orderId);
  1009. if($orderInfo == false){
  1010. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  1011. }
  1012. }
  1013. // 根据客户id (customerId) 获取 openId
  1014. if(!empty($orderInfo['customerId'])){
  1015. $customerId = $orderInfo['customerId'];
  1016. $objDCustomer = new DCustomer('default');
  1017. $objDCustomer->setTable($objDCustomer->get_Table() . '_' . $this->onlineEnterpriseId);
  1018. $customerData = $objDCustomer->get($customerId);
  1019. if($customerData === false){
  1020. return ResultWrapper::fail($objDCustomer->error(), ErrorCode::$dberror);
  1021. }
  1022. if( empty($customerData) ){
  1023. return ResultWrapper::fail('查找不到该客户数据', ErrorCode::$contentNotExists);
  1024. }
  1025. // 小程序订阅消息
  1026. if (isset($customerData['openId']) && !empty($customerData['openId'])) {
  1027. // 发送小程序订阅消息
  1028. $sendMessageData = [
  1029. 'character_string3' => ['value' => StatusCode::$noPrefix[1] . '-' . $orderInfo['no']], // 订单编号
  1030. 'date10' => ['value' => date('Y-m-d H:i:s', $orderInfo['createTime'])], // 下单时间
  1031. 'time4' => ['value' => date('Y-m-d H:i:s', time())], // 支付时间
  1032. 'thing7' => ['value' => '银行打款'], // 支付方式
  1033. 'name8' => ['value' => substr($orderInfo['shopName'],0,30)] // 商家名称
  1034. ];
  1035. $objMSystemPushMessage = new MSystemPushMessage($this->onlineUserId, $this->onlineEnterpriseId);
  1036. $result = $objMSystemPushMessage->sendWeiXinPushMessage(3, $customerData['openId'], $sendMessageData);
  1037. if (!$result->isSuccess()) {
  1038. 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);
  1039. }
  1040. }
  1041. }
  1042. $payParams = ResultWrapper::success($orderIds);
  1043. break;
  1044. default:
  1045. //TODO
  1046. return ResultWrapper::fail('暂未开放的支付方式',ErrorCode::$paramError);
  1047. break;
  1048. }
  1049. unset($payType[$k]);
  1050. if (!$payParams->isSuccess()) {
  1051. return ResultWrapper::fail($payParams->getData(), $payParams->getErrorCode());
  1052. }
  1053. }
  1054. return ResultWrapper::success($payParams->getData());
  1055. }
  1056. /**
  1057. * Doc: (des="已审核未出库订单,审核驳回")
  1058. * User: XMing
  1059. * Date: 2021/2/25
  1060. * Time: 9:41 上午
  1061. * @param int $orderId
  1062. * @return ResultWrapper
  1063. * @throws \Exception
  1064. */
  1065. public function revokeAudit(int $orderId): ResultWrapper
  1066. {
  1067. $orderIndex = $this->objDOrderIndex->get($orderId);
  1068. if ($orderIndex === false) {
  1069. return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
  1070. }
  1071. if (empty($orderIndex)) {
  1072. return ResultWrapper::fail('未获取到指定订单', ErrorCode::$paramError);
  1073. }
  1074. $fix = ceil((empty($params['userCenterId']) ? 1 : $params['userCenterId']) / $this->cutTable);
  1075. $this->objDOrder->setTable('qianniao_order_'.$this->onlineEnterpriseId.'_'.$fix);
  1076. $orderData = $this->objDOrder->get($orderId);
  1077. if ($orderData === false){
  1078. return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror);
  1079. }
  1080. if (empty($orderData)){
  1081. return ResultWrapper::fail('为获取到指定的订单信息',ErrorCode::$paramError);
  1082. }
  1083. if ($orderData['auditStatus'] != StatusCode::$auditStatus['auditPass']){
  1084. return ResultWrapper::fail('订单审核状态异常,不能驳回',ErrorCode::$paramError);
  1085. }
  1086. if ($orderData['outStatus'] != StatusCode::$delete){
  1087. return ResultWrapper::fail('订单已经出库,不能驳回',ErrorCode::$paramError);
  1088. }
  1089. if ($orderData['orderStatus'] == StatusCode::$orderStatus['close']){
  1090. return ResultWrapper::fail('订单已关闭,不嫩驳回',ErrorCode::$paramError);
  1091. }
  1092. $this->objDOrderIndex->beginTransaction();
  1093. $time = time();
  1094. //update order
  1095. $updateOrder = $this->objDOrder->update([
  1096. 'auditStatus' => StatusCode::$auditStatus['auditing'],
  1097. 'updateTime' => $time,
  1098. 'revokeTime' => $time
  1099. ],$orderId);
  1100. if ($updateOrder === false){
  1101. $this->objDOrderIndex->rollBack();
  1102. return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror);
  1103. }
  1104. //update orderIndex
  1105. $updateOrderIndex = $this->objDOrderIndex->update([
  1106. 'auditStatus' => StatusCode::$auditStatus['auditing'],
  1107. 'updateTime' => $time
  1108. ],$orderId);
  1109. if ($updateOrderIndex === false){
  1110. $this->objDOrderIndex->rollBack();
  1111. return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror);
  1112. }
  1113. //update stock
  1114. $objMInventoryOut = new MInventoryOut($this->onlineEnterpriseId,$this->onlineUserId);
  1115. $stockOutResult = $objMInventoryOut->delInventoryOutStatus([
  1116. 'sourceId' => $orderId,
  1117. 'type' => StatusCode::$orderType['saleOut']
  1118. ]);
  1119. if (!$stockOutResult->isSuccess()){
  1120. $this->objDOrderIndex->rollBack();
  1121. return ResultWrapper::fail($stockOutResult->getData(),$stockOutResult->getErrorCode());
  1122. }
  1123. // 删除已生成的收款单
  1124. $objDReceivedIndex = new DReceivedIndex('finance');
  1125. $objDReceivedIndex->setTable('qianniao_received_index_' . $this->onlineEnterpriseId);
  1126. $deleteReceive = $objDReceivedIndex->delete(['sourceId'=>$orderIndex['id']]);
  1127. if ($deleteReceive === false) {
  1128. return ResultWrapper::fail($objDReceivedIndex->error(), ErrorCode::$dberror);
  1129. }
  1130. /*
  1131. //update es
  1132. $_id = self::createEsDocumentId($orderId);
  1133. $this->objDOrder->esupdateTypeFieldVaule([
  1134. 'auditStatus' => StatusCode::$auditStatus['auditing'],
  1135. 'updateTime' => $time
  1136. ], $_id);*/
  1137. $this->objDOrderIndex->commit();
  1138. return ResultWrapper::success(true);
  1139. }
  1140. /**
  1141. * Doc: (des="")
  1142. * User: XMing
  1143. * Date: 2021/3/9
  1144. * Time: 5:13 下午
  1145. * @param int $orderId
  1146. * @return ResultWrapper
  1147. * @throws \Exception
  1148. */
  1149. public function reStockOut(int $orderId): ResultWrapper
  1150. {
  1151. // 获取订单索引表数据
  1152. $orderIndex = $this->objDOrderIndex->get($orderId);
  1153. if ($orderIndex === false){
  1154. return ResultWrapper::fail($this->objDOrderIndex->error(),ErrorCode::$dberror);
  1155. }
  1156. if (empty($orderIndex)){
  1157. return ResultWrapper::fail('未获取到指定地订单信息',ErrorCode::$paramError);
  1158. }
  1159. // 获取订单数据
  1160. $fix = ceil($orderIndex['userCenterId'] / $this->cutTable);
  1161. $this->objDOrder->setTable('qianniao_order_'.$this->onlineEnterpriseId.'_'.$fix);
  1162. $orderData = $this->objDOrder->get($orderId);
  1163. if ($orderData === false){
  1164. return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror);
  1165. }
  1166. if (empty($orderData)){
  1167. return ResultWrapper::fail('未获取到指定的订单信息',ErrorCode::$paramError);
  1168. }
  1169. if ($orderData['outStatus'] == StatusCode::$standard){
  1170. return ResultWrapper::fail('订单已经出库,请不要重复出库',ErrorCode::$paramError);
  1171. }
  1172. // 查询销售订单是否还有未审核的出库单,必须先处理完,再生成新的出库单
  1173. $objMInventoryOut = new MInventoryOut($this->onlineEnterpriseId,$this->onlineUserId);
  1174. $condition = [
  1175. 'originId' => $orderData['id'],
  1176. 'deleteStatus' => StatusCode::$standard,
  1177. 'auditStatus' => StatusCode::$auditStatus['auditing'],
  1178. ];
  1179. $result = $objMInventoryOut->getInventoryOutData($condition);
  1180. if (!$result->isSuccess()) {
  1181. return ResultWrapper::fail($result->getData(), ErrorCode::$dberror);
  1182. }
  1183. $inventoryOutData = $result->getData();
  1184. if( !empty($inventoryOutData) ){
  1185. return ResultWrapper::fail('当前销售订单还有未审核的出库单,单号:'.StatusCode::$noPrefix[5].'-'.$inventoryOutData[0]['no'].',请先处理完成', ErrorCode::$notAllowAccess);
  1186. }
  1187. // 查询订单商品表数据
  1188. $this->objDOrderGoods->setTable('qianniao_order_goods_'.$this->onlineEnterpriseId.'_'.$fix);
  1189. $orderGoodsData = $this->objDOrderGoods->select(['orderId' => $orderId,'deleteStatus' => StatusCode::$standard]);
  1190. if ($orderGoodsData === false){
  1191. return ResultWrapper::fail($this->objDOrderGoods->error(),ErrorCode::$dberror);
  1192. }
  1193. if (empty($orderGoodsData)){
  1194. return ResultWrapper::fail('订单商品获取失败',ErrorCode::$paramError);
  1195. }
  1196. // 组装出库单数据
  1197. $saleOutData = [
  1198. 'sourceId' => $orderData['id'],
  1199. 'sourceNo' => $orderData['no'],
  1200. 'originNo' => $orderData['no'],
  1201. 'originId' => $orderData['id'],
  1202. 'shopId' => $orderData['shopId'],
  1203. 'shopName' => $orderData['shopName'],
  1204. 'amount' => $orderData['payAmount'],
  1205. 'operatorId' => $orderData['auditId'],//操作人id
  1206. 'operatorName' => $orderData['audit'],//操作人信息
  1207. 'customerId' => $orderData['customerId'],
  1208. 'customerName' => $orderData['customerName'],
  1209. 'customerCode' => createCode(StatusCode::$code['customer']['prefix'], $orderData['customerId'], StatusCode::$code['customer']['length']),
  1210. 'customerMobile' => $orderData['customerMobile'],
  1211. 'source' => StatusCode::$orderType['saleOrder'], //订单来源(出库类型)
  1212. 'type' => StatusCode::$orderType['saleOut'],
  1213. 'deliveryType' => $orderData['deliveryType'],//配送方式
  1214. 'remark' => $orderData['remark'],
  1215. ];
  1216. $saleOutData['materielNum'] = 0;
  1217. //获取sku
  1218. $objMSku = new MSku($this->onlineUserId, $this->onlineEnterpriseId);
  1219. $skuIds = array_column(array_values($orderGoodsData), 'skuId');
  1220. $modelResult = $objMSku->getSkuDataBySkuIds($skuIds);
  1221. if (!$modelResult->isSuccess()) {
  1222. return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
  1223. }
  1224. $skuData = $modelResult->getData();
  1225. unset($modelResult);
  1226. foreach ($orderGoodsData as $key => $value) {
  1227. if ($value['outOfNum'] > 0 && $value['isEq'] == StatusCode::$delete){
  1228. $saleOutData['materielNum']++;
  1229. $totalMoney = bcsub(bcsub($value['totalMoney'], $value['vipDiscount']), $value['preferential']);//销售总价 !优惠后
  1230. $saleOutData['orderGoodsData'][] = [
  1231. 'materielId' => $value['goodsBasicId'],
  1232. 'materielName' => $value['goodsName'],
  1233. 'materielCode' => createCode(StatusCode::$code['goodsBasic']['prefix'], $value['goodsBasicId'], StatusCode::$code['goodsBasic']['length']),
  1234. 'skuId' => $value['skuId'],
  1235. 'num' => $value['outOfNum'],
  1236. 'otherNum' => $value['otherNum'],
  1237. 'outNum' => 0,
  1238. 'total' => $value['outOfNum'],
  1239. 'unitName' => isset($value['unitName']) ? $value['unitName'] : '',
  1240. 'skuName' => isset($skuData[$value['skuId']]) ? $skuData[$value['skuId']]['skuName'] : '',
  1241. 'unitPrice' => $value['price'],//单价 不优惠
  1242. 'totalPrice' => $totalMoney,//销售总价 !优惠后
  1243. ];
  1244. }
  1245. }
  1246. if (empty($saleOutData['orderGoodsData'])){
  1247. return ResultWrapper::fail('此订单没有需要出库的商品',ErrorCode::$paramError);
  1248. }
  1249. // 新增出库单
  1250. $dbResult = $objMInventoryOut->addInventoryOut($saleOutData);
  1251. if (!$dbResult->isSuccess()){
  1252. return ResultWrapper::fail($dbResult->getData(),$dbResult->getErrorCode());
  1253. }
  1254. return ResultWrapper::success($dbResult->getData());
  1255. }
  1256. /**
  1257. * Doc: (des="")
  1258. * User: XMing
  1259. * Date: 2021/3/18
  1260. * Time: 6:55 下午
  1261. * @param int $orderId
  1262. * @return ResultWrapper
  1263. * @throws \Exception
  1264. */
  1265. public function retAmount(int $orderId)
  1266. {
  1267. $message = '退款成功';
  1268. // 从订单索引表查询订单数据
  1269. $orderIndex = $this->objDOrderIndex->get($orderId);
  1270. if ($orderIndex === false){
  1271. return ResultWrapper::fail($this->objDOrderIndex->error(),ErrorCode::$dberror);
  1272. }
  1273. if (empty($orderIndex)){
  1274. return ResultWrapper::fail('未获取到订单数据',ErrorCode::$paramError);
  1275. }
  1276. // 从订单和订单商品查询订单数据
  1277. $fix = ceil($orderIndex['userCenterId'] / $this->cutTable);
  1278. $this->objDOrder->setTable('qianniao_order_'.$this->onlineEnterpriseId.'_'.$fix);
  1279. $this->objDOrderGoods->setTable('qianniao_order_goods_'.$this->onlineEnterpriseId.'_'.$fix);
  1280. $order = $this->objDOrder->get($orderId);
  1281. if ($order === false){
  1282. return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror);
  1283. }
  1284. if ( empty($order) ){
  1285. return ResultWrapper::fail('未获取到指定订单信息',ErrorCode::$paramError);
  1286. }
  1287. $sql = 'SELECT * FROM qianniao_order_goods_'.$this->onlineEnterpriseId.'_'.$fix.' WHERE orderId = '.$orderId.' AND deleteStatus = '.StatusCode::$standard.' AND outOfNum > 0';
  1288. $rows = $this->objDOrderGoods->query($sql);
  1289. if ($rows === false){
  1290. return ResultWrapper::fail($this->objDOrderGoods->error(),ErrorCode::$dberror);
  1291. }
  1292. if (empty($rows)){
  1293. return ResultWrapper::fail('未获取到指定订单的商品信息',ErrorCode::$paramError);
  1294. }
  1295. // 根据实际订单未出库数量计算退款金额
  1296. $receiveMoney = 0;
  1297. foreach ($rows as $row){
  1298. if ($row['outOfNum'] <= 0) continue;
  1299. $receiveMoney = bcadd($receiveMoney,bcmul($row['price'],$row['outOfNum'], 4),4);
  1300. }
  1301. // 保留4位判断金额是否异常
  1302. if ($receiveMoney <= 0){
  1303. return ResultWrapper::fail('退款金额异常',ErrorCode::$paramError);
  1304. }
  1305. $receiveMoney = bcadd($receiveMoney, '0', 2); // 实际退款保留两位
  1306. $status = $this->objDOrder->beginTransaction();
  1307. $payType = explode(',', $orderIndex['payType']);
  1308. // 未支付订单不生成退款单
  1309. if( $order['payStatus'] == StatusCode::$standard){
  1310. // 小于1分钱不做退款处理
  1311. if ($receiveMoney >= 0.01){
  1312. // 根据订单支付方式规划退款账户
  1313. $objMAccount = new MAccount($this->onlineEnterpriseId,$this->onlineUserId);
  1314. // 包含余额组合支付方式统一返回余额,其他原路返回
  1315. if( in_array(StatusCode::$payType['balance'],$payType) ){
  1316. $financeAccountData = $objMAccount->getDefaultAccount(StatusCode::$payType['balance']);
  1317. }else if( in_array(StatusCode::$payType['bankLoans'],$payType) ){
  1318. $extends = json_decode($order['extends'], true);
  1319. if( isset($extends['bankData']['id']) && !empty($extends['bankData']['id'])){
  1320. $accountId = $extends['bankData']['id'];
  1321. //获取银行打款账户信息
  1322. $financeAccountData = $objMAccount->getAccountInfo($accountId);
  1323. }else{
  1324. $financeAccountData = ResultWrapper::fail('获取打款账户错误');
  1325. }
  1326. } else{
  1327. $financeAccountData = $objMAccount->getDefaultAccount($payType);
  1328. }
  1329. if(!$financeAccountData->isSuccess()){
  1330. return ResultWrapper::fail($financeAccountData->getData(), $financeAccountData->getErrorCode());
  1331. }
  1332. $financeAccountData = $financeAccountData->getData();
  1333. //记录负应收的id
  1334. //$financeRefundData['offsetId'] = (int)$addReceiveResult->getData();
  1335. // 生成财务退款单
  1336. $financeRefundData = [
  1337. 'originId' => getArrayItem($order,'id',0),
  1338. 'originNo' => getArrayItem($order,'no',''),
  1339. 'sourceId' => getArrayItem($order,'id',0),
  1340. 'sourceNo' => getArrayItem($order,'no',''),
  1341. 'refundTime' => time(),
  1342. 'createTime' => time(),
  1343. 'unitId' => getArrayItem($order,'customerId',0),
  1344. 'unitName' => getArrayItem($order,'customerName',0),
  1345. 'currentAccountName' => getArrayItem($order,'customerName',''),
  1346. 'financeType' => '订单完结退款',
  1347. 'financeTypeId' => 1,
  1348. 'payType' =>getArrayItem($order,'payType',''),
  1349. 'shopId' => getArrayItem($order,'shopId',0),
  1350. 'shopName' => getArrayItem($order,'shopName',0),
  1351. 'money' => $receiveMoney,
  1352. 'operatorId' => $this->onlineUserId,
  1353. 'type' => StatusCode::$standard,
  1354. 'auditStatus' => StatusCode::$auditStatus['auditing'],
  1355. 'remark' => '订单一键完结,订单编号:'. getArrayItem($order,'no','').'完结后需退款金额:'.$receiveMoney
  1356. ];
  1357. $financeRefundData['accountList'] = [
  1358. [
  1359. 'accountId' => $financeAccountData['id'],
  1360. 'accountNumber' => $financeAccountData['accountNumber'],
  1361. 'accountName' => $financeAccountData['name'],
  1362. 'money' => $receiveMoney,
  1363. ]
  1364. ];
  1365. $objMRefund = new MRefund($this->onlineEnterpriseId,$this->onlineUserId);
  1366. $result = $objMRefund->addRefund($financeRefundData);
  1367. if(!$result->isSuccess()){
  1368. $this->objDOrder->rollBack();
  1369. return ResultWrapper::fail($result->getData(),$result->getErrorCode());
  1370. }
  1371. // 应收自动审核队列
  1372. //Factory::cache('finance')->zadd('salesOutReceive::'.$this->onlineEnterpriseId, time(), $addReceiveResult->getData());
  1373. }else{
  1374. $message = '退款金额少于0.01,不做退款处理,退款成功';
  1375. }
  1376. }
  1377. $updateIndexData = [
  1378. 'updateTime' => time(),
  1379. 'isRet' => StatusCode::$standard,
  1380. ];
  1381. $updateOrderIndex = $this->objDOrderIndex->update($updateIndexData, $orderId);
  1382. if ($updateOrderIndex === false){
  1383. $this->objDOrder->rollBack();
  1384. return ResultWrapper::fail($this->objDOrderIndex->error(),ErrorCode::$dberror);
  1385. }
  1386. $update = [
  1387. 'updateTime' => time(),
  1388. 'retTime' => time(),
  1389. 'retMoney' => $receiveMoney,
  1390. 'isRet' => StatusCode::$standard,
  1391. ];
  1392. $updateOrder = $this->objDOrder->update($update,$orderId);
  1393. if ($updateOrder === false){
  1394. $this->objDOrder->rollBack();
  1395. return ResultWrapper::fail($this->objDOrderIndex->error(),ErrorCode::$dberror);
  1396. }
  1397. //订单解锁
  1398. $objMInventory = new MInventory($this->onlineEnterpriseId, $this->onlineUserId);
  1399. $unlockResult = $objMInventory->unlockInventory([$orderId], StatusCode::$orderType['saleOrder'], $orderIndex['createTime']);
  1400. if (!$unlockResult->isSuccess()) {
  1401. $this->objDOrder->rollBack();
  1402. return ResultWrapper::fail($unlockResult->getData(), ErrorCode::$dberror);
  1403. }
  1404. $status && $this->objDOrder->commit();
  1405. return ResultWrapper::success($message);
  1406. }
  1407. /**
  1408. * Doc: (des="创建分销")
  1409. * User: XMing
  1410. * Date: 2020/7/29
  1411. * Time: 6:41 下午
  1412. * @param string $token
  1413. * @param string $auth
  1414. * @param int $customerId
  1415. * @param int $orderId
  1416. */
  1417. private function taskCreateCommission(string $token, string $auth, int $customerId, int $orderId)
  1418. {
  1419. $i = 1;
  1420. do {
  1421. $postData = [
  1422. 'topicName' => 'MyJob',
  1423. 'topicClass' => 'Jobs\Model\MTopic\Order\MCommissionOrder',
  1424. 'topicMethon' => 'push',
  1425. 'topicMethonParams' => [
  1426. 'Authorization' => $auth,
  1427. 'Token' => $token,
  1428. 'orderId' => $orderId,
  1429. 'customerId' => $customerId,
  1430. 'PROJECT_DOMAIN' => PROJECT_DOMAIN
  1431. ],
  1432. ];
  1433. $url = QIANNIAO_QUEUE . '/CAddJob/add';
  1434. $result = request($url, $postData);
  1435. $i++;
  1436. } while ($result['httpcode'] != 200 && $i <= 3);
  1437. Logger::logs(E_USER_ERROR, '投递任务成功', __CLASS__, __LINE__, $postData);
  1438. }
  1439. /**
  1440. * Doc: (des="修改订单的退货状态")
  1441. * User: XMing
  1442. * Date: 2020/7/14
  1443. * Time: 3:54 下午
  1444. * @param $params
  1445. * @return ResultWrapper
  1446. * @throws \Exception
  1447. */
  1448. public function editOrder($params)
  1449. {
  1450. if (empty($params['id'])) {
  1451. return ResultWrapper::fail('没有订单id', ErrorCode::$paramError);
  1452. }
  1453. $id = $params['id'];
  1454. unset($params['id']);
  1455. $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId);
  1456. $orderIndex = $this->objDOrderIndex->get(['id' => $id], 'userCenterId');
  1457. if ($orderIndex === false) {
  1458. return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
  1459. }
  1460. $this->objDOrderIndex->beginTransaction();
  1461. $updateResult = $this->objDOrderIndex->update([
  1462. 'updateTime' => $params['updateTime'],
  1463. 'returnStatus' => $params['returnStatus'],
  1464. ], ['id' => $id]);
  1465. if ($updateResult === false) {
  1466. $this->objDOrderIndex->rollBack();
  1467. return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
  1468. }
  1469. $tableNum = ceil($orderIndex['userCenterId'] / $this->cutTable);
  1470. $this->objDOrder->setTable('qianniao_order_' . $this->onlineEnterpriseId . '_' . $tableNum);
  1471. $dbResult = $this->objDOrder->update([
  1472. 'updateTime' => $params['updateTime'],
  1473. 'returnStatus' => $params['returnStatus'],
  1474. ], $id);
  1475. if ($dbResult === false) {
  1476. $this->objDOrderIndex->rollBack();
  1477. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  1478. }
  1479. $this->objDOrderIndex->commit();
  1480. /*//修改es数据
  1481. $_id = self::createEsDocumentId($id);
  1482. $this->objDOrder->esupdateTypeFieldVaule(['returnStatus' => $params['returnStatus'], 'updateTime' => $params['updateTime']], $_id);*/
  1483. return ResultWrapper::success($dbResult);
  1484. }
  1485. /**
  1486. * 更新ES
  1487. * @param $orderId
  1488. * @param $order
  1489. * @param $addressData
  1490. * @param $addOrderGoodsName
  1491. * @param int $userCenterId
  1492. */
  1493. public function updateEsData($orderId, $order, $addressData, $addOrderGoodsName, $userCenterId = 0)
  1494. {
  1495. $orderEsData = [
  1496. /*订单表信息*/
  1497. 'id' => $orderId,//订单编号,
  1498. 'no' => $order['no'],//订单编号,
  1499. 'outerTradeNo' => '',//'外部流水号(支付宝/微信返回的流水号)'
  1500. 'shopId' => $order['shopId'],
  1501. 'shopName' => $order['shopName'],
  1502. 'enterpriseId' => $this->onlineEnterpriseId,
  1503. 'userCenterId' => $userCenterId != 0 ? $userCenterId : $this->onlineUserId,
  1504. 'totalMoney' => $order['totalMoney'],
  1505. 'payAmount' => $order['payAmount'],
  1506. 'buyTotal' => isset($order['buyTotal']) ? $order['buyTotal'] : 0,//购买总数
  1507. 'customerName' => $order['customerName'],//客户姓名
  1508. 'customerId' => $order['customerId'],//客户id
  1509. 'customerType' => isset($order['customerType']) ? $order['customerType'] : 0,//客户类型
  1510. 'payStatus' => StatusCode::$delete,//'支付状态 默认4 未支付 5已支付'
  1511. 'orderStatus' => StatusCode::$orderStatus['waitPay'],//订单状态 默认1 创建 2待支付 3代发货 4待收货 5已完成 6已关闭
  1512. 'payType' => $order['payType'],//'支付方式 1微信 2支付宝 3货到付款 4上门自提'
  1513. 'deliveryType' => $order['deliveryType'],//'配送方式 1商品配送 2上门自提'
  1514. 'source' => $order['source'],//订单来源 默认1 ios 2android 3小程序 4后台创建
  1515. 'remark' => $order['remark'],//订单备注
  1516. 'auditStatus' => $order['auditStatus'],// '审核状态 默认1 待审 2审核通过 3 审核未通过 4 审核中'
  1517. //'payTime' => '',//'付款时间'
  1518. 'createTime' => $order['createTime'],//'创建时间'
  1519. 'updateTime' => $order['updateTime'],//'修改时间',
  1520. 'salesManId' => isset($order['salesManId']) ? $order['salesManId'] : 0,
  1521. 'salesManName' => isset($order['salesManName']) ? $order['salesManName'] : '',
  1522. 'returnStatus' => StatusCode::$orderReturn['notReturn'],
  1523. 'outStatus' => StatusCode::$delete,
  1524. 'verifyCode' => $order['verifyCode'],//核销码
  1525. /*收货人信息*/
  1526. 'realName' => isset($addressData['realName']) ? $addressData['realName'] : '',//收货人姓名
  1527. 'mobile' => isset($addressData['mobile']) ? $addressData['mobile'] : '',//收货人电话
  1528. 'address' => isset($addressData['address']) ? $addressData['address'] : '',//收货详细地址
  1529. 'provinceCode' => isset($addressData['provinceCode']) ? $addressData['provinceCode'] : '',//收货人省份编码
  1530. 'cityCode' => isset($addressData['cityCode']) ? $addressData['cityCode'] : '',//收货人城市编码
  1531. 'districtCode' => isset($addressData['districtCode']) ? $addressData['districtCode'] : '',//收货人区编码
  1532. /*优惠信息*/
  1533. 'preferential' => $order['preferential'],//优惠券优惠金额
  1534. 'vipDiscount' => $order['vipDiscount'],//会员卡优惠金额
  1535. 'vipDoubleDiscount' => $order['vipDoubleDiscount'],//会员卡折上折优惠金额
  1536. /*商品信息*/
  1537. 'goodsName' => $addOrderGoodsName,
  1538. 'orderType' => isset($order['orderType']) ? $order['orderType'] : StatusCode::$orderType['salesSlip'],
  1539. ];
  1540. isset($order['salesManName']) && $orderEsData['salesManName'] = $order['salesManName'];
  1541. $_id = self::createEsDocumentId($orderId);
  1542. $result = $this->objDOrder->addUpSearchIndexDocument($orderEsData, $_id);
  1543. if (isset($result['_shards']) && isset($result['_shards']['successful']) && $result['_shards']['successful'] == 1) {
  1544. //echo "es操作成功";
  1545. //return;
  1546. }
  1547. //echo "es操作失败";
  1548. }
  1549. /**
  1550. * 创建文档id
  1551. *
  1552. * @param $orderId
  1553. * @return string
  1554. */
  1555. private function createEsDocumentId($orderId)
  1556. {
  1557. return 'EnterpriseId_' . $this->onlineEnterpriseId . '_OrderId_' . $orderId;
  1558. }
  1559. /**
  1560. * Doc: (des="获取订单创建时间,用于其它业务计算分表使用")
  1561. * User: XMing
  1562. * Date: 2020/12/25
  1563. * Time: 2:16 下午
  1564. * @param $orderId
  1565. * @return ResultWrapper
  1566. * @throws \Exception
  1567. */
  1568. public function getOrderCreateTime($orderId)
  1569. {
  1570. $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId);
  1571. $orderIndexRes = $this->objDOrderIndex->get_by('id', $orderId);
  1572. if ($orderIndexRes === false) {
  1573. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  1574. }
  1575. if (empty($orderIndexRes)) {
  1576. return ResultWrapper::fail('未找到订单信息', ErrorCode::$paramError);
  1577. }
  1578. return ResultWrapper::success($orderIndexRes);
  1579. }
  1580. /**
  1581. * Doc: (des="获取订单详情")
  1582. * User: XMing
  1583. * Date: 2020/7/14
  1584. * Time: 6:25 下午
  1585. * @param $id
  1586. * @return ResultWrapper
  1587. * @throws \Exception
  1588. */
  1589. public function getOrderInfoById($id): ResultWrapper
  1590. {
  1591. $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId);
  1592. $orderIndexRes = $this->objDOrderIndex->get_by('id', $id);
  1593. if ($orderIndexRes === false) {
  1594. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  1595. }
  1596. if (empty($orderIndexRes)) {
  1597. return ResultWrapper::fail('未找到订单信息', ErrorCode::$paramError);
  1598. }
  1599. //切换分表
  1600. self::orderSubTable($this->onlineEnterpriseId, $orderIndexRes['userCenterId']);
  1601. $dbResult = $this->objDOrder->get_by('id', $id);
  1602. if ($dbResult === false) {
  1603. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  1604. }
  1605. $formatData = self::format($dbResult);
  1606. if (!$formatData->isSuccess()){
  1607. return ResultWrapper::fail($formatData->getData(),$formatData->getErrorCode());
  1608. }
  1609. $dbResult = $formatData->getData();
  1610. //添加订单打印的数据
  1611. $printResult = self::printInfo($dbResult);
  1612. if (!$printResult->isSuccess()){
  1613. return ResultWrapper::fail($printResult->getData(),$printResult->getErrorCode());
  1614. }
  1615. $dbResult = $printResult->getData();
  1616. //logisticsData
  1617. $dbResult['logisticsData'] = json_decode($dbResult['logisticsData'],true);
  1618. // 查询订单退货对应退货单的状态
  1619. if($dbResult['returnStatus']){
  1620. $objMOrderReturn = new MOrderReturn($this->onlineEnterpriseId, $this->onlineUserId);
  1621. $result = $objMOrderReturn->getAuditStatusByOrderId($id);
  1622. $dbResult['returnAuditStatus'] = StatusCode::$auditStatus['auditing'];
  1623. if($result->isSuccess()){
  1624. $dbResult['returnAuditStatus'] = $result->getData();
  1625. }
  1626. }
  1627. return ResultWrapper::success($dbResult);
  1628. }
  1629. /**
  1630. * 补充打印订单字段信息
  1631. *
  1632. * @param $dbResult
  1633. * @return ResultWrapper
  1634. * @throws \Exception
  1635. */
  1636. public function printInfo($dbResult)
  1637. {
  1638. if ($dbResult['source'] == StatusCode::$source['manage']){
  1639. $dbResult['receivable'] = $dbResult['totalMoney'];//应收
  1640. }else{
  1641. $dbResult['receivable'] = $dbResult['payAmount'];//应收
  1642. }
  1643. if ($dbResult['payType'] == StatusCode::$payType['cashPay']
  1644. || $dbResult['payType'] == StatusCode::$payType['bankLoans']
  1645. ) {
  1646. //货到付款 已支付 = payAmount金额
  1647. if ($dbResult['source'] == StatusCode::$source['manage']){
  1648. $dbResult['netReceipts'] = isset($dbResult['receivedMoney']) ? $dbResult['receivedMoney'] : 0;
  1649. }else{
  1650. if ($dbResult['payStatus'] == StatusCode::$standard) {
  1651. $dbResult['netReceipts'] = $dbResult['payAmount'];//实收
  1652. } else {
  1653. $dbResult['netReceipts'] = 0;//实收
  1654. }
  1655. }
  1656. } else {
  1657. //在线支付 已支付 = payAmount金额
  1658. if ($dbResult['payStatus'] == StatusCode::$standard) {
  1659. $dbResult['netReceipts'] = $dbResult['payAmount'];//实收
  1660. } else {
  1661. $dbResult['netReceipts'] = 0;//实收
  1662. }
  1663. }
  1664. $dbResult['currentShortage'] = bcsub($dbResult['receivable'], $dbResult['netReceipts'], 2);//本单欠
  1665. $dbResult['upOwe'] = $dbResult['customerOwe'];//上欠
  1666. $dbResult['totalDeficit'] = bcadd($dbResult['currentShortage'], $dbResult['upOwe'], 2);
  1667. $objMShop = new MShop($this->onlineEnterpriseId, $this->onlineUserId);
  1668. $shopData = $objMShop->getShopInfo(['id' => $dbResult['shopId']]);
  1669. if (!$shopData->isSuccess()) {
  1670. return ResultWrapper::fail($shopData->getData(),$shopData->getErrorCode());
  1671. } else {
  1672. $shopData = $shopData->getData();
  1673. }
  1674. $dbResult['shopAddress'] = isset($shopData['area']) ? $shopData['area'] : [];
  1675. $dbResult['shopMobile'] = isset($shopData['mobile']) ? $shopData['mobile'] : '';
  1676. $dbResult['shopDescribe'] = isset($shopData['describe']) ? $shopData['describe'] : '';
  1677. $dbResult['partnerPhone'] = isset($shopData['mobile']) ? $shopData['mobile'] : '';//合伙人联系电弧
  1678. $objMAccount = new MAccount($this->onlineEnterpriseId,$this->onlineUserId);
  1679. $accountName = '';
  1680. if ($dbResult['payType'] == StatusCode::$payType['wxPay'] || $dbResult['payType'] == StatusCode::$payType['aliPay']){
  1681. $accountResult = $objMAccount->getDefaultAccount($dbResult['payType']);
  1682. if (!$accountResult->isSuccess()){
  1683. return ResultWrapper::fail($accountResult->getData(),$accountResult->getErrorCode());
  1684. }
  1685. $account = $accountResult->getData();
  1686. $accountName = isset($account['name']) ? $account['name'] : '';
  1687. }else{
  1688. $account = isset($dbResult['accountList']) ? array_shift($dbResult['accountList']) : [];
  1689. $accountName = isset($account['accountName']) ? $account['accountName'] : '';
  1690. }
  1691. $dbResult['accountName'] = $accountName;//收款账户
  1692. $pbjMPrintNum = new MPrintNum($this->onlineEnterpriseId);
  1693. $dbResult['printingNum'] = $pbjMPrintNum->getObjectPrintNum($dbResult['no'], $dbResult['orderType']);
  1694. return ResultWrapper::success($dbResult);
  1695. }
  1696. /**
  1697. * 检索导出(ES)
  1698. *
  1699. * @param $dsl
  1700. * @return ResultWrapper
  1701. * @throws \Exception
  1702. */
  1703. private function exportSearch($dsl)
  1704. {
  1705. $result = $this->objDOrder->getScrollSearchQueryDsl($dsl);
  1706. if (isset($result['status']) && $result['status'] == 400) {
  1707. return ResultWrapper::fail('获取数据失败' . $result['error']['reason'], ErrorCode::$apiNotResult);
  1708. }
  1709. if (!isset($result['hits']) && $result['hits']['total'] == 0) {
  1710. return ResultWrapper::fail('导出数据为空' . $result['error']['reason'], ErrorCode::$apiNotResult);
  1711. }
  1712. $dbResult = $result['hits']['hits'];
  1713. $list = [];
  1714. foreach ($dbResult as $key => &$value) {
  1715. $data = [];
  1716. $data = $value['_source'];
  1717. $list[] = $data;
  1718. }
  1719. self::exportOrder($list, 'es');
  1720. }
  1721. /**
  1722. * 导出方法
  1723. *
  1724. * @param $allOrderData
  1725. */
  1726. private static function export($allOrderData)
  1727. {
  1728. //导出到本地
  1729. header("Content-type:application/vnd.ms-excel");
  1730. header("Content-Disposition:filename=订单记录.csv");
  1731. header('Cache-Control: max-age=0');
  1732. $fp = fopen('php://output', 'a');
  1733. $head = ['ID', '订单编号', '下单时间', '客户名称', '收货人', '业务员', '联系电话', '订单金额', '订单状态', '收款状态', '配送方式', '订单来源', '订单审核']; //定义标题
  1734. foreach ($head as $i => $v) {
  1735. $head[$i] = mb_convert_encoding($v, 'GBK', 'utf-8'); //将中文标题转换编码,否则乱码
  1736. }
  1737. fputcsv($fp, $head);
  1738. $limit = 10000;
  1739. $num = 0;//计数器
  1740. foreach ($allOrderData as $v) {
  1741. //循环数据
  1742. $num++;
  1743. if ($num == $limit) {
  1744. ob_flush();//释放内存
  1745. flush();
  1746. }
  1747. $rows['id'] = $v['id'];
  1748. $rows['no'] = $v['no'];
  1749. $rows['createTime'] = date('Y-m-d H:i:s', $v['createTime']);
  1750. $rows['customerName'] = $v['customerName'];
  1751. $rows['realName'] = $v['realName'];
  1752. $rows['salesManName'] = $v['salesManName'];
  1753. $rows['mobile'] = $v['mobile'];
  1754. $rows['payAmount'] = $v['payAmount'];
  1755. $rows['orderStatus'] = StatusCode::$orderStatus[$v['orderStatus']];
  1756. $rows['payStatus'] = StatusCode::$standard == $v['payStatus'] ? '已支付' : '未支付';
  1757. $rows['deliveryType'] = ($v['deliveryType'] != StatusCode::$deliveryType['goodsDelivery'] && $v['deliveryType'] != StatusCode::$deliveryType['selfMention']) ? '' : StatusCode::$deliveryType[$v['deliveryType']];
  1758. $rows['source'] = StatusCode::$source[$v['source']];
  1759. $rows['auditStatus'] = StatusCode::$auditStatus[$v['auditStatus']];
  1760. foreach ($rows as $kk => $vv) {
  1761. $rs[$kk] = mb_convert_encoding($vv, 'GBK', 'utf-8'); //转译编码
  1762. }
  1763. fputcsv($fp, $rs);
  1764. $rows = [];
  1765. }
  1766. exit;
  1767. }
  1768. /**
  1769. * 导出列表(数据库)
  1770. *
  1771. * @param string $sql
  1772. * @return ResultWrapper
  1773. * @throws \Exception
  1774. */
  1775. public function exportAllOrder(string $sql)
  1776. {
  1777. $objDOrderIndex = new DOrderIndex();
  1778. $dbResult = $objDOrderIndex->query($sql);
  1779. if ($dbResult === false) {
  1780. return ResultWrapper::fail($objDOrderIndex->error(), ErrorCode::$dberror);
  1781. }
  1782. $allOrderData = [];
  1783. $allGroupData = [];
  1784. foreach ($dbResult as $key => $val) {
  1785. $tableNum = (int)ceil($val['userCenterId'] / $this->cutTable);
  1786. //这里感觉没有必要使用对主索引表的订单id进行分组,可以通过条件直接查询表下的数据
  1787. $allGroupData[$tableNum][] = $val['id'];
  1788. }
  1789. $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';
  1790. foreach ($allGroupData as $k => $orderId) {
  1791. $this->objDOrder->setTable('qianniao_order_' . $this->onlineEnterpriseId . '_' . $k);
  1792. $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';
  1793. $dbResult = $this->objDOrder->query($sql);
  1794. if ($dbResult === false) {
  1795. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  1796. }
  1797. $allOrderData = array_merge($dbResult, $allOrderData);
  1798. }
  1799. self::export($allOrderData);
  1800. }
  1801. /**
  1802. * Doc: (des="订单导出,构建查询数据")
  1803. * User: XMing
  1804. * Date: 2020/8/22
  1805. * Time: 10:25 上午
  1806. * @param array|string $data
  1807. * @param string $field
  1808. * @return ResultWrapper
  1809. */
  1810. private function buildSelectGroupDataByCondition($data, string $field)
  1811. {
  1812. switch ($field) {
  1813. case 'db':
  1814. $result = self::getAllOrderIdsBySql($data);
  1815. break;
  1816. case 'es':
  1817. $result = self::getAllOrderIdsBySearchResult($data);
  1818. break;
  1819. }
  1820. if (!$result->isSuccess()) {
  1821. return ResultWrapper::fail($result->getData(), $result->getErrorCode());
  1822. }
  1823. return ResultWrapper::success($result->getData());
  1824. }
  1825. /**
  1826. * Doc: (des="将es检索数据,进行数据分组转化为统一格式")
  1827. * [[表后缀]=>[订单id,]]
  1828. * User: XMing
  1829. * Date: 2020/8/22
  1830. * Time: 10:15 上午
  1831. * @param array $data
  1832. * @return ResultWrapper
  1833. */
  1834. private function getAllOrderIdsBySearchResult(array $data)
  1835. {
  1836. if (empty($data)) {
  1837. return ResultWrapper::success([]);
  1838. }
  1839. $groupMapRes = self::buildGroupMapByArray((array)$data);
  1840. if (!$groupMapRes->isSuccess()) {
  1841. return ResultWrapper::fail($groupMapRes->getData(), $groupMapRes->getErrorCode());
  1842. }
  1843. return ResultWrapper::success($groupMapRes->getData());
  1844. }
  1845. /**
  1846. * Doc: (des="")
  1847. * User: XMing
  1848. * Date: 2020/8/22
  1849. * Time: 10:18 上午
  1850. * @param array $data
  1851. * @return ResultWrapper
  1852. */
  1853. private function buildGroupMapByArray(array $data)
  1854. {
  1855. if (empty($data)) {
  1856. return ResultWrapper::success([]);
  1857. }
  1858. $allGroupMap = [];
  1859. //对所有数据进行分组,[[表后缀]=>[订单id,]]
  1860. foreach ($data as $key => $val) {
  1861. $tableNum = (int)ceil($val['userCenterId'] / $this->cutTable);
  1862. //这里感觉没有必要使用对主索引表的订单id进行分组,可以通过条件直接查询表下的数据
  1863. $allGroupMap[$tableNum][] = $val['id'];
  1864. }
  1865. return ResultWrapper::success($allGroupMap);
  1866. }
  1867. /**
  1868. * Doc: (des="通过sql,进行数据分组转化为统一格式")
  1869. * [[表后缀]=>[订单id,]]
  1870. * User: XMing
  1871. * Date: 2020/8/22
  1872. * Time: 9:55 上午
  1873. * @param string $sql
  1874. * @return ResultWrapper
  1875. */
  1876. private function getAllOrderIdsBySql(string $sql)
  1877. {
  1878. if (empty($sql)) {
  1879. return ResultWrapper::success([]);
  1880. }
  1881. $list = $this->objDOrderIndex->exportQuery($sql);
  1882. if ($list === false) {
  1883. return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
  1884. }
  1885. $list = self::getGeneratorData($list);
  1886. if (empty($list)) {
  1887. return ResultWrapper::success([]);
  1888. }
  1889. $groupMapRes = self::buildGroupMapByArray((array)$list);
  1890. if (!$groupMapRes->isSuccess()) {
  1891. return ResultWrapper::fail($groupMapRes->getData(), $groupMapRes->getErrorCode());
  1892. }
  1893. return ResultWrapper::success($groupMapRes->getData());
  1894. }
  1895. /**
  1896. * Doc: (des="获取export查询方法返回的数据集合")
  1897. * User: XMing
  1898. * Date: 2020/8/22
  1899. * Time: 11:42 上午
  1900. * @param $object
  1901. * @return array
  1902. */
  1903. private static function getGeneratorData($object)
  1904. {
  1905. $arrayList = [];
  1906. foreach ($object as $value) {
  1907. $arrayList[] = $value;
  1908. }
  1909. return $arrayList;
  1910. }
  1911. /**
  1912. * Doc: (des="格式化导出数据,统一根据订单id格式化数据")
  1913. * User: XMing
  1914. * Date: 2020/8/22
  1915. * Time: 9:44 上午
  1916. * @param array|string $data
  1917. * @param string $source
  1918. * @return ResultWrapper
  1919. * @throws \Exception
  1920. */
  1921. private function exportOrder($data, string $source)
  1922. {
  1923. if (empty($data)) {
  1924. return ResultWrapper::success([]);
  1925. }
  1926. $groupMapRes = self::buildSelectGroupDataByCondition($data, $source);
  1927. if (!$groupMapRes->isSuccess()) {
  1928. return ResultWrapper::fail($groupMapRes->getData(), $groupMapRes->getErrorCode());
  1929. }
  1930. $groupMap = $groupMapRes->getData();
  1931. if (empty($groupMap)) {
  1932. return ResultWrapper::fail('导出数据构建失败', ErrorCode::$paramError);
  1933. }
  1934. //查询需要导出的数据
  1935. $orderFields = '*';
  1936. $orderReceiveFields = '*';
  1937. $orderGoodsFields = '*';
  1938. $allOrderData = [];//订单集
  1939. $allOrderReceiveData = [];//订单收货地址集
  1940. $allOrderGoodsData = [];//订单商品信息
  1941. foreach ($groupMap as $k => $orderIds) {
  1942. //订单表
  1943. $this->objDOrder->setTable('qianniao_order_' . $this->onlineEnterpriseId . '_' . $k);
  1944. $orderResult = $this->objDOrder->exportSelect(['id' => $orderIds], $orderFields, 'createTime desc');//查询订单
  1945. if ($orderResult === false) {
  1946. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  1947. }
  1948. $orderResult = self::getGeneratorData($orderResult);
  1949. //订单收货表
  1950. $this->objDOrderReceive->setTable('qianniao_order_receive_' . $this->onlineEnterpriseId . '_' . $k);
  1951. $orderReceiveResult = $this->objDOrderReceive->exportSelect(['orderId' => $orderIds], $orderReceiveFields, 'createTime desc');//订单收货
  1952. if ($orderReceiveResult === false) {
  1953. return ResultWrapper::fail($this->objDOrderReceive->error(), ErrorCode::$dberror);
  1954. }
  1955. $orderReceiveResult = self::getGeneratorData($orderReceiveResult);
  1956. //订单商品表
  1957. $this->objDOrderGoods->setTable('qianniao_order_goods_' . $this->onlineEnterpriseId . '_' . $k);
  1958. $orderGoodsResult = $this->objDOrderGoods->exportSelect(['orderId' => $orderIds], $orderGoodsFields, 'createTime desc');
  1959. if ($orderGoodsResult === false) {
  1960. return ResultWrapper::fail($this->objDOrderGoods->error(), ErrorCode::$dberror);
  1961. }
  1962. $orderGoodsResult = self::getGeneratorData($orderGoodsResult);
  1963. //对数据进行合并
  1964. $allOrderData = array_merge($orderResult, $allOrderData);
  1965. $allOrderReceiveData = array_merge($orderReceiveResult, $allOrderReceiveData);
  1966. $allOrderGoodsData = array_merge($orderGoodsResult, $allOrderGoodsData);
  1967. }
  1968. $formatResult = self::formatManageOrderList($allOrderData, $allOrderReceiveData, $allOrderGoodsData);
  1969. if (!$formatResult->isSuccess()) {
  1970. return ResultWrapper::fail($formatResult->getData(), $formatResult->getErrorCode());
  1971. }
  1972. $exportData = $formatResult->getData();
  1973. if (empty($exportData)) {
  1974. return ResultWrapper::fail('构建导出数据为空', ErrorCode::$paramError);
  1975. }
  1976. //将数据导出
  1977. self::exportCsv($exportData);
  1978. }
  1979. /**
  1980. * Doc: (des="")
  1981. * User: XMing
  1982. * Date: 2020/8/22
  1983. * Time: 2:24 下午
  1984. * @param array $area
  1985. * @param string $address
  1986. * @return string
  1987. */
  1988. private static function createAddress($area, $address)
  1989. {
  1990. $str = '';
  1991. if (isset($area['provinceName']) && !empty($area['provinceName'])) {
  1992. $str .= $area['provinceName'];
  1993. }
  1994. if (isset($area['cityName']) && !empty($area['cityName'])) {
  1995. $str .= $area['cityName'];
  1996. }
  1997. if (isset($area['districtName']) && !empty($area['districtName'])) {
  1998. $str .= $area['districtName'];
  1999. }
  2000. $str .= $address;
  2001. return $str;
  2002. }
  2003. /**
  2004. * Doc: (des="生成规格名字")
  2005. * User: XMing
  2006. * Date: 2020/8/22
  2007. * Time: 2:47 下午
  2008. * @param array $specGroup
  2009. * @return string
  2010. */
  2011. private static function createSpecName($specGroup)
  2012. {
  2013. if(empty($specGroup)){
  2014. return "无";
  2015. }
  2016. $str = '';
  2017. foreach ($specGroup as $value) {
  2018. empty($str) && $str .= ' ';
  2019. $str .= $value['specName'] . ':';
  2020. $str .= $value['specValueName'];
  2021. }
  2022. return $str;
  2023. }
  2024. /**
  2025. * Doc: (des="将数据导出到表格")
  2026. * User: XMing
  2027. * Date: 2020/8/22
  2028. * Time: 11:09 上午
  2029. * @param array $data
  2030. */
  2031. private function exportCsv(array $data)
  2032. {
  2033. //导出到本地
  2034. header("Content-type:application/vnd.ms-excel");
  2035. header("Content-Disposition:filename=订单记录.csv");
  2036. header('Cache-Control: max-age=0');
  2037. $fp = fopen('php://output', 'a');
  2038. $head = ['ID', '订单编号', '订单金额', '优惠金额', '付款金额', '订单状态', '支付方式', '付款状态','配送方式','订单来源','审核状态','下单时间','客户名称','收货人','收货人电话','收货人地址','所属店铺', '业务员','件数','商品编码','商品名称','单位','属性','数量','销售单价(元)','销售总价'];//定义标题
  2039. foreach ($head as $i => $v) {
  2040. $head[$i] = mb_convert_encoding($v, 'GBK', 'utf-8'); //将中文标题转换编码,否则乱码
  2041. }
  2042. fputcsv($fp, $head);
  2043. $limit = 10000;
  2044. $num = 0;//计数器
  2045. $rows = [];
  2046. foreach ($data as $v) {
  2047. //循环数据
  2048. $num++;
  2049. if ($num == $limit) {
  2050. ob_flush();//释放内存
  2051. flush();
  2052. }
  2053. foreach ($v['goodsData'] as $index => $item) {
  2054. self::buildExportData($rows, $v, $item, $index);
  2055. foreach ($rows as $kk => $vv) {
  2056. $rs[$kk] = mb_convert_encoding($vv, 'GBK', 'utf-8'); //转译编码
  2057. }
  2058. fputcsv($fp, $rs);
  2059. $rows = [];
  2060. }
  2061. }
  2062. exit;
  2063. }
  2064. /**
  2065. * Doc: (des="")
  2066. * User: XMing
  2067. * Date: 2020/8/22
  2068. * Time: 3:28 下午
  2069. * @param array $rows
  2070. * @param array $v
  2071. * @param array $item
  2072. * @param int $index
  2073. */
  2074. private static function buildExportData(&$rows, array $v, array $item, int $index)
  2075. {
  2076. $rows['id'] = '';
  2077. $rows['no'] = '';
  2078. $rows['totalMoney'] = '';
  2079. $rows['subMoney'] = '';
  2080. $rows['payMoney'] = '';
  2081. $rows['orderMsg'] = '';
  2082. $rows['payTypeMsg'] = '';
  2083. $rows['payMsg'] = '';
  2084. $rows['deliveryMsg'] = '';
  2085. $rows['sourceMsg'] = '';
  2086. $rows['auditMsg'] = '';
  2087. $rows['createTime'] = '';
  2088. $rows['customerName'] = '';
  2089. $rows['receiveName'] = '';
  2090. $rows['receiveMobile'] = '';
  2091. $rows['receiveAddress'] = '';
  2092. $rows['shopName'] = '';
  2093. $rows['salesManName'] = '';
  2094. $rows['otherNum'] = '';
  2095. $rows['id'] = $v['id'];
  2096. $rows['no'] = $v['no'];
  2097. $rows['totalMoney'] = $v['totalMoney'];
  2098. $rows['subMoney'] = bcsub($v['payAmount'], $v['totalMoney'], 2);
  2099. $rows['payMoney'] = $v['payAmount'];
  2100. $rows['orderMsg'] = $v['orderMsg'];
  2101. $rows['payTypeMsg'] = $v['payTypeMsg'];
  2102. $rows['payMsg'] = $v['payMsg'];
  2103. $rows['deliveryMsg'] = $v['deliveryMsg'];
  2104. $rows['sourceMsg'] = $v['sourceMsg'];
  2105. $rows['auditMsg'] = $v['auditMsg'];
  2106. $rows['createTime'] = date('Y-m-d H:i:s', $v['createTime']);
  2107. $rows['customerName'] = $v['customerName'];
  2108. $rows['receiveName'] = $v['receiveData']['realName'];
  2109. $rows['receiveMobile'] = $v['receiveData']['mobile'];
  2110. $rows['receiveAddress'] = self::createAddress($v['receiveData']['area'], $v['receiveData']['address']);
  2111. $rows['shopName'] = $v['shopName'];
  2112. $rows['salesManName'] = $v['salesManName'];
  2113. $rows['goodsCode'] = $item['goodsCode'];
  2114. $rows['goodsName'] = $item['goodsName'];
  2115. $rows['unitName'] = $item['unitName'];
  2116. $rows['specName'] = self::createSpecName((isset($item['specGroup']) && !empty($item['specGroup'])) ? json_decode($item['specGroup'], true) : []);
  2117. $rows['buyNum'] = $item['buyNum'];
  2118. $rows['unitPrice'] = $item['price'];
  2119. $rows['totalPrice'] = $item['totalMoney'];
  2120. $rows['otherNum'] = $item['otherNum'];
  2121. }
  2122. /**
  2123. * 获取所有订单
  2124. *
  2125. * @param $selectParams
  2126. * @param $search
  2127. * @param bool $is_export
  2128. * @return ResultWrapper
  2129. * @throws \Exception
  2130. * @waitAudit:等待审核 orderStatus != 6 auditStatus = 1
  2131. * @waitOutStock:待出库 orderStatus != 6 auditPass = 2
  2132. * @hasOutStock:已出库 orderStatus = 4 auditPass = 2
  2133. * @finish:已完成 orderStatus = 5 auditPass 2
  2134. * @close:已关闭 orderStatus = 6
  2135. *
  2136. * 新订单列表 {"page":1,"pageSize":10,"search":{"auditStatus":1}}
  2137. * 订单查询 {"page":1,"pageSize":10,"search":{"auditStatus":2}} 订单查询:此页面只展示新订单审核后的订单,订单状态为【待出库】,订单出库后,页面会显示出【确认收货】的按钮,订单在出库管理进行出库后,订单状态为【已出库】,客户或后台操作【确认收货】后,订单状态为【已完成】。
  2138. * 自提订单 {"page":1,"pageSize":10,"search":{"deliveryType":2}}
  2139. * 取消订单 {"page":1,"pageSize":10,"search":{"orderStatus":6}}
  2140. *
  2141. */
  2142. public function getAllOrder($selectParams, $search, $is_export = false)
  2143. {
  2144. $objDOrderIndex = new DOrderIndex();
  2145. $selectParams = array_merge($selectParams, $search);
  2146. // 组装检索sql语句
  2147. $buildSql = self::setOrderStatusSqlAttr($selectParams);
  2148. $sql = $buildSql['sql'];
  2149. if ($is_export === true) self::exportOrder($sql, 'db');//导出数据
  2150. $total = $objDOrderIndex->query($buildSql['countSql']);
  2151. if (isset($selectParams['limit']) && isset($selectParams['offset'])) {
  2152. $sql .= ' limit ' . $selectParams['offset'] . ',' . $selectParams['limit'];
  2153. }
  2154. $dbResult = $objDOrderIndex->query($sql);
  2155. if ($dbResult === false) {
  2156. return ResultWrapper::fail($objDOrderIndex->error(), ErrorCode::$dberror);
  2157. }
  2158. $allOrderData = [];//订单集
  2159. $allOrderReceiveData = [];//订单收货地址集
  2160. $allGroupData = [];
  2161. if (!empty($dbResult)) {
  2162. foreach ($dbResult as $key => $val) {
  2163. $tableNum = ceil($val['userCenterId'] / $this->cutTable);
  2164. $allGroupData[$tableNum][] = $val['id'];
  2165. }
  2166. foreach ($allGroupData as $k => $orderId) {
  2167. $this->objDOrder->setTable('qianniao_order_' . $this->onlineEnterpriseId . '_' . $k);
  2168. $dbResult = $this->objDOrder->select(['id' => $orderId], '*', 'createTime desc');//查询订单
  2169. if ($dbResult === false) {
  2170. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  2171. }
  2172. //物流信息展示
  2173. if( !empty($dbResult['logisticsData']) ){
  2174. json_decode($dbResult['logisticsData'],true);
  2175. }
  2176. $this->objDOrderReceive->setTable('qianniao_order_receive_' . $this->onlineEnterpriseId . '_' . $k);
  2177. $orderReceiveResult = $this->objDOrderReceive->select(['orderId' => $orderId], '*', 'createTime desc');//订单收货
  2178. if ($orderReceiveResult === false) {
  2179. return ResultWrapper::fail($this->objDOrderReceive->error(), ErrorCode::$dberror);
  2180. }
  2181. $allOrderData = array_merge($dbResult, $allOrderData);//订单集
  2182. $allOrderReceiveData = array_merge($orderReceiveResult, $allOrderReceiveData);//订单收货地址集
  2183. }
  2184. }
  2185. // 格式化后台订单列表
  2186. $formatResult = self::formatManageOrderList($allOrderData, $allOrderReceiveData);
  2187. if (!$formatResult->isSuccess()) {
  2188. return ResultWrapper::fail($formatResult->getData(), $formatResult->getErrorCode());
  2189. }
  2190. $return = [
  2191. 'data' => $formatResult->getData(),
  2192. 'total' => isset($total[0]['total']) ? $total[0]['total'] : 0,
  2193. ];
  2194. return ResultWrapper::success($return);
  2195. }
  2196. /**
  2197. * Doc: (des="获取检索订单数据")
  2198. *订单列表搜索商品名称、商品编码、收货人、电话
  2199. * @waitAudit:等待审核 orderStatus != 6 auditStatus = 1
  2200. * @waitOutStock:待出库 orderStatus != 6 auditPass = 2
  2201. * @hasOutStock:已出库 orderStatus = 4 auditPass = 2
  2202. * @finish:已完成 orderStatus = 5 auditPass 2
  2203. * @close:已关闭 orderStatus = 6
  2204. * @param $export
  2205. * @param $selectParams
  2206. */
  2207. public function keywordSearch($selectParams,$export = '')
  2208. {
  2209. // 组装检索sql
  2210. $whereSql = '';
  2211. if(!empty($selectParams['keywordType']) && !empty($selectParams['keyword'])){
  2212. $whereSql = self::assemblySql($selectParams['keywordType'],$selectParams['keyword']);
  2213. }
  2214. $orderTab ='qianniao_order_'.$this->onlineEnterpriseId.'_'.'1';
  2215. $orderGoodsTab ='qianniao_order_goods_'.$this->onlineEnterpriseId.'_'.'1';
  2216. $orderReceive ='qianniao_order_receive_'.$this->onlineEnterpriseId.'_'.'1';
  2217. // 初始化表
  2218. $this->objDOrder->setTable($orderTab);
  2219. $this->objDOrder->setTable($orderGoodsTab);
  2220. $this->objDOrder->setTable($orderReceive);
  2221. $condition = '';
  2222. $limit = '';
  2223. if(!$export){
  2224. if (isset($selectParams['limit']) && isset($selectParams['offset'])) {
  2225. $limit .= ' limit ' . $selectParams['offset'] . ',' . $selectParams['limit'];
  2226. }
  2227. }
  2228. // 时间筛选
  2229. if (isset($selectParams['startTime']) && !empty($selectParams['startTime'])){
  2230. $condition .= ' AND o.createTime BETWEEN '.$selectParams['startTime'].' AND '.$selectParams['endTime'];
  2231. }
  2232. //userCenterId
  2233. if (isset($selectParams['userCenterId']) && !empty($selectParams['userCenterId'])) {
  2234. $condition .= ' and o.userCenterId = ' . $selectParams['userCenterId'];
  2235. }
  2236. //customerId
  2237. if (isset($selectParams['customerId']) && !empty($selectParams['customerId'])) {
  2238. $condition .= ' and o.customerId = ' . $selectParams['customerId'];
  2239. }
  2240. //shopId
  2241. if (isset($selectParams['shopId']) && !empty($selectParams['shopId'])) {
  2242. $condition .= ' and o.shopId = ' . $selectParams['shopId'];
  2243. }
  2244. // 付款状态 支付状态 默认4 未支付 5已支付
  2245. if (isset($selectParams['payStatus']) && !empty($selectParams['payStatus'])) {
  2246. $condition .= ' and o.payStatus = ' . $selectParams['payStatus'];
  2247. }
  2248. //支付方式
  2249. if (isset($selectParams['payType']) && !empty($selectParams['payType'])) {
  2250. $condition .= ' and find_in_set('.$selectParams['payType'].',o.payType) ';
  2251. }
  2252. // 客户类型
  2253. if (isset($selectParams['customerType']) && !empty($selectParams['customerType'])){
  2254. $condition .= ' AND o.customerType = '.$selectParams['customerType'];
  2255. }
  2256. // 订单来源 订单来源 默认1 ios 2android 3小程序 4后台创建
  2257. if (isset($selectParams['source']) && !empty($selectParams['source'])){
  2258. $condition .= ' AND o.source = '.$selectParams['source'];
  2259. }
  2260. //出库状态
  2261. if (isset($selectParams['outStatus']) && !empty($selectParams['outStatus'])) {
  2262. $condition .= ' and o.outStatus = ' . $selectParams['outStatus'];
  2263. }
  2264. //退货状态
  2265. if (isset($selectParams['returnStatus']) && !empty($selectParams['returnStatus'])) {
  2266. if (is_array($selectParams['returnStatus'])) {
  2267. $returnStatusStr = implode(',', $selectParams['returnStatus']);
  2268. $condition .= ' and o.returnStatus in(' . $returnStatusStr . ') ';
  2269. } else {
  2270. $condition .= ' and o.returnStatus = ' . $selectParams['returnStatus'];
  2271. }
  2272. }
  2273. //订单状态
  2274. if (isset($selectParams['state']) && !empty($selectParams['state'])) {
  2275. $condition = self::orderStateSql($condition, $selectParams['state']);
  2276. }
  2277. if($export){
  2278. $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 ';
  2279. $orderGoodsData = $this->objDOrder->exportQuery($sql);
  2280. if ($orderGoodsData === false) {
  2281. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  2282. }
  2283. $result = self::exportOrderList($orderGoodsData);
  2284. exit;
  2285. }
  2286. $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;
  2287. $dbResult = $this->objDOrder->query($sql);
  2288. if ($dbResult === false) {
  2289. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  2290. }
  2291. // 格式化后台订单列表
  2292. $formatResult = self::formatManageOrderList($dbResult,[]);
  2293. if (!$formatResult->isSuccess()) {
  2294. return ResultWrapper::fail($formatResult->getData(), $formatResult->getErrorCode());
  2295. }
  2296. $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;
  2297. $total = $this->objDOrder->query($sqlTotal);
  2298. if ($total === false) {
  2299. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  2300. }
  2301. $return = [
  2302. 'data' => $formatResult->getData(),
  2303. 'total' => isset($total[0]['total']) ? $total[0]['total'] : 0,
  2304. ];
  2305. return ResultWrapper::success($return);
  2306. }
  2307. /**
  2308. * 获取检索订单数据导出
  2309. * @param $orderListData
  2310. * @return ResultWrapper
  2311. */
  2312. public function exportOrderList($orderListData)
  2313. {
  2314. //导出到本地
  2315. header("Content-type:application/vnd.ms-excel");
  2316. header("Content-Disposition:filename=订单管理.csv");
  2317. header('Cache-Control: max-age=0');
  2318. $fp = fopen('php://output', 'a');
  2319. $head = ['ID', '订单编号', '订单金额', '订单金额', '付款金额', '订单状态', '支付方式', '付款状态','配送方式','订单来源','审核状态','下单时间','客户名称','收货人','收货人电话','收货人地址','所属店铺', '业务员','件数','商品编码','商品名称','单位','属性','数量','销售单价(元)','优惠金额','销售总价'];//定义标题
  2320. foreach ($head as $i => $v) {
  2321. $head[$i] = mb_convert_encoding($v, 'GBK', 'utf-8'); //将中文标题转换编码,否则乱码
  2322. }
  2323. fputcsv($fp, $head);
  2324. $limit = 10000;
  2325. $num = 0;//计数器
  2326. foreach ($orderListData as $value) {//循环数据
  2327. $orderReceiveData[]= [
  2328. 'orderId' => $value['id'],
  2329. 'provinceCode' => $value['provinceCode'],
  2330. 'cityCode' => $value['cityCode'],
  2331. 'districtCode' => $value['districtCode'],
  2332. 'allAddress' => $value['allAddress']
  2333. ];
  2334. // 格式化后台订单列表
  2335. $fromatValue = self::formatManageOrderList([$value],$orderReceiveData);
  2336. if (!$fromatValue->isSuccess()) {
  2337. echo($fromatValue->getData());
  2338. exit();
  2339. }
  2340. $fromatValue = array_pop($fromatValue->getData());
  2341. $value = array_merge($value, $fromatValue);
  2342. $num++;
  2343. if ($num == $limit) {
  2344. ob_flush();//释放内存
  2345. flush();
  2346. }
  2347. $rows['id'] = isset($value['id']) ? $value['id'] : null; // ID
  2348. $rows['no'] = isset($value['no']) ? $value['no'] : null; // 订单编号
  2349. $rows['totalMoney'] = isset($value['totalMoney']) ? $value['totalMoney'] : null; // 订单金额
  2350. $rows['subMoney'] = isset($value['payAmount']) && isset($value['totalMoney']) ? bcsub($value['payAmount'], $value['totalMoney'], 2): 0; // 订单金额
  2351. $rows['payAmount'] = isset($value['payAmount']) ? $value['payAmount'] : null; // 付款金额
  2352. $rows['orderMsg'] = isset($value['orderMsg']) ? $value['orderMsg'] : null; // 订单状态
  2353. $rows['payTypeMsg'] = isset($value['payTypeMsg']) ? $value['payTypeMsg'] : null; // 支付方式
  2354. $rows['payMsg'] = isset($value['payMsg']) ? $value['payMsg'] : null; // 付款状态
  2355. $rows['deliveryMsg'] = isset($value['deliveryMsg']) ? $value['deliveryMsg'] : null; // 配送方式
  2356. $rows['sourceMsg'] = isset($value['sourceMsg']) ? $value['sourceMsg'] : null; // 订单来源
  2357. $rows['auditMsg'] = isset($value['auditMsg']) ? $value['auditMsg'] : null; // 审核状态
  2358. $rows['createTime'] = isset( $value['createTime']) ? date('Y-m-d H:i:s', $value['createTime']) : null; // 下单时间
  2359. $rows['customerName'] = isset($value['customerName']) ? $value['customerName'] : null; // 客户名称
  2360. $rows['receiveName'] = isset($value['realName']) ? $value['realName']: null; // 收货人
  2361. $rows['receiveMobile'] = isset($value['mobile']) ? $value['mobile'] : null; // 收货人电话
  2362. $rows['receiveAddress'] = isset($value['receiveData']['allAddress']) ? $value['receiveData']['allAddress'] : null;// '收货人地址'
  2363. $rows['shopName'] = isset($value['shopName']) ? $value['shopName'] : null; // ,'所属店铺',
  2364. $rows['salesManName'] = isset($value['salesManName']) ? $value['salesManName'] : null; // '业务员'
  2365. $rows['otherNum'] = getArrayItem($value, 'otherNum', 0); //件数
  2366. $rows['goodsCode'] = getArrayItem($value, 'goodsCode'); // '商品编码'
  2367. $rows['goodsName'] = getArrayItem($value, 'goodsName'); // '商品名称
  2368. $rows['unitName'] = getArrayItem($value, 'unitName'); // 单位
  2369. $rows['specName'] = self::createSpecName((isset($value['specGroup']) && !empty($value['specGroup'])) ? json_decode($value['specGroup'], true) : []);
  2370. $rows['buyNum'] = getArrayItem($value, 'buyNum', 0);
  2371. $rows['unitPrice'] = getArrayItem($value, 'price', 0);
  2372. $rows['preferential'] = getArrayItem($value, 'preferential', 0);
  2373. $rows['totalPrice'] = getArrayItem($value, 'totalMoney', 0); // '销售单价(元)'
  2374. foreach ($rows as $kk => $vv) {
  2375. $rs[$kk] = mb_convert_encoding($vv, 'GBK', 'utf-8'); //转译编码
  2376. }
  2377. fputcsv($fp, $rs);
  2378. $rows = [];
  2379. }
  2380. }
  2381. /**
  2382. * 根据订单列表 keywordType 拼装sql
  2383. * @param $keywordType
  2384. * @param $keyword
  2385. */
  2386. public function assemblySql($keywordType,$keyword)
  2387. {
  2388. $whereSql = '';
  2389. switch ($keywordType){
  2390. case 1: // 单据编号 order
  2391. if(strpos($keyword,StatusCode::$noPrefix[1]) !== false){
  2392. $orderNo = explode('-',$keyword);
  2393. if(count($orderNo)==3){
  2394. $orderNo = $orderNo[1].'-'.$orderNo[2];
  2395. }elseif(count($orderNo)==2){
  2396. $orderNo = $orderNo[1];
  2397. }else{
  2398. $orderNo = $keyword;
  2399. }
  2400. $whereSql .= ' and o.no = "'.$orderNo.'"';
  2401. }else{
  2402. $whereSql .= ' and o.no = "'.$keyword.'"';
  2403. }
  2404. break;
  2405. case 2: // 自提码 order
  2406. $whereSql .= ' and o.verifyCode ="'.$keyword.'"';
  2407. break;
  2408. case 3: // 商品名称 order_goods
  2409. $whereSql .=' and g.goodsName LIKE "%' .$keyword. '%" ';
  2410. break;
  2411. case 4: // 商品编码 order_goods
  2412. $whereSql .=' and g.goodsCode ="'.$keyword.'"';
  2413. break;
  2414. case 5: // 收货人 order_receive
  2415. $whereSql .=' and r.realName LIKE "%' .$keyword. '%" ';
  2416. break;
  2417. case 6: // 电话 order_receive
  2418. $whereSql .=' and r.mobile ="'.$keyword.'"';
  2419. break;
  2420. case 7: // 业务员 order
  2421. $whereSql .=' and o.salesManName LIKE "%' .$keyword. '%" ';
  2422. break;
  2423. case 8: // 详细地址 order_receive
  2424. $whereSql .=' and r.address LIKE "%' .$keyword. '%" ';
  2425. }
  2426. return $whereSql;
  2427. }
  2428. /**
  2429. * Doc: (des="state标示多选sql处理")
  2430. *
  2431. */
  2432. private static function orderStateSql($sql, $states)
  2433. {
  2434. if (is_array($states)) {
  2435. if (in_array('all', $states)) {
  2436. return $sql;
  2437. }
  2438. foreach ($states as $index => $state) {
  2439. $sql .= $index == 0 ? ' and (' . self::orderstate($state) : ' or ' . self::orderstate($state);
  2440. }
  2441. $sql .= ') ';
  2442. } else {
  2443. if ($states == 'all') {
  2444. return $sql;
  2445. }
  2446. $stateSql = self::orderstate($states);
  2447. if (!empty($stateSql)) {
  2448. $sql .= ' and ' . self::orderstate($states);
  2449. }
  2450. }
  2451. return $sql;
  2452. }
  2453. /**
  2454. * Doc: (des="state标示对应sql")
  2455. */
  2456. private static function orderstate($state)
  2457. {
  2458. $sql = '';
  2459. switch ($state) {
  2460. case 'waitAudit'://待审核
  2461. $sql .= ' (o.auditStatus = ' . StatusCode::$auditStatus['auditing'] . ' and o.orderStatus != ' . StatusCode::$orderStatus['close'] . ')';
  2462. break;
  2463. case 'waitOutStock'://待出库
  2464. $sql .= ' (o.auditStatus = ' . StatusCode::$auditStatus['auditPass'] . ' and (o.orderStatus = ' . StatusCode::$orderStatus['waitPay'] . ' or orderStatus = ' . StatusCode::$orderStatus['waitDelivery'] . ')) ';
  2465. break;
  2466. case 'hasOutStock'://已出库
  2467. $sql .= ' (o.auditStatus = ' . StatusCode::$auditStatus['auditPass'] . ' and o.orderStatus = ' . StatusCode::$orderStatus['waitReceive'] . ')';
  2468. break;
  2469. case 'finish'://已完成
  2470. $sql .= ' (o.auditStatus = ' . StatusCode::$auditStatus['auditPass'] . ' and o.orderStatus = ' . StatusCode::$orderStatus['finish'] . ')';
  2471. break;
  2472. case 'close'://已关闭
  2473. $sql .= ' (o.orderStatus = ' . StatusCode::$orderStatus['close'] . ')';
  2474. break;
  2475. case 'all'://全部订单
  2476. break;
  2477. }
  2478. return $sql;
  2479. }
  2480. /**
  2481. * Doc: (des="格式化后台订单列表")
  2482. * User: XMing
  2483. * Date: 2020/7/11
  2484. * Time: 5:02 下午
  2485. * @param array $orderData
  2486. * @param array $orderReceiveData
  2487. * @param array $orderGoodsData
  2488. * @return ResultWrapper
  2489. */
  2490. public function formatManageOrderList(array $orderData, array $orderReceiveData, array $orderGoodsData = [])
  2491. {
  2492. $returnData = [];
  2493. if (empty($orderData)) {
  2494. return ResultWrapper::success($returnData);
  2495. }
  2496. $receiveMap = [];
  2497. if (!empty($orderReceiveData)) {
  2498. $orderReceiveData = self::formatSysArea($orderReceiveData);// 订单收货地址集渲染
  2499. foreach ($orderReceiveData as $key => &$item) {
  2500. $receiveMap[$item['orderId']] = [
  2501. 'customerId' => getArrayItem($item, 'customerId', 0),
  2502. 'address' => getArrayItem($item, 'address'),
  2503. 'allAddress' => $item['area']['provinceName'].$item['area']['cityName'].$item['area']['districtName'].getArrayItem($item, 'address'),
  2504. 'realName' => getArrayItem($item, 'realName'),
  2505. 'mobile' => getArrayItem($item, 'mobile'),
  2506. 'area' => getArrayItem($item, 'area', [])
  2507. ];
  2508. }
  2509. unset($item);
  2510. }
  2511. $orderData = self::formatOrderStatus($orderData); // 格式化订单状态
  2512. $goodsMap = [];
  2513. if (!empty($orderGoodsData)) {
  2514. foreach ($orderGoodsData as $key => $item) {
  2515. $goodsMap[$item['orderId']][] = $item;
  2516. }
  2517. }
  2518. unset($item);
  2519. // 映射下打印次数
  2520. $allOrderNos = [];
  2521. foreach ($orderData as $key => $value){
  2522. $allOrderNos[] = $value['no'];
  2523. }
  2524. $pbjMPrintNum = new MPrintNum($this->onlineEnterpriseId);
  2525. $printNumData = $pbjMPrintNum->getObjectPrintNumByNos($allOrderNos); // 批量获取打印次数
  2526. $orderNoBindPritNum = [];
  2527. if(!empty($printNumData)){
  2528. foreach ($printNumData as $key => $value){
  2529. $orderNoBindPritNum[$value['objectNo']] = $value['printNum'];
  2530. }
  2531. }
  2532. foreach ($orderData as $key => $datum) {
  2533. $returnData[$key] = [
  2534. 'id' => $datum['id'],
  2535. 'no' => self::formatSn($datum['no']),
  2536. 'shopId' => $datum['shopId'],
  2537. 'shopName' => isset($datum['shopName']) ? $datum['shopName'] : '',
  2538. 'customerId' => $datum['customerId'],
  2539. 'customerName' => $datum['customerName'],
  2540. 'userCenterId' => $datum['userCenterId'],
  2541. 'payAmount' => $datum['payAmount'],
  2542. 'retMoney' => $datum['retMoney'],
  2543. 'totalMoney' => $datum['totalMoney'],
  2544. 'payStatus' => $datum['payStatus'],
  2545. 'auditStatus' => $datum['auditStatus'],
  2546. 'returnStatus' => $datum['returnStatus'],
  2547. 'outStatus' => $datum['outStatus'],
  2548. 'deliveryType' => $datum['deliveryType'],
  2549. 'payType' => $datum['payType'],
  2550. 'salesManName' => empty($datum['salesManName']) ? '' : $datum['salesManName'],
  2551. 'salesman' => !isset($datum['salesman']) || is_null($datum['salesman']) ? '' : $datum['salesman'],
  2552. 'salesManId' => $datum['salesManId'],
  2553. 'createTime' => $datum['createTime'],
  2554. 'source' => $datum['source'],
  2555. 'orderStatus' => $datum['orderStatus'],
  2556. 'receiveData' => isset($receiveMap[$datum['id']]) ? $receiveMap[$datum['id']] : [],
  2557. 'orderMsg' => $datum['orderMsg'],
  2558. 'payMsg' => $datum['payMsg'],
  2559. 'deliveryMsg' => $datum['deliveryMsg'],
  2560. 'payTypeMsg' => $datum['payTypeMsg'],
  2561. 'sourceMsg' => $datum['sourceMsg'],
  2562. 'auditMsg' => $datum['auditMsg'],
  2563. 'extends' => json_decode($datum['extends'],true),
  2564. 'printingNum' => getArrayItem($orderNoBindPritNum, $datum['no'], 0),
  2565. ];
  2566. if (!empty($orderGoodsData)) {
  2567. $returnData[$key]['goodsData'] = isset($goodsMap[$datum['id']]) ? $goodsMap[$datum['id']] : [];
  2568. }
  2569. }
  2570. return ResultWrapper::success($returnData);
  2571. }
  2572. private static function formatSn($no): string
  2573. {
  2574. return StatusCode::$noPrefix[StatusCode::$orderType['saleOrder']].'-'.$no;
  2575. }
  2576. /**
  2577. * Doc: (des="订单查询index表 sql生成")
  2578. * User: XMing
  2579. * Date: 2020/7/11
  2580. * Time: 11:23 上午
  2581. * @waitAudit:等待审核 orderStatus != 6 auditStatus = 1
  2582. * @waitOutStock:待出库 orderStatus != 6 auditPass = 2
  2583. * @hasOutStock:已出库 orderStatus = 4 auditPass = 2
  2584. * @finish:已完成 orderStatus = 5 auditPass 2
  2585. * @close:已关闭 orderStatus = 6
  2586. * @param array $selectParams
  2587. * @return array
  2588. */
  2589. public function setOrderStatusSqlAttr(array $selectParams): array
  2590. {
  2591. $fields = 'id,userCenterId,no,customerId';
  2592. $countFields = ' COUNT(id) AS total ';
  2593. //订单类型
  2594. $whereSql = '';
  2595. if (isset($selectParams['orderType']) && !empty($selectParams['orderType'])) {
  2596. if (is_array($selectParams['orderType'])) {
  2597. $orderTypeStr = implode(',', $selectParams['orderType']);
  2598. $whereSql .= ' and orderType in(' . $orderTypeStr . ') ';
  2599. } else {
  2600. $whereSql .= ' and orderType = ' . $selectParams['orderType'];
  2601. }
  2602. } else {
  2603. $whereSql .= ' and orderType = ' . StatusCode::$orderType['saleOrder'];
  2604. }
  2605. if (isset($selectParams['keyword']) && !empty($selectParams['keyword'])){
  2606. if (strstr($selectParams['keyword'],StatusCode::$noPrefix['1'])){
  2607. $selectParams['keyword']= substr($selectParams['keyword'],strlen(StatusCode::$noPrefix[StatusCode::$orderType['saleOrder']])+1);
  2608. }
  2609. $keyword = '"%'.$selectParams['keyword'].'%"';
  2610. $whereSql .= ' and no LIKE '.$keyword.' or verifyCode LIKE '.$keyword;
  2611. }
  2612. if (isset($selectParams['orderType']) && $selectParams['orderType'] == StatusCode::$orderType['cashierOrder']) {
  2613. $selectParams['cashierUid'] = $this->onlineUserId;
  2614. }
  2615. if (isset($selectParams['isAll']) && $selectParams['isAll'] == StatusCode::$standard) {
  2616. unset($selectParams['cashierUid']);
  2617. }
  2618. //userCenterId
  2619. if (isset($selectParams['userCenterId']) && !empty($selectParams['userCenterId'])) {
  2620. $whereSql .= ' and userCenterId = ' . $selectParams['userCenterId'];
  2621. }
  2622. //customerId
  2623. if (isset($selectParams['customerId']) && !empty($selectParams['customerId'])) {
  2624. $whereSql .= ' and customerId = ' . $selectParams['customerId'];
  2625. }
  2626. //收银员id
  2627. if (isset($selectParams['cashierStaffId']) && !empty($selectParams['cashierStaffId'])) {
  2628. $whereSql .= ' and cashierStaffId = ' . $selectParams['cashierStaffId'];
  2629. }
  2630. //no
  2631. if (isset($selectParams['no']) && !empty($selectParams['no'])) {
  2632. $whereSql .= ' and no = "' . $selectParams['no'].'"';
  2633. }
  2634. //shopId
  2635. if (isset($selectParams['shopId']) && !empty($selectParams['shopId'])) {
  2636. $whereSql .= ' and shopId = ' . $selectParams['shopId'];
  2637. }
  2638. //收银员id
  2639. if (isset($selectParams['cashierUid']) && !empty($selectParams['cashierUid'])) {
  2640. $whereSql .= ' and cashierUid = ' . $selectParams['cashierUid'];
  2641. }
  2642. //审核状态
  2643. if (isset($selectParams['auditStatus']) && !empty($selectParams['auditStatus'])) {
  2644. $whereSql .= ' and auditStatus = ' . $selectParams['auditStatus'];
  2645. }
  2646. //出库状态
  2647. if (isset($selectParams['outStatus']) && !empty($selectParams['outStatus'])) {
  2648. $whereSql .= ' and outStatus = ' . $selectParams['outStatus'];
  2649. }
  2650. //退货状态
  2651. if (isset($selectParams['returnStatus']) && !empty($selectParams['returnStatus'])) {
  2652. if (is_array($selectParams['returnStatus'])) {
  2653. $returnStatusStr = implode(',', $selectParams['returnStatus']);
  2654. $whereSql .= ' and returnStatus in(' . $returnStatusStr . ') ';
  2655. } else {
  2656. $whereSql .= ' and returnStatus = ' . $selectParams['returnStatus'];
  2657. }
  2658. }
  2659. //配送方式
  2660. if (isset($selectParams['deliveryType']) && !empty($selectParams['deliveryType'])) {
  2661. $whereSql .= ' and deliveryType = ' . $selectParams['deliveryType'];
  2662. }
  2663. //支付方式
  2664. if (isset($selectParams['payType']) && !empty($selectParams['payType'])) {
  2665. $whereSql .= ' and find_in_set('.$selectParams['payType'].',payType) ';
  2666. }
  2667. if (isset($selectParams['startTime']) && !empty($selectParams['startTime'])){
  2668. $whereSql .= ' AND createTime BETWEEN '.$selectParams['startTime'].' AND '.$selectParams['endTime'];
  2669. }
  2670. if (isset($selectParams['source']) && !empty($selectParams['source'])){
  2671. $whereSql .= ' AND source = '.$selectParams['source'];
  2672. }
  2673. if (isset($selectParams['salesManId']) && !empty($selectParams['salesManId'])){
  2674. $whereSql .= ' AND salesManId = '.$selectParams['salesManId'];
  2675. }
  2676. if (isset($selectParams['customerType']) && !empty($selectParams['customerType'])){
  2677. $whereSql .= ' AND customerType = '.$selectParams['customerType'];
  2678. }
  2679. //订单状态
  2680. if (isset($selectParams['state']) && !empty($selectParams['state'])) {
  2681. $whereSql = self::buildStateSqlAttr($whereSql, $selectParams['state']);
  2682. }
  2683. //数据域
  2684. if (isset($selectParams['orderType']) && $selectParams['orderType'] == StatusCode::$orderType['cashierOrder'] && isset($selectParams['cashierUid']) && !empty($selectParams['cashierUid'])) {
  2685. //收银台列表
  2686. } else {
  2687. $whereSql = parent::getSalesManQueryParams($whereSql);
  2688. }
  2689. $whereSql = parent::getShopIdQueryParams($whereSql);
  2690. $whereSql .= ' order by createTime desc';
  2691. $sql = 'select ' . $fields . ' from qianniao_order_index_' . $this->onlineEnterpriseId . ' where deleteStatus = ' . StatusCode::$standard.$whereSql;
  2692. $countSql = 'select ' . $countFields . ' from qianniao_order_index_' . $this->onlineEnterpriseId . ' where deleteStatus = ' . StatusCode::$standard.$whereSql;
  2693. return [
  2694. 'sql' => $sql,
  2695. 'countSql' => $countSql
  2696. ];
  2697. }
  2698. /**
  2699. * Doc: (des="state标示多选sql处理")
  2700. * User: XMing
  2701. * Date: 2020/7/13
  2702. * Time: 9:38 上午
  2703. * @param string $sql
  2704. * @param mixed $states
  2705. * @return string
  2706. */
  2707. private static function buildStateSqlAttr(string $sql, $states)
  2708. {
  2709. if (is_array($states)) {
  2710. if (in_array('all', $states)) {
  2711. return $sql;
  2712. }
  2713. foreach ($states as $index => $state) {
  2714. $sql .= $index == 0 ? ' and (' . self::stateSql($state) : ' or ' . self::stateSql($state);
  2715. }
  2716. $sql .= ') ';
  2717. } else {
  2718. if ($states == 'all') {
  2719. return $sql;
  2720. }
  2721. $stateSql = self::stateSql($states);
  2722. if (!empty($stateSql)) {
  2723. $sql .= ' and ' . self::stateSql($states);
  2724. }
  2725. }
  2726. return $sql;
  2727. }
  2728. /**
  2729. * Doc: (des="state标示对应sql")
  2730. * User: XMing
  2731. * Date: 2020/7/13
  2732. * Time: 9:43 上午
  2733. * @param string $state
  2734. * @return string
  2735. */
  2736. private static function stateSql(string $state)
  2737. {
  2738. $sql = '';
  2739. switch ($state) {
  2740. case 'waitAudit'://待审核
  2741. $sql .= ' (auditStatus = ' . StatusCode::$auditStatus['auditing'] . ' and orderStatus != ' . StatusCode::$orderStatus['close'] . ')';
  2742. break;
  2743. case 'waitOutStock'://待出库
  2744. $sql .= ' (auditStatus = ' . StatusCode::$auditStatus['auditPass'] . ' and (orderStatus = ' . StatusCode::$orderStatus['waitPay'] . ' or orderStatus = ' . StatusCode::$orderStatus['waitDelivery'] . ')) ';
  2745. break;
  2746. case 'hasOutStock'://已出库
  2747. $sql .= ' (auditStatus = ' . StatusCode::$auditStatus['auditPass'] . ' and orderStatus = ' . StatusCode::$orderStatus['waitReceive'] . ')';
  2748. break;
  2749. case 'finish'://已完成
  2750. $sql .= ' (auditStatus = ' . StatusCode::$auditStatus['auditPass'] . ' and orderStatus = ' . StatusCode::$orderStatus['finish'] . ')';
  2751. break;
  2752. case 'close'://已关闭
  2753. $sql .= ' (orderStatus = ' . StatusCode::$orderStatus['close'] . ')';
  2754. break;
  2755. case 'all'://全部订单
  2756. break;
  2757. }
  2758. return $sql;
  2759. }
  2760. /**
  2761. * 删除订单视图
  2762. */
  2763. public function dropView()
  2764. {
  2765. $sql = 'DROP VIEW ' . $this->orderStatisticsTableName . '_' . $this->onlineEnterpriseId;
  2766. $dbResult = $this->objDOrder->query($sql);
  2767. if ($dbResult === false) {
  2768. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  2769. }
  2770. return ResultWrapper::success('删除成功');
  2771. }
  2772. /**
  2773. * 判断表是否存在
  2774. * @param $tableName
  2775. */
  2776. public function existsTable($tableName)
  2777. {
  2778. $exists = $this->objDOrder->existsTable($tableName);
  2779. if (!$exists) {
  2780. //不存在删除视图
  2781. self::dropView();
  2782. }
  2783. }
  2784. /**
  2785. * 添加银行打款数据
  2786. */
  2787. public function addOrderBankData($orderBankData)
  2788. {
  2789. //切换分表
  2790. $fix = $fix = ceil($this->onlineUserId / $this->cutTable);
  2791. $this->objDOrder->setTable('qianniao_order_' . $this->onlineEnterpriseId . '_' . $fix);
  2792. foreach ($orderBankData['orderId'] as $key => $value){
  2793. //获取订单信息
  2794. $orderData = $this->objDOrder->get(['id' => $value]);
  2795. if ($orderData === false) {
  2796. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  2797. }
  2798. if(empty($orderData)){
  2799. return ResultWrapper::fail('订单不存在', ErrorCode::$contentNotExists);
  2800. }
  2801. $orderData['extends'] = json_decode($orderData['extends'], true);
  2802. $orderData['extends']['bankData'] = $orderBankData['bankData'];
  2803. $orderData['extends'] = json_encode($orderData['extends']);
  2804. $dbReuslt = $this->objDOrder->update(['extends'=>$orderData['extends'],'updateTime'=>time()], $value);
  2805. if ($dbReuslt === false) {
  2806. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  2807. }
  2808. }
  2809. return ResultWrapper::success($dbReuslt);
  2810. }
  2811. /**
  2812. * Doc: (des="审核订单,到出库单")
  2813. * User: XMing
  2814. * Date: 2020/7/14
  2815. * Time: 6:38 下午
  2816. * @param array $params
  2817. * @return ResultWrapper
  2818. * @throws \Exception
  2819. */
  2820. public function updateAuditStatus(array $params)
  2821. {
  2822. $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId);
  2823. $orderIndex = $this->objDOrderIndex->get(['id' => $params['id']]);
  2824. if ($orderIndex === false) {
  2825. return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
  2826. }
  2827. if (empty($orderIndex)) {
  2828. return ResultWrapper::fail('没有找到订单信息', ErrorCode::$paramError);
  2829. }
  2830. if ($orderIndex['auditStatus'] == StatusCode::$auditStatus['auditPass']) {
  2831. return ResultWrapper::fail('当前订单已经审核通过!', ErrorCode::$paramError);
  2832. }
  2833. if ($this->isCashier === false) {
  2834. //在线支付的订单必须是已支付才能审核
  2835. if ($orderIndex['payType'] == StatusCode::$payType['wxPay'] || $orderIndex['payType'] == StatusCode::$payType['aliPay']) {
  2836. if ($params['auditStatus'] == StatusCode::$auditStatus['auditPass'] && $orderIndex['payStatus'] == StatusCode::$delete) {
  2837. return ResultWrapper::fail('订单尚未支付,不能审核', ErrorCode::$notAllowAccess);
  2838. }
  2839. }
  2840. }
  2841. //切换分表
  2842. $fix = $fix = ceil($orderIndex['userCenterId'] / $this->cutTable);
  2843. $this->objDOrder->setTable('qianniao_order_' . $this->onlineEnterpriseId . '_' . $fix);
  2844. //获取订单信息
  2845. $orderData = $this->objDOrder->get(['id' => $params['id']]);
  2846. if ($orderData === false) {
  2847. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  2848. }
  2849. // 银行打款支付方式审核之前需要判断是否上传凭证
  2850. if( $orderData['payType'] == StatusCode::$payType['bankLoans'] ){
  2851. $extends = json_decode($orderData['extends'],true);
  2852. if (!array_key_exists('bankData',$extends)){
  2853. return ResultWrapper::fail('该订单未上传银行打款凭证', ErrorCode::$paramError);
  2854. }
  2855. $customerData = $this->objDCustomer->get(['id'=>$orderData['customerId']]);
  2856. if ($customerData === false) {
  2857. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  2858. }
  2859. if(isset($customerData['openId']) && !empty($customerData['openId'])){
  2860. // 银行打款上传凭证小程序订阅消息
  2861. $sendMessageData = [
  2862. 'date4' => [ 'value' => date('Y-m-d H:i:s',$orderData['createTime'])], // 提交时间
  2863. 'thing10' => [ 'value' => $customerData['name'] ], // 申请人
  2864. 'thing2' => [ 'value' => '银行打款凭证是否通过'], // 审核内容
  2865. 'date3' => [ 'value' => date('Y-m-d H:i:s',$orderData['updateTime']) ], // 审核时间
  2866. 'phrase1' => [ 'value' => $orderData['auditStatus'] == StatusCode::$auditStatus['auditPass'] ? '审核通过':'审核未通过'], // 审核结果
  2867. ];
  2868. $objMSystemPushMessage = new MSystemPushMessage($this->onlineUserId, $this->onlineEnterpriseId);
  2869. $result = $objMSystemPushMessage->sendWeiXinPushMessage(4, $customerData['openId'], $sendMessageData);
  2870. if(!$result->isSuccess()){
  2871. 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);
  2872. }
  2873. }
  2874. }
  2875. $this->objDOrderIndex->beginTransaction();
  2876. // 生成收款单
  2877. $receivedResult = self::createReceived($orderData);
  2878. if (!$receivedResult->isSuccess()) {
  2879. $this->objDOrderIndex->rollBack();
  2880. return ResultWrapper::fail($receivedResult->getData(), $receivedResult->getErrorCode());
  2881. }
  2882. $update = [
  2883. 'auditStatus' => $params['auditStatus'],
  2884. 'updateTime' => time(),
  2885. ];
  2886. if ( $orderData['payType'] == StatusCode::$payType['bankLoans'] ){//银行打款更新payStatus,orderStatus
  2887. $update = [
  2888. 'auditStatus' => $params['auditStatus'],
  2889. 'payStatus' => StatusCode::$standard,
  2890. 'orderStatus' => StatusCode::$orderStatus['waitDelivery'],
  2891. 'updateTime' => time(),
  2892. ];
  2893. }
  2894. //操作索引表
  2895. $orderIndexUpdate = $this->objDOrderIndex->update($update, ['id' => $params['id']]);
  2896. if ($orderIndexUpdate === false) {
  2897. $this->objDOrderIndex->rollBack();
  2898. Logger::logs(E_USER_ERROR, 'sql错误', __CLASS__, __LINE__, $this->objDOrderIndex->error());
  2899. return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
  2900. }
  2901. //操作订单表
  2902. $orderUpdate = $this->objDOrder->update($update, $params['id']);
  2903. if ($orderUpdate === false) {
  2904. $this->objDOrderIndex->rollBack();
  2905. Logger::logs(E_USER_ERROR, 'sql错误', __CLASS__, __LINE__, $this->objDOrder->error());
  2906. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  2907. }
  2908. //订单审核出库
  2909. $outId = 0;
  2910. if ($params['auditStatus'] == StatusCode::$auditStatus['auditPass']) {
  2911. $orderData['auditId'] = $params['auditId'];
  2912. $orderData['audit'] = $params['audit'];
  2913. $addInventoryOutResult = self::addInventoryOut($params['id'], $orderData, $orderData['userCenterId']);
  2914. if (!$addInventoryOutResult->isSuccess()) {
  2915. $this->objDOrderIndex->rollBack();
  2916. return ResultWrapper::fail($addInventoryOutResult->getData(), $addInventoryOutResult->getErrorCode());
  2917. }
  2918. $outId = $addInventoryOutResult->getData();
  2919. }
  2920. $this->objDOrderIndex->commit();
  2921. /*
  2922. //跟新es
  2923. $_id = self::createEsDocumentId($params['id']);
  2924. $this->objDOrder->esupdateTypeFieldVaule($update, $_id);*/
  2925. self::runProcessNextOut($outId,$orderData);
  2926. if ($params['auditStatus'] == StatusCode::$auditStatus['auditPass']) {
  2927. return ResultWrapper::success($outId);
  2928. }
  2929. if(isset($customerData['openId']) && !empty($customerData['openId'])){
  2930. // 订单审核通过
  2931. $sendMessageData = [
  2932. 'date4' => [ 'value' => date('Y-m-d H:i:s',$orderData['createTime'])], // 提交时间
  2933. 'thing2' => [ 'value' => '银行打款凭证是否通过'], // 审核内容
  2934. 'phrase1' => [ 'value' => $orderData['auditStatus'] == 2 ? '审核通过':'审核未通过'], // 审核结果
  2935. 'date3' => [ 'value' => date('Y-m-d H:i:s',$orderData['updateTime']) ], // 审核时间
  2936. ];
  2937. $objMSystemPushMessage = new MSystemPushMessage($this->onlineUserId, $this->onlineEnterpriseId);
  2938. $result = $objMSystemPushMessage->sendWeiXinPushMessage(6, $customerData['openId'], $sendMessageData);
  2939. if(!$result->isSuccess()){
  2940. 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);
  2941. }
  2942. }
  2943. return ResultWrapper::success('操作成功');
  2944. }
  2945. /**
  2946. * Doc: (des="step 3: 审核出库")
  2947. * User: XMing
  2948. * Date: 2020/11/9
  2949. * Time: 9:24 上午
  2950. * @param array $order
  2951. * @param int $outId
  2952. * @return ResultWrapper
  2953. * @throws \Exception
  2954. */
  2955. private function runProcessNextOut(int $outId,array $order): ResultWrapper
  2956. {
  2957. if (empty($outId)){
  2958. return ResultWrapper::success(true);
  2959. }
  2960. if ($order['orderType'] != StatusCode::$orderType['saleOrder']){
  2961. return ResultWrapper::success(true);
  2962. }
  2963. $setResult = $this->objMProcessSetting->getProcessSettingByType(StatusCode::$processType['sales'],'out');
  2964. if (!$setResult->isSuccess()){
  2965. Logger::logs(E_USER_ERROR,'获取流程配置出错',__CLASS__,__LINE__,$setResult->getData());
  2966. return ResultWrapper::fail($setResult->getData(),$setResult->getErrorCode());
  2967. }
  2968. $set = $setResult->getData();
  2969. if (empty($set)){
  2970. Logger::logs(E_USER_ERROR,'配置为空',__CLASS__,__LINE__,'');
  2971. return ResultWrapper::success(true);
  2972. }
  2973. if (isset($set['enableStatus']) && $set['enableStatus'] == StatusCode::$standard){
  2974. Logger::logs(E_USER_ERROR,'配置',__CLASS__,__LINE__,$set);
  2975. return ResultWrapper::success(true);
  2976. }
  2977. $params = [
  2978. 'id' => $outId,
  2979. 'auditId' => $this->onlineUserId,//操作人id
  2980. 'auditName' => '自动审核',//操作人姓名
  2981. ];
  2982. $objMInventoryOut = new MInventoryOut($this->onlineEnterpriseId,$this->onlineUserId);
  2983. $result = $objMInventoryOut->updateInventoryOutStatus($params);
  2984. if (!$result->isSuccess()){
  2985. Logger::logs(E_USER_ERROR,'自动审核出库单出错',__CLASS__,__LINE__,$result->getData());
  2986. return ResultWrapper::fail($result->getData(),$result->getErrorCode());
  2987. }
  2988. Logger::logs(E_USER_ERROR,'自动审核出库单成功',__CLASS__,__LINE__,$outId);
  2989. return ResultWrapper::success(true);
  2990. }
  2991. /**
  2992. * Doc: (des="后台代客下单创建收款单")
  2993. * User: XMing
  2994. * Date: 2020/11/5
  2995. * Time: 5:31 下午
  2996. * @param array $orderData
  2997. * @return ResultWrapper
  2998. * @throws \Exception
  2999. */
  3000. private function createReceived(array $orderData): ResultWrapper
  3001. {
  3002. // 银行打款
  3003. if ($orderData['payType'] == StatusCode::$payType['bankLoans']){
  3004. $orderExtendsData = json_decode($orderData['extends'], true);
  3005. // 组装收款单账户数据
  3006. $accountListData[] = [
  3007. 'discountMoney' => 0,
  3008. 'money' => $orderData['payAmount'],
  3009. 'payWay' => StatusCode::$payType[4],
  3010. 'remark' => '银行打款生成收款',
  3011. 'accountId' => ($orderExtendsData['bankData']['id']) ? : 0,
  3012. 'accountName' => ($orderExtendsData['bankData']['name']) ? : '',
  3013. 'accountNumber' => ($orderExtendsData['bankData']['accountNumber']) ? : '',
  3014. 'finalMoney' => $orderData['payAmount'],
  3015. ];
  3016. $orderData['accountList'] = json_encode($accountListData);
  3017. $orderData['currentAccountName'] = ($orderExtendsData['bankData']['name']) ? : '';
  3018. }
  3019. //生成收款单
  3020. if ( ($orderData['orderType'] == StatusCode::$orderType['saleOrder'] || $orderData['orderType'] == StatusCode::$orderType['salesSlip']) &&
  3021. $orderData['source'] == StatusCode::$source['manage'] &&
  3022. !empty($orderData['accountList']) &&
  3023. !empty(floatval($orderData['receivedMoney'])) || ( $orderData['payType'] == StatusCode::$payType['bankLoans'] )//银行打款也生成收款单
  3024. ) {
  3025. $this->objDOrderIndex->beginTransaction();
  3026. //生成收款单
  3027. $objMReceived = new MReceived($this->onlineEnterpriseId, $this->onlineUserId);
  3028. //创建收款单
  3029. $received = [
  3030. 'currentAccountName' => $orderData['currentAccountName'],
  3031. 'financeType' => '银行打款收款',
  3032. 'financeTypeId' => 2,
  3033. 'shopId' => $orderData['shopId'],
  3034. 'shopName' => $orderData['shopName'],
  3035. 'receiptTime' => time(),
  3036. 'operatorId' => $this->onlineUserId,
  3037. 'accountList' => json_decode($orderData['accountList'], true),
  3038. 'customerId' => $orderData['customerId'],
  3039. 'customerName' => $orderData['customerName'],
  3040. 'sourceNo' => $orderData['no'],
  3041. 'sourceId' => $orderData['id'],
  3042. 'originId' => $orderData['id'],
  3043. 'originNo' => $orderData['originNo'],
  3044. 'sourceNoMoney' => $orderData['receivedMoney'],
  3045. 'extends' => isset($orderExtendsData['bankData']) ? json_encode($orderExtendsData['bankData']) : '[]',
  3046. 'createTime' => time(),
  3047. 'auditStatus' => StatusCode::$auditStatus['auditing'],
  3048. 'updateTime' => time(),
  3049. ];
  3050. $receivedResult = $objMReceived->addReceived($received, true);
  3051. if (!$receivedResult->isSuccess()) {
  3052. $this->objDOrderIndex->rollBack();
  3053. return ResultWrapper::fail($receivedResult->getData(), $receivedResult->getErrorCode());
  3054. }
  3055. $up = [];
  3056. if ($orderData['receivedMoney'] >= $orderData['payAmount']) {
  3057. $up = [
  3058. 'payStatus' => StatusCode::$standard,
  3059. 'updateTime' => time(),
  3060. ];
  3061. }else{
  3062. if ($orderData['receivedMoney'] != 0){
  3063. $up = [
  3064. 'payStatus' => StatusCode::$offline,//部分收款
  3065. 'updateTime' => time(),
  3066. ];
  3067. }
  3068. }
  3069. if (!empty($up)){
  3070. $result = $this->objDOrderIndex->update($up, $orderData['id']);
  3071. if ($result === false) {
  3072. $this->objDOrderIndex->rollBack();
  3073. return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
  3074. }
  3075. $result = $this->objDOrder->update($up, $orderData['id']);
  3076. if ($result === false) {
  3077. $this->objDOrderIndex->rollBack();
  3078. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  3079. }
  3080. }
  3081. $this->objDOrderIndex->commit();
  3082. }
  3083. return ResultWrapper::success(true);
  3084. }
  3085. /**
  3086. * Doc: (des="订单审核出库,使用此方法一定要注意在上文获取当前订单的userCenterId用于下文切换分表")
  3087. * User: XMing
  3088. * Date: 2020/7/15
  3089. * Time: 9:48 上午
  3090. * @param array $orderData
  3091. * @param int $id
  3092. * @param int $thisOnlineUserId 当前订单的用户id,用来切换分表
  3093. * @return ResultWrapper
  3094. * @throws \Exception
  3095. */
  3096. private function addInventoryOut(int $id, array $orderData, int $thisOnlineUserId)
  3097. {
  3098. //查询订单商品表
  3099. $objMOrderGoods = new MOrderGoods($thisOnlineUserId, $this->onlineEnterpriseId);
  3100. $selectData = ['orderId' => $id];
  3101. $orderGoodsDataObj = $objMOrderGoods->getOrderGoodsByOrderIds($selectData);
  3102. if (!$orderGoodsDataObj->isSuccess()) {
  3103. return ResultWrapper::fail($orderGoodsDataObj->getData(), ErrorCode::$dberror);
  3104. }
  3105. $objMInventoryOut = new MInventoryOut($this->onlineEnterpriseId, $this->onlineUserId);
  3106. $totalResult = $objMInventoryOut->getTotalByOrderId($orderData['id']);
  3107. if (!$totalResult->isSuccess()){
  3108. return ResultWrapper::fail($totalResult->getData(),$totalResult->getErrorCode());
  3109. }
  3110. $total = (int)$totalResult->getData();
  3111. if ($total > 0){
  3112. //已经生成过出库单了
  3113. Logger::logs(E_USER_ERROR, '订单id:'.$orderData['id'].',重复生成出库单', __CLASS__, __LINE__,$orderData);
  3114. return ResultWrapper::fail('不要重复操作,避免生成成多个出库单',ErrorCode::$paramError);
  3115. }
  3116. //查询商铺id对应的仓库数据
  3117. $objMShop = new MShop($this->onlineEnterpriseId, $this->onlineUserId);
  3118. $modelResult = $objMShop->getShopDataByShopIds([$orderData['shopId']]);
  3119. if (!$modelResult->isSuccess()) {
  3120. return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
  3121. }
  3122. $shopData = $modelResult->getData();
  3123. unset($modelResult);
  3124. //获取订单收货信息
  3125. $orderReceiveDbResult = [];
  3126. if ($orderData['deliveryType'] == StatusCode::$deliveryType['goodsDelivery']) {
  3127. $fix = ceil($thisOnlineUserId / $this->cutTable);
  3128. $this->objDOrderReceive->setTable('qianniao_order_receive_' . $this->onlineEnterpriseId . '_' . $fix);
  3129. $orderReceiveDbResult = $this->objDOrderReceive->get(['orderId' => $id]);
  3130. if ($orderReceiveDbResult === false) {
  3131. return ResultWrapper::fail($this->objDOrderReceive->error(), ErrorCode::$dberror);
  3132. }
  3133. if (empty($orderReceiveDbResult)) {
  3134. return ResultWrapper::fail('订单收货地址查询失败', ErrorCode::$dberror);
  3135. }
  3136. }
  3137. $objMCustomer = new MCustomer($this->onlineEnterpriseId,$this->onlineUserId);
  3138. $customerResult = $objMCustomer->getCustomerByCustomerId($orderData['customerId']);
  3139. if (!$customerResult->isSuccess()){
  3140. return ResultWrapper::fail($customerResult->getData(),$customerResult->getErrorCode());
  3141. }
  3142. $customer = $customerResult->getData();
  3143. $orderGoodsData = $orderGoodsDataObj->getData();//订单商品数据
  3144. $saleOutData = [
  3145. 'sourceId' => $orderData['id'],
  3146. 'sourceNo' => $orderData['no'],
  3147. 'originNo' => $orderData['no'],
  3148. 'originId' => $orderData['id'],
  3149. 'shopId' => $orderData['shopId'],
  3150. 'shopName' => $orderData['shopName'],
  3151. 'amount' => $orderData['payAmount'],
  3152. 'operatorId' => $orderData['auditId'],//操作人id
  3153. 'operatorName' => $orderData['audit'],//操作人信息
  3154. 'customerId' => $orderData['customerId'],
  3155. 'customerName' => $orderData['customerName'],
  3156. 'customerCode' => createCode(StatusCode::$code['customer']['prefix'], $orderData['customerId'], StatusCode::$code['customer']['length']),
  3157. 'customerMobile' => isset($customer['mobile']) ? $customer['mobile'] : '',
  3158. 'source' => StatusCode::$orderType['saleOrder'], //订单来源(出库类型)
  3159. 'type' => StatusCode::$orderType['saleOut'],
  3160. 'deliveryType' => $orderData['deliveryType'],//配送方式
  3161. 'remark' => $orderData['remark'],
  3162. ];
  3163. $saleOutData['materielNum'] = 0;
  3164. //获取sku
  3165. $objMSku = new MSku($this->onlineUserId, $this->onlineEnterpriseId);
  3166. $skuIds = array_column(array_values($orderGoodsData), 'skuId');
  3167. $modelResult = $objMSku->getSkuDataBySkuIds($skuIds);
  3168. if (!$modelResult->isSuccess()) {
  3169. return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
  3170. }
  3171. $skuData = $modelResult->getData();
  3172. unset($modelResult);
  3173. foreach ($orderGoodsData as $key => $value) {
  3174. $saleOutData['materielNum']++;
  3175. $totalMoney = bcsub(bcsub($value['totalMoney'], $value['vipDiscount']), $value['preferential']);//销售总价 !优惠后
  3176. $saleOutData['orderGoodsData'][] = [
  3177. 'materielId' => $value['goodsBasicId'],
  3178. 'materielName' => $value['goodsName'],
  3179. 'materielCode' => createCode(StatusCode::$code['goodsBasic']['prefix'], $value['goodsBasicId'], StatusCode::$code['goodsBasic']['length']),
  3180. 'skuId' => $value['skuId'],
  3181. 'num' => $value['buyNum'],
  3182. 'otherNum' => $value['otherNum'],
  3183. 'outNum' => 0,
  3184. 'total' => $value['buyNum'],
  3185. 'unitName' => isset($value['unitName']) ? $value['unitName'] : '',
  3186. 'skuName' => isset($skuData[$value['skuId']]) ? $skuData[$value['skuId']]['skuName'] : '',
  3187. 'unitPrice' => $value['price'],//单价 不优惠
  3188. 'totalPrice' => $totalMoney,//销售总价 !优惠后
  3189. 'extend' => $value['extends'],
  3190. 'isEq' => $value['isEq'],
  3191. ];
  3192. }
  3193. $dbResult = $objMInventoryOut->addInventoryOut($saleOutData);
  3194. if (!$dbResult->isSuccess()) {
  3195. Logger::logs(E_USER_ERROR, 'sql错误', __CLASS__, __LINE__, $dbResult->getData());
  3196. return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror);
  3197. }
  3198. self::noticeStatistics([
  3199. 'userCenterId' => $thisOnlineUserId,
  3200. 'enterpriseId' => $this->onlineEnterpriseId,
  3201. 'customerId' => $orderData['customerId'],
  3202. 'no' => $orderData['no'],
  3203. 'noticeType' => 'audit',//审核
  3204. ], 'MOrderStatistics');
  3205. //添加日志
  3206. parent::saveLog([
  3207. 'no' => $orderData['no'],
  3208. 'actionType' => '审核通过',
  3209. 'operationData' => '',
  3210. 'userCenterId' => $this->onlineUserId,
  3211. 'enterpriseId' => $this->onlineEnterpriseId,
  3212. 'createTime' => time(),
  3213. ]);
  3214. self::sendMessage($this->onlineEnterpriseId,'NewOrder','stockOut');
  3215. return ResultWrapper::success($dbResult->getData());
  3216. }
  3217. /**
  3218. * 批量审核
  3219. * @param array $params
  3220. * @return ResultWrapper
  3221. * @throws \Exception
  3222. */
  3223. public function batchUpdateAuditStatus(array $params)
  3224. {
  3225. $auditParam = [
  3226. 'audit' => $params['audit'],
  3227. 'auditId' => $params['auditId'],
  3228. 'auditStatus' => $params['auditStatus']
  3229. ];
  3230. foreach ($params['ids'] as $id) {
  3231. $auditParam['id'] = $id;
  3232. $result = self::updateAuditStatus($auditParam);
  3233. if (!$result->isSuccess()) {
  3234. return ResultWrapper::fail($result->getData(), $result->getErrorCode());
  3235. }
  3236. }
  3237. return ResultWrapper::success("审核成功");
  3238. }
  3239. /**
  3240. * Doc: (des="修改订单的状态,orderStatus")
  3241. * User: XMing
  3242. * Date: 2020/7/14
  3243. * Time: 5:25 下午
  3244. * @param $id
  3245. * @param $selectParams
  3246. * @param array $header
  3247. * @return ResultWrapper
  3248. * @throws \Exception
  3249. */
  3250. public function updateOrderStatus($id, $selectParams, array $header)
  3251. {
  3252. // 查询订单索引表数据
  3253. $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId);
  3254. $orderIndex = $this->objDOrderIndex->get(['id' => $id], 'userCenterId,payStatus,createTime,customerId,no,updateTime');
  3255. if ($orderIndex === false) {
  3256. return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
  3257. }
  3258. if (empty($orderIndex)) {
  3259. return ResultWrapper::fail('订单信息不存在', ErrorCode::$paramError);
  3260. }
  3261. // 后台设置的审核通过不能取消订单
  3262. $objEnterpriseCache = new EnterpriseCache();
  3263. $enterSettingData = $objEnterpriseCache->getEnterpriseSetting($this->onlineEnterpriseId);
  3264. if(isset($enterSettingData['cancelOrder']) && $enterSettingData['cancelOrder'] == StatusCode::$delete && $orderIndex['auditStatus'] == StatusCode::$auditStatus['auditPass'] && $selectParams['orderStatus'] == StatusCode::$orderStatus['close']){
  3265. return ResultWrapper::fail('当前订单已经审核通过,暂不支持取消,请联系客服处理', ErrorCode::$notAllowAccess);
  3266. }
  3267. if ($selectParams['orderStatus'] == StatusCode::$orderStatus['close']
  3268. && isset($orderIndex['outStatus']) && $orderIndex['outStatus'] == StatusCode::$standard) {
  3269. return ResultWrapper::fail('已经发货订单不能取消', ErrorCode::$paramError);
  3270. }
  3271. // 切换订单分表,查询订单主单据数据
  3272. $fix = ceil($orderIndex['userCenterId'] / $this->cutTable);;
  3273. $this->objDOrder->setTable('qianniao_order_' . $this->onlineEnterpriseId . '_' . $fix);
  3274. $orderData = $this->objDOrder->get(['id' => $id]);
  3275. if($orderData === false) {
  3276. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  3277. }
  3278. if(empty($orderData)){
  3279. return ResultWrapper::fail('要操作的订单不存在', ErrorCode::$contentNotExists);
  3280. }
  3281. $this->objDOrderIndex->beginTransaction();
  3282. $selectParams['cancelbeforeOrderStatus'] = $orderData["orderStatus"];
  3283. // 更新订单表
  3284. $orderData['extends'] = json_decode($orderData['extends'], true);
  3285. if( !empty($selectParams['cancelReason']) ){
  3286. $orderData['extends']['cancelReason'] = $selectParams['cancelReason'];
  3287. $orderData['extends']['cancelbeforeOrderStatus'] = $selectParams['cancelbeforeOrderStatus'];
  3288. $selectParams['successFullyTime'] = time();
  3289. }
  3290. if( !empty($selectParams['cancelRejectReason']) ){
  3291. $orderData['extends']['cancelRejectReason'] = $selectParams['cancelRejectReason'];
  3292. $selectParams['orderStatus'] = $orderData['extends']['cancelbeforeOrderStatus']; // 取消被拒恢复到取消之前的订单状态
  3293. }
  3294. // 更新索引表
  3295. $orderIndexUpdate = $this->objDOrderIndex->update([
  3296. 'orderStatus' => $selectParams['orderStatus'],
  3297. 'updateTime' => time()
  3298. ], ['id' => $id]);
  3299. if ($orderIndexUpdate === false) {
  3300. $this->objDOrderIndex->rollBack();
  3301. return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
  3302. }
  3303. $selectParams['extends'] = json_encode($orderData['extends']);
  3304. $selectParams['updateTime'] = time();
  3305. unset($selectParams['cancelReason']);
  3306. unset($selectParams['cancelRejectReason']);
  3307. unset($selectParams['cancelbeforeOrderStatus']);
  3308. $orderUpdate = $this->objDOrder->update($selectParams, ['id' => $id]);
  3309. if ($orderUpdate === false) {
  3310. $this->objDOrderIndex->rollBack();
  3311. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  3312. }
  3313. // 取消订单
  3314. if ($selectParams['orderStatus'] == StatusCode::$orderStatus['close']) {
  3315. // 解锁库存
  3316. $unlockResult = self::unlockInventory($id, $orderData);
  3317. if (!$unlockResult->isSuccess()) {
  3318. $this->objDOrderIndex->rollBack();
  3319. return ResultWrapper::fail($unlockResult->getData(), $unlockResult->getErrorCode());
  3320. }
  3321. // 已经支付订单做自动退款处理
  3322. if($orderData['payStatus'] == StatusCode::$standard){
  3323. // 生成财务退款单
  3324. $financeRefundData = [
  3325. 'originId' => getArrayItem($orderData,'id',0),
  3326. 'originNo' => getArrayItem($orderData,'no',''),
  3327. 'sourceId' => getArrayItem($orderData,'id',0),
  3328. 'sourceNo' => getArrayItem($orderData,'no',''),
  3329. 'refundTime' => time(),
  3330. 'createTime' => time(),
  3331. 'updateTime' => time(),
  3332. 'unitId' => getArrayItem($orderData,'customerId',0),
  3333. 'unitName' => getArrayItem($orderData,'customerName',0),
  3334. 'currentAccountName' => getArrayItem($orderData,'customerName',''),
  3335. 'financeType' => '订单取消退款',
  3336. 'financeTypeId' => 1,
  3337. 'payType' =>getArrayItem($orderData,'payType',''),
  3338. 'shopId' => getArrayItem($orderData,'shopId',0),
  3339. 'shopName' => getArrayItem($orderData,'shopName',0),
  3340. 'money' => $orderData['payAmount'],
  3341. 'operatorId' => $this->onlineUserId,
  3342. 'type' => StatusCode::$standard,
  3343. 'auditStatus' => StatusCode::$auditStatus['auditing'],
  3344. 'remark' => '订单取消,订单编号:'. getArrayItem($orderData,'no','').'需退款金额:'.$orderData['payAmount'],
  3345. ];
  3346. // 根据订单支付方式规划退款账户
  3347. $objMAccount = new MAccount($this->onlineEnterpriseId,$this->onlineUserId);
  3348. $extends = is_array($orderData['extends'])?$orderData['extends']: json_decode($orderData['extends'], true);
  3349. if(isset($extends['admixPayData'])){ // 组合支付
  3350. foreach ($extends['admixPayData'] as $key => $value){
  3351. $financeAccountData = $objMAccount->getDefaultAccount($value['payType']);
  3352. if(!$financeAccountData->isSuccess()){
  3353. return ResultWrapper::fail($financeAccountData->getData(), $financeAccountData->getErrorCode());
  3354. }
  3355. $financeAccountData = $financeAccountData->getData();
  3356. $financeRefundData['accountList'][] = [
  3357. 'accountId' => $financeAccountData['id'],
  3358. 'accountNumber' => $financeAccountData['accountNumber'],
  3359. 'accountName' => $financeAccountData['name'],
  3360. 'money' => $value['payMoney'],
  3361. ];
  3362. }
  3363. }else{
  3364. $financeAccountData = $objMAccount->getDefaultAccount($orderData['payType']);
  3365. if(!$financeAccountData->isSuccess()){
  3366. return ResultWrapper::fail($financeAccountData->getData(), $financeAccountData->getErrorCode());
  3367. }
  3368. $financeAccountData = $financeAccountData->getData();
  3369. $financeRefundData['accountList'] = [
  3370. [
  3371. 'accountId' => $financeAccountData['id'],
  3372. 'accountNumber' => $financeAccountData['accountNumber'],
  3373. 'accountName' => $financeAccountData['name'],
  3374. 'money' => $orderData['payAmount'],
  3375. ]
  3376. ];
  3377. }
  3378. $objMRefund = new MRefund($this->onlineEnterpriseId,$this->onlineUserId);
  3379. $result = $objMRefund->addRefund($financeRefundData);
  3380. if(!$result->isSuccess()){
  3381. return ResultWrapper::fail($result->getData(),$result->getErrorCode());
  3382. }
  3383. // 自动审核退款单
  3384. $result = $objMRefund->updateRefundStatus(['id'=>$result->getData(),'createTime'=>time()]);
  3385. if(!$result->isSuccess()){
  3386. return ResultWrapper::fail($result->getData(),$result->getErrorCode());
  3387. }
  3388. }
  3389. // 订单审核待出库时取消订单 同步删除销售出库单
  3390. if($orderData['auditStatus'] == StatusCode::$auditStatus['auditPass']){
  3391. $objMInventoryOut = new MInventoryOut($this->onlineEnterpriseId, $this->onlineUserId);
  3392. $inventoryOutResult = $objMInventoryOut->delInventoryOutStatus(['originId' => $orderData['id']]);
  3393. if (!$inventoryOutResult->isSuccess()) {
  3394. $this->objDOrderIndex->rollBack();
  3395. return ResultWrapper::fail($inventoryOutResult->getData(), $inventoryOutResult->getErrorCode());
  3396. }
  3397. }
  3398. $customerData = $this->objDCustomer->get(['id'=>$orderData['customerId']]);
  3399. if ($customerData === false) {
  3400. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  3401. }
  3402. if(isset($customerData['openId']) && !empty($customerData['openId'])){
  3403. // 后台取消订单小程序订阅消息
  3404. $sendMessageData = [
  3405. 'character_string13' => [ 'value' => StatusCode::$noPrefix[1] . '-' . $orderData['no']], // 订单编号
  3406. 'date10' => [ 'value' => date('Y-m-d H:i:s',$orderData['createTime']) ], // 下单时间
  3407. 'thing14' => [ 'value' => substr($orderData['shopName'],0,30)], // 门店名称
  3408. 'date2' => [ 'value' => date('Y-m-d H:i:s',$orderData['updateTime']) ], // 取消时间
  3409. ];
  3410. $objMSystemPushMessage = new MSystemPushMessage($this->onlineUserId, $this->onlineEnterpriseId);
  3411. $result = $objMSystemPushMessage->sendWeiXinPushMessage(5, $customerData['openId'], $sendMessageData);
  3412. if(!$result->isSuccess()){
  3413. 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);
  3414. }
  3415. }
  3416. }
  3417. //订单完成
  3418. if ($selectParams['orderStatus'] == StatusCode::$orderStatus['finish'] && !empty($header)) {
  3419. // 计算分销订单提成
  3420. $i = 1;
  3421. do {
  3422. $postData = [
  3423. 'topicName' => 'MyJob',
  3424. 'topicClass' => 'Jobs\Model\MTopic\Order\MCommissionOrder',
  3425. 'topicMethon' => 'updateBalance',
  3426. 'topicMethonParams' => [
  3427. 'Authorization' => $header['Authorization'],
  3428. 'Token' => $header['Token'],
  3429. 'orderId' => $id,
  3430. 'PROJECT_DOMAIN' => PROJECT_DOMAIN
  3431. ],
  3432. ];
  3433. $url = QIANNIAO_QUEUE . '/CAddJob/add';
  3434. $result = request($url, $postData);
  3435. $i++;
  3436. } while ($result['httpcode'] != 200 && $i <= 3);
  3437. // 计算用户积分 start
  3438. // 查询客户信息
  3439. $customerData = $this->objDCustomer->get($orderIndex['customerId']);
  3440. if ($customerData === false) {
  3441. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  3442. }
  3443. // 查询订单商品数据
  3444. $fix = ceil($orderIndex['userCenterId'] / $this->cutTable);
  3445. $this->objDOrderGoods->setTable('qianniao_order_goods_' . $this->onlineEnterpriseId . '_' . $fix);
  3446. $orderGoodsData = $this->objDOrderGoods->select(['deleteStatus'=>StatusCode::$standard,'orderId'=>$id]);
  3447. if ($orderGoodsData === false) {
  3448. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  3449. }
  3450. // 调用计算积分方法
  3451. $objMCustomer = new MCustomer($this->onlineEnterpriseId, $this->onlineUserId);
  3452. $result = $objMCustomer->addCustomerIntegralByOrder(0, $customerData, $orderData, $orderGoodsData);
  3453. if(!$result->isSuccess()){
  3454. return ResultWrapper::fail($result->getData(), $result->getErrorCode());
  3455. }
  3456. //调用计算提成方法
  3457. $objMStaff = new MStaff($this->onlineEnterpriseId, $this->onlineUserId);
  3458. $result = $objMStaff->addStaffRewardByOrder(0, $customerData, $orderData, $orderGoodsData);
  3459. if(!$result->isSuccess()){
  3460. return ResultWrapper::fail($result->getData(), $result->getErrorCode());
  3461. }
  3462. //订单完成商户结算金额
  3463. $objMMerchantSettlement = new MMerchantSettlement($this->onlineEnterpriseId, $this->onlineUserId);
  3464. $updateMerchantSettlement = $objMMerchantSettlement->updateMerchantSettlement(['orderId'=>$orderData['id']]);
  3465. if(!$updateMerchantSettlement->isSuccess()){
  3466. return ResultWrapper::fail($updateMerchantSettlement->getData(), $updateMerchantSettlement->getErrorCode());
  3467. }
  3468. //只有小程序微信支付订单才可以计算分佣
  3469. if(!empty($orderData) && $orderData["payAmount"]>0 && $orderData["payType"]==1 && $orderData["source"]==3){
  3470. $checkData = [
  3471. "parentPath"=>$customerData["parentPath"],
  3472. "payAmount"=>$orderData["payAmount"],
  3473. ];
  3474. // PartnerTools::addTask($orderData["id"], $this->onlineEnterpriseId,$checkData);
  3475. }
  3476. }
  3477. //取消订单
  3478. if ($selectParams['orderStatus'] == StatusCode::$orderStatus['close'] && !empty($header)) {
  3479. $i = 1;
  3480. do {
  3481. $postData = [
  3482. 'topicName' => 'MyJob',
  3483. 'topicClass' => 'Jobs\Model\MTopic\Order\MCommissionOrder',
  3484. 'topicMethon' => 'cancelSubCommission',
  3485. 'topicMethonParams' => [
  3486. 'Authorization' => $header['Authorization'],
  3487. 'Token' => $header['Token'],
  3488. 'orderId' => $id,
  3489. 'PROJECT_DOMAIN' => PROJECT_DOMAIN
  3490. ],
  3491. ];
  3492. $url = QIANNIAO_QUEUE . '/CAddJob/add';
  3493. $result = request($url, $postData);
  3494. $i++;
  3495. } while ($result['httpcode'] != 200 && $i <= 3);
  3496. }
  3497. /*
  3498. //ES更新
  3499. $_id = self::createEsDocumentId($id);
  3500. $this->objDOrder->esupdateTypeFieldVaule(['orderStatus' => $selectParams['orderStatus']], $_id);*/
  3501. $this->objDOrderIndex->commit();
  3502. return ResultWrapper::success('操作成功');
  3503. }
  3504. /**
  3505. * Doc: (des="取消订单解锁库存")
  3506. * User: XMing
  3507. * Date: 2020/7/14
  3508. * Time: 5:54 下午
  3509. * @param int $id 订单id
  3510. * @param array $params 订单数据
  3511. * @return ResultWrapper
  3512. */
  3513. private function unlockInventory(int $id, array $params)
  3514. {
  3515. //解锁库存
  3516. $objMInventory = new MInventory($this->onlineEnterpriseId, $this->onlineUserId);
  3517. $unlockResult = $objMInventory->unlockInventory([$id], StatusCode::$orderType['saleOrder'], $params['createTime']);
  3518. if (!$unlockResult->isSuccess()) {
  3519. //暂时关闭,没发现有锁定的地方
  3520. // return ResultWrapper::fail($unlockResult->getData(), ErrorCode::$dberror);
  3521. }
  3522. self::noticeStatistics([
  3523. 'userCenterId' => $this->onlineUserId,
  3524. 'enterpriseId' => $this->onlineEnterpriseId,
  3525. 'customerId' => $params['customerId'],
  3526. 'no' => $params['no'],
  3527. 'data' => $params,
  3528. 'noticeType' => 'close',//取消订单
  3529. ], 'MOrderStatistics');
  3530. //记录日志
  3531. parent::saveLog([
  3532. 'no' => $params['no'],
  3533. 'actionType' => '取消订单',
  3534. 'operationData' => '',
  3535. 'userCenterId' => $this->onlineUserId,
  3536. 'enterpriseId' => $this->onlineEnterpriseId,
  3537. 'createTime' => time(),
  3538. ]);
  3539. return ResultWrapper::success($unlockResult->getData());
  3540. }
  3541. /**
  3542. * Doc: (des="订单出库状态")
  3543. * User: XMing
  3544. * Date: 2020/12/28
  3545. * Time: 10:38 上午
  3546. * @param array $params
  3547. * @param array $where
  3548. * @param array $outInventoryMap
  3549. * @return ResultWrapper
  3550. * @throws \Exception
  3551. * @oaram $outInventoryMap
  3552. */
  3553. public function updateOutStatus(array $params,array $where,array $outInventoryMap): ResultWrapper
  3554. {
  3555. if (empty($where)) {
  3556. return ResultWrapper::fail('参数为空', ErrorCode::$paramError);
  3557. }
  3558. $orderIndex = $this->objDOrderIndex->get($where);
  3559. if ($orderIndex === false){
  3560. return ResultWrapper::fail($this->objDOrderIndex->error(),ErrorCode::$dberror);
  3561. }
  3562. if (empty($orderIndex)){
  3563. return ResultWrapper::fail('未获取到指定的订单信息',ErrorCode::$paramError);
  3564. }
  3565. $orderId = getArrayItem($orderIndex,'id',0);
  3566. $fix = ceil($orderIndex['userCenterId'] / $this->cutTable);
  3567. $this->objDOrder->setTable('qianniao_order_'.$this->onlineEnterpriseId.'_'.$fix);
  3568. $this->objDOrderGoods->setTable('qianniao_order_goods_'.$this->onlineEnterpriseId.'_'.$fix);
  3569. $this->objDOrderIndex->beginTransaction();
  3570. foreach ($outInventoryMap as $skuId => $outNum){
  3571. $row = $this->objDOrderGoods->get(['orderId' => $orderId, 'skuId' => $skuId, 'deleteStatus' => StatusCode::$standard]);
  3572. if ($row === false){
  3573. $this->objDOrderIndex->rollback();
  3574. return ResultWrapper::fail($this->objDOrderGoods->error(),ErrorCode::$dberror);
  3575. }
  3576. $update = [
  3577. 'outNum' => bcadd($row['outNum'],$outNum,2),
  3578. 'outOfNum' => bcsub($row['outOfNum'],$outNum,2),
  3579. 'updateTime' => time(),
  3580. ];
  3581. if ($update['outOfNum'] < 0){
  3582. Logger::logs(E_USER_ERROR,'企业:'.$this->onlineEnterpriseId.' 订单:'.$orderId.' 出库数量异常',__CLASS__,__LINE__,$row);
  3583. $this->objDOrderIndex->rollback();
  3584. return ResultWrapper::fail('出库数量异常',ErrorCode::$paramError);
  3585. }
  3586. $updateGoodsResult = $this->objDOrderGoods->update($update,['id' => $row['id']]);
  3587. if ($updateGoodsResult === false){
  3588. Logger::logs(E_USER_ERROR,'sql error',__CLASS__,__LINE__,$this->objDOrderGoods->error());
  3589. $this->objDOrderIndex->rollback();
  3590. return ResultWrapper::fail($this->objDOrderGoods->error(),ErrorCode::$paramError);
  3591. }
  3592. }
  3593. $outStatusResult = self::checkStockOutStatus($orderId);
  3594. if (!$outStatusResult->isSuccess()){
  3595. $this->objDOrderIndex->rollback();
  3596. return ResultWrapper::fail($outStatusResult->getData(),$outStatusResult->getErrorCode());
  3597. }
  3598. $outStatus = (int)$outStatusResult->getData();
  3599. $params['outStatus'] = $outStatus;//出库状态
  3600. $updateIndex = $this->objDOrderIndex->update($params,$orderId);
  3601. if ($updateIndex === false){
  3602. $this->objDOrderIndex->rollback();
  3603. return ResultWrapper::fail($this->objDOrderIndex->error(),ErrorCode::$dberror);
  3604. }
  3605. $updateOrder = $this->objDOrder->update($params,$orderId);
  3606. if ($updateOrder === false){
  3607. $this->objDOrderIndex->rollback();
  3608. return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror);
  3609. }
  3610. /*
  3611. $_id = self::createEsDocumentId($orderId);
  3612. $this->objDOrder->esupdateTypeFieldVaule($params, $_id);*/
  3613. $this->objDOrderIndex->commit();
  3614. return ResultWrapper::success($orderId);
  3615. }
  3616. /**
  3617. * Doc: (des="返回订单的出库")
  3618. * User: XMing
  3619. * Date: 2021/3/10
  3620. * Time: 10:35 上午
  3621. * @param int $orderId
  3622. * @return ResultWrapper
  3623. */
  3624. public function checkStockOutStatus(int $orderId): ResultWrapper
  3625. {
  3626. //检测是否都已经出库
  3627. $lists = $this->objDOrderGoods->select(['orderId' => $orderId,'deleteStatus' => StatusCode::$standard]);
  3628. if ($lists === false){
  3629. Logger::logs(E_USER_ERROR,'sql error',__CLASS__,__LINE__,$this->objDOrderGoods->error());
  3630. return ResultWrapper::fail($this->objDOrderGoods->error(),ErrorCode::$dberror);
  3631. }
  3632. if (empty($lists)){
  3633. return ResultWrapper::fail('订单商品获取失败',ErrorCode::$paramError);
  3634. }
  3635. foreach ($lists as $item){
  3636. if ($item['outOfNum'] > 0){
  3637. //还有未出库商品
  3638. return ResultWrapper::success(6);
  3639. }
  3640. }
  3641. return ResultWrapper::success(5);
  3642. }
  3643. /**
  3644. * Doc: (des="修改订单的支付状态")
  3645. * User: XMing
  3646. * Date: 2020/7/14
  3647. * Time: 5:18 下午
  3648. * @param $orderData
  3649. * @param $condition
  3650. * @param bool $isNotify
  3651. * @return ResultWrapper
  3652. * @throws \Exception
  3653. */
  3654. public function updateOrderPayData($orderData, $condition, $isNotify = false): ResultWrapper
  3655. {
  3656. $total_fel = 0;
  3657. if ($isNotify) {
  3658. $total_fel = $orderData['total_fel'];
  3659. unset($orderData['total_fel']);
  3660. }
  3661. if (isset($orderData['pay_way'])) {
  3662. $pay_way = $orderData['pay_way'];
  3663. unset($orderData['pay_way']);
  3664. }
  3665. // 查询订单数据
  3666. $orderInfoData = $this->objDOrder->select($condition);
  3667. if (empty($orderInfoData)) {
  3668. return ResultWrapper::fail('查询订单数据为空', ErrorCode::$paramError);
  3669. }
  3670. if ($orderInfoData === false) {
  3671. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  3672. }
  3673. // 回调通知判断订单是否已经修改过订单状态
  3674. if ($isNotify == true && $orderInfoData[0]['payStatus'] == StatusCode::$standard) {
  3675. return ResultWrapper::fail('支付状态已经修改过了', ErrorCode::$notAllowAccess);
  3676. }
  3677. $this->objDOrder->beginTransaction();
  3678. // 如果之前是组合支付方式,修改支付方式的时候不能直接修改
  3679. if( in_array(StatusCode::$payType['balance'], explode(',', $orderInfoData[0]['payType'])) ){
  3680. $orderData['payType'] = $orderData['payType'].','.StatusCode::$payType['balance'];
  3681. $orderData['notPayMoney'] = bcsub($orderData['notPayMoney'], $orderData['total_fel'], 2);
  3682. }
  3683. $dbResult = $this->objDOrder->update($orderData, $condition);
  3684. if ($dbResult === false) {
  3685. $this->objDOrder->rollBack();
  3686. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  3687. }
  3688. unset($dbResult);
  3689. if (!isset($condition['id'])) {
  3690. //查询订单id
  3691. $dbResult = $this->objDOrder->get($condition, 'id');
  3692. if ($dbResult === false) {
  3693. $this->objDOrder->rollBack();
  3694. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  3695. }
  3696. if (empty($dbResult) || !isset($dbResult['id'])) {
  3697. $this->objDOrder->rollBack();
  3698. return ResultWrapper::fail('订单数据为空', ErrorCode::$dberror);
  3699. }
  3700. $condition['id'][] = $dbResult['id'];
  3701. unset($dbResult);
  3702. }
  3703. unset($orderData['notPayMoney']);
  3704. $dbResult = self::updateOrderIndex($orderData, $condition);
  3705. if (!$dbResult->isSuccess()) {
  3706. $this->objDOrder->rollBack();
  3707. return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror);
  3708. }
  3709. if (!is_array($condition['id'])){
  3710. $condition['id'] = [$condition['id']];
  3711. }
  3712. /*
  3713. foreach ($condition['id'] as $key => $value) {
  3714. $_id = self::createEsDocumentId($value);
  3715. $this->objDOrder->esupdateTypeFieldVaule($orderData, $_id);
  3716. }*/
  3717. //线上支付生成收款单$orderData['payStatus'] $condition['id'] 支付完成后回调这两个有值
  3718. if (isset($pay_way) && isset($orderData['payStatus']) && isset($condition['id'])) {
  3719. if ($orderData['payStatus'] == StatusCode::$standard) {
  3720. //拿到微信默认账户
  3721. $defaultAccountResult = $this->objMAccount->getDefaultAccount($pay_way);
  3722. if ($defaultAccountResult->isSuccess() == false) {
  3723. $this->objDOrder->rollBack();
  3724. return ResultWrapper::fail($defaultAccountResult->getData(), $defaultAccountResult->getErrorCode());
  3725. }
  3726. $defaultAccount = $defaultAccountResult->getData();
  3727. if(empty($defaultAccount)){
  3728. return ResultWrapper::fail('支付方式对应的银行账户为空', ErrorCode::$contentNotExists);
  3729. }
  3730. foreach ($orderInfoData as $orderInfo) {
  3731. // 组合支付,收款单金额重新计算
  3732. if( in_array(StatusCode::$payType['balance'], explode(',', $orderInfoData[0]['payType'])) ){
  3733. $orderInfo['extends'] = json_decode($orderInfo['extends'], true);
  3734. if( isset($orderInfo['extends']['admixPayData']) ){
  3735. foreach ($orderInfo['extends']['admixPayData'] as $key => $value){
  3736. if($value['payType'] == StatusCode::$payType['wxPay']){
  3737. $orderInfo['payAmount'] = $value['payMoney'];
  3738. }
  3739. }
  3740. }
  3741. }
  3742. //循环订单数据,拼接生成收款单
  3743. $receivedData = [
  3744. 'customerId' => $orderInfo['customerId'],
  3745. 'customerName' => $orderInfo['customerName'],
  3746. 'currentAccountName' => $orderInfo['shopName'],
  3747. 'financeType' => '线上支付收款',
  3748. 'financeTypeId' => StatusCode::$systemFinanceType['saleReceipt'],
  3749. 'shopId' => $orderInfo['shopId'],
  3750. 'shopName' => $orderInfo['shopName'],
  3751. 'receiptTime' => time(),
  3752. 'operatorId' => 0,
  3753. 'originId' => $orderInfo['id'],
  3754. 'originNo' => $orderInfo['no'],
  3755. 'sourceId' => $orderInfo['id'],
  3756. 'sourceNo' => $orderInfo['no'],
  3757. 'sourceNoMoney' => $orderInfo['payAmount'],
  3758. 'auditStatus' => StatusCode::$auditStatus['auditing'],
  3759. 'offsetMoney' => 0,
  3760. 'notOffsetMoney' => 0,
  3761. 'offsetStatus' => StatusCode::$delete,
  3762. 'createTime' => time(),
  3763. 'updateTime' => time(),
  3764. 'accountList' => [
  3765. [
  3766. "accountId" => isset($defaultAccount['id']) ? $defaultAccount['id'] : 0,
  3767. "accountNumber" => isset($defaultAccount['accountNumber']) ? $defaultAccount['accountNumber'] : '请设置默认的收款账户',
  3768. "money" => $orderInfo['payAmount'],
  3769. "discountMoney" => 0,
  3770. "finalMoney" => $orderInfo['payAmount'],
  3771. "payWay" => isset($pay_way) ? $pay_way . "支付" : '在线支付',
  3772. "remark" => "在线支付自动生成收款单"
  3773. ]
  3774. ],
  3775. ];
  3776. $result = $this->objMReceived->addReceived($receivedData, true);
  3777. if ($result->isSuccess() == false) {
  3778. $this->objDOrder->rollBack();
  3779. return ResultWrapper::fail($result->getData(), $result->getErrorCode());
  3780. }
  3781. // 微信生成的收款单自动审核
  3782. if( in_array(StatusCode::$payType['wxPay'], explode(',', $orderInfoData[0]['payType'])) ){
  3783. $updateReceived = $this->objMReceived->updateReceivedStatus(['id'=>$result->getData(),'createTime'=>time()]);
  3784. if (!$updateReceived->isSuccess()) {
  3785. $this->objDOrder->rollBack();
  3786. return ResultWrapper::fail($updateReceived->getData(), $updateReceived->getErrorCode());
  3787. }
  3788. }
  3789. unset($receivedData);
  3790. unset($result);
  3791. }
  3792. }
  3793. }
  3794. if ($isNotify) {
  3795. self::runProcessNextAudit($condition['id']);
  3796. $objMCustomer = new MCustomer($this->onlineEnterpriseId, $this->onlineUserId);
  3797. $customer = $objMCustomer->getCustomerInfoByUserCenterId($this->onlineUserId);
  3798. if (!$customer->isSuccess()) {
  3799. return ResultWrapper::fail($customer->getData(), $customer->getErrorCode());
  3800. }
  3801. $customer = $customer->getData();
  3802. parent::coupon([
  3803. 'userCenterId' => $this->onlineUserId,
  3804. 'enterpriseId' => $this->onlineEnterpriseId,
  3805. 'customerId' => isset($customer['id']) ? $customer['id'] : '',
  3806. 'payAmount' => isset($total_fel) ? $total_fel : 0,
  3807. ], 'MOnlinePayCoupon');
  3808. $objCustomerCache = new CustomerCache();
  3809. $objCustomerCache->delInterestCustomerAfterPay($customer['id'], $this->onlineEnterpriseId);
  3810. if (isset($customer['openId']) && !empty($customer['openId'])) {
  3811. /* $payment = '';
  3812. //判断支付方式
  3813. switch ($orderInfoData[0]['payType']) {
  3814. case StatusCode::$payType['wxPay']:
  3815. $payment = StatusCode::$payType[1];
  3816. break;
  3817. case StatusCode::$payType['balance']:
  3818. $payment = StatusCode::$payType[7];
  3819. break;
  3820. case StatusCode::$payType['cashPay']:
  3821. $payment = StatusCode::$payType[3];
  3822. break;
  3823. case StatusCode::$payType['bankLoans']:
  3824. $payment = StatusCode::$payType[4];
  3825. break;
  3826. }
  3827. $orderInfoData[0]['extends'] = json_decode($orderInfoData[0]['extends'], true);
  3828. if (isset($orderInfoData[0]['extends']['admixPayData'])) {
  3829. $payment = '组合支付';
  3830. }*/
  3831. // 发送小程序订阅消息
  3832. $sendMessageData = [
  3833. 'character_string3' => ['value' => StatusCode::$noPrefix[1] . '-' . $orderInfoData[0]['no']], // 订单编号
  3834. 'date10' => ['value' => date('Y-m-d H:i:s', $orderInfoData[0]['createTime'])], // 下单时间
  3835. 'time4' => ['value' => date('Y-m-d H:i:s', time())], // 支付时间
  3836. 'thing7' => ['value' => '微信支付'], // 支付方式
  3837. 'name8' => ['value' => substr($orderInfoData[0]['shopName'],0,30)] // 商家名称
  3838. ];
  3839. $objMSystemPushMessage = new MSystemPushMessage($this->onlineUserId, $this->onlineEnterpriseId);
  3840. $result = $objMSystemPushMessage->sendWeiXinPushMessage(3, $customer['openId'], $sendMessageData);
  3841. if (!$result->isSuccess()) {
  3842. 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);
  3843. }
  3844. }
  3845. }
  3846. $this->objDOrder->commit();
  3847. $objMMerchantFlow = new MMerchantFlow($this->onlineEnterpriseId,$this->onlineUserId);
  3848. if ($isNotify == true || $orderData['payStatus'] == StatusCode::$standard){
  3849. foreach ($condition['id'] as $key => $id) {
  3850. $objMMerchantFlow->calculation($id);
  3851. }
  3852. }
  3853. return ResultWrapper::success('操作成功');
  3854. }
  3855. /**
  3856. * 更新索引表订单状态,支付状态,支付方式
  3857. * @param $orderData
  3858. * @param $params
  3859. * @return ResultWrapper
  3860. * @throws \Exception
  3861. */
  3862. private function updateOrderIndex($orderData, $params)
  3863. {
  3864. $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId);
  3865. $updateData = [];
  3866. isset($orderData['payType']) && $updateData['payType'] = $orderData['payType'];
  3867. isset($orderData['payStatus']) && $updateData['payStatus'] = $orderData['payStatus'];
  3868. isset($orderData['orderStatus']) && $updateData['orderStatus'] = $orderData['orderStatus'];
  3869. isset($orderData['outStatus']) && $updateData['outStatus'] = $orderData['outStatus'];
  3870. $where['id'] = $params['id'];
  3871. $dbResult = $this->objDOrderIndex->update($updateData, $where);
  3872. if ($dbResult === false) {
  3873. return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
  3874. }
  3875. return ResultWrapper::success($dbResult);
  3876. }
  3877. /**
  3878. * 格式化返回数据
  3879. * @param $data
  3880. * @return array
  3881. * @throws \Exception
  3882. * @return ResultWrapper
  3883. */
  3884. private function format($data): ResultWrapper
  3885. {
  3886. // 提取所有订单id
  3887. $allOrderIds = [];
  3888. $allShopIds = [];
  3889. $allOrderNo = [];
  3890. $customerIds = [];
  3891. $allCustomerTypeIds = [];
  3892. if (isset($data['id'])) {
  3893. $dimension = $data;
  3894. unset($data);
  3895. $data[] = $dimension;
  3896. }
  3897. foreach ($data as $key => $value) {
  3898. $allOrderNo[] = $value['no'];
  3899. $allOrderIds[] = $value['id'];
  3900. $allShopIds[] = $value['shopId'];
  3901. $allCustomerTypeIds = $value['customerType'];
  3902. $customerIds[] = $value['customerId'];
  3903. $this->onlineUserId = $value['userCenterId'];
  3904. if ($value['auditStatus'] == StatusCode::$auditStatus['auditing']) {
  3905. $data[$key]['orderMsg'] = '待审核';
  3906. }
  3907. if ($value['auditStatus'] == StatusCode::$auditStatus['auditPass']) {
  3908. $data[$key]['orderMsg'] = '待出库';
  3909. if ($value['orderStatus'] == StatusCode::$orderStatus['waitReceive']) {
  3910. $data[$key]['orderMsg'] = '已出库';
  3911. if ($value['outStatus'] == 6 && $value['isRet'] != StatusCode::$standard){
  3912. $data[$key]['orderMsg'] = '部分出库';
  3913. }
  3914. }
  3915. if ($value['orderStatus'] == StatusCode::$orderStatus['finish']) {
  3916. $data[$key]['orderMsg'] = '已完成';
  3917. }
  3918. }
  3919. switch ($value['orderStatus']){
  3920. case StatusCode::$orderStatus['close']:
  3921. $data[$key]['orderMsg'] = '已关闭';
  3922. break;
  3923. case StatusCode::$orderStatus['cancelIng'];
  3924. $data[$key]['orderMsg'] = '待取消';
  3925. break;
  3926. }
  3927. if (isset($value['payType'])) {
  3928. $data[$key]['payTypeMsg'] = isset(StatusCode::$payType[$value['payType']]) ? StatusCode::$payType[$value['payType']] : '';
  3929. }
  3930. }
  3931. //获取客户类型
  3932. $customerTypeMap = [];
  3933. if (!empty($allCustomerTypeIds)) {
  3934. $objDCustomerSource = new DCustomerSource();
  3935. $customerSourceLists = $objDCustomerSource->select(['id' => $allCustomerTypeIds], 'id,name');
  3936. if ($customerSourceLists != false) {
  3937. foreach ($customerSourceLists as $val) {
  3938. $customerTypeMap[$val['id']] = $val['name'];
  3939. }
  3940. }
  3941. }
  3942. //获取店铺信息
  3943. $objMShop = new MShop($this->onlineEnterpriseId, $this->onlineUserId);
  3944. $shopData = $objMShop->getShopName($allShopIds);
  3945. /********************************订单商品 start****************************/
  3946. $objMOrderGoods = new MOrderGoods($this->onlineUserId, $this->onlineEnterpriseId);
  3947. $dbResult = $objMOrderGoods->getOrderGoodsByOrderIds(['orderId' => $allOrderIds, 'deleteStatus' => StatusCode::$standard]);
  3948. $orderGoodsData = [];//订单商品信息
  3949. if (!$dbResult->isSuccess()) {
  3950. return ResultWrapper::fail($dbResult->getData(),$dbResult->getErrorCode());
  3951. }
  3952. $orderGoodsData = $dbResult->getData();
  3953. unset($dbResult);
  3954. //查询sku信息
  3955. $objMSku = new MSku($this->onlineUserId, $this->onlineEnterpriseId);
  3956. //查询商品数据
  3957. $allGoodsIds = array_unique(array_column($orderGoodsData, 'goodsId'));
  3958. $allGoodsBasicIds = array_unique(array_column($orderGoodsData, 'goodsBasicId'));
  3959. $objMGoods = new MGoods($this->onlineEnterpriseId, false, $this->onlineUserId);
  3960. $goodsData = $objMGoods->getGoodsNames($allGoodsIds);
  3961. //获取商品的库存
  3962. $inventorySelectParams = [];
  3963. $objMInventory = new MInventory($this->onlineEnterpriseId, '');
  3964. foreach ($orderGoodsData as $item){
  3965. $inventorySelectParams[$item['shopId']][] = $item['skuId'];
  3966. }
  3967. $inventoryMap = [];
  3968. foreach ($inventorySelectParams as $shopId => $skuIds){
  3969. $inventoryResult = $objMInventory->getInventoryByShopIdAndSkuIds($shopId,$skuIds);
  3970. if (!$inventoryResult->isSuccess()) {
  3971. return ResultWrapper::fail($inventoryResult->getData(),$inventoryResult->getErrorCode());
  3972. }
  3973. $inventoryMap[$shopId] = $inventoryResult->getData();
  3974. }
  3975. //sku信息
  3976. $skuResult = $objMSku->getSpecNameBySkuId(array_column($orderGoodsData, 'skuId'));
  3977. if (!$skuResult->isSuccess()) {
  3978. return ResultWrapper::fail($skuResult->getData(),$skuResult->getErrorCode());
  3979. }
  3980. $allSku = $skuResult->getData();
  3981. $goods = [];
  3982. $allSkuIds = [];
  3983. foreach ($orderGoodsData as $val){
  3984. if (!in_array($val['skuId'],$allSkuIds)){
  3985. $allSkuIds[] = $val['skuId'];
  3986. }
  3987. }
  3988. foreach ($orderGoodsData as $key => &$value) {
  3989. $value['isNew'] = isset($allSku[$value['skuId']]['isNew']) ? $allSku[$value['skuId']]['isNew'] : StatusCode::$delete;
  3990. $value['barCode'] = isset($allSku[$value['skuId']]['barCode']) ? $allSku[$value['skuId']]['barCode'] : '';
  3991. $value['unitName'] = isset($allSku[$value['skuId']]['unitName']) ? $allSku[$value['skuId']]['unitName'] : '';
  3992. $value['specGroup'] = isset($allSku[$value['skuId']]['specGroup']) ? $allSku[$value['skuId']]['specGroup'] : [];
  3993. $value['images'] = isset($goodsData[$value['goodsId']]['images']) ? json_decode($goodsData[$value['goodsId']]['images'], true) : '';
  3994. $value['returnPrice'] = bcdiv(bcsub(bcsub($value['totalMoney'], $value['preferential']), $value['vipDiscount']), $value['buyNum']);
  3995. $value['isMater'] = isset($allSku[$value['skuId']]['isMaster']) ? $allSku[$value['skuId']]['isMaster'] : StatusCode::$delete;
  3996. $value['conversion'] = isset($allSku[$value['skuId']]['conversion']) ? $allSku[$value['skuId']]['conversion'] : 0;
  3997. $value['inventory'] = isset($inventoryMap[$value['shopId']][$value['skuId']]['num']) ? $inventoryMap[$value['shopId']][$value['skuId']]['num'] : 0;
  3998. // 处理订单商品表扩展字段
  3999. if( !empty($value['extends']) ){
  4000. $extends = json_decode($value['extends'], true);
  4001. if(!empty($extends)){
  4002. foreach($extends as $keys => $item){
  4003. $value[$keys] = $item;
  4004. }
  4005. }
  4006. }
  4007. $allOrderGoodsData[$value['orderId']][] = $value;
  4008. if (!isset($goods[$value['orderId']]['goodsPreferential'])) {
  4009. $goods[$value['orderId']]['goodsPreferential'] = 0;
  4010. }
  4011. $goods[$value['orderId']]['goodsPreferential'] = bcadd($goods[$value['orderId']]['goodsPreferential'], bcmul($value['preferential'], $value['buyNum']), 2);
  4012. }
  4013. unset($dbResult);
  4014. /********************************收货信息 start******************************/
  4015. $objMOrderReceive = new MOrderReceive($this->onlineUserId, $this->onlineEnterpriseId);
  4016. $dbResult = $objMOrderReceive->getOrderReceiveByOrderIds(['orderId' => $allOrderIds]);
  4017. $orderReceiveData = [];//订单收货信息
  4018. if (!$dbResult->isSuccess()) {
  4019. return ResultWrapper::fail($dbResult->getData(),$dbResult->getErrorCode());
  4020. }
  4021. $orderReceiveData = self::formatSysArea($dbResult->getData());
  4022. foreach ($orderReceiveData as $key => $value) {
  4023. $allOrderReceiveData[$value['orderId']] = $value;
  4024. }
  4025. unset($dbResult);
  4026. /*********************************订单操作记录*********************************/
  4027. $objMOrderLog = new MOrderLog($this->onlineEnterpriseId);
  4028. $orderLog = $objMOrderLog->getOrderLog(['no' => $allOrderNo]);
  4029. /**********************************获取基本配置*********************************/
  4030. $objMBasicSetup = new MBasicSetup($this->onlineEnterpriseId);
  4031. $setupResult = $objMBasicSetup->getBasicField('allowReturnDay');
  4032. if (!$setupResult->isSuccess()) {
  4033. return ResultWrapper::fail($setupResult->getData(),$setupResult->getErrorCode());
  4034. }
  4035. $setupResult = $setupResult->getData();
  4036. $allowReturnDay = empty($setupResult['allowReturnDay']) ? 0 : $setupResult['allowReturnDay'];
  4037. /********************************映射数据 start******************************/
  4038. $nowTime = time();
  4039. foreach ($data as $key => $value) {
  4040. $data[$key]['no'] = StatusCode::$noPrefix[1].'-'.$value['no'];
  4041. $data[$key]['extends'] = !empty($value['extends']) ? json_decode($value['extends'], true) : (object)[];
  4042. $data[$key]['goodsData'] = isset($allOrderGoodsData[$value['id']]) ? $allOrderGoodsData[$value['id']] : [];
  4043. $data[$key]['receiveData'] = isset($allOrderReceiveData[$value['id']]) ? $allOrderReceiveData[$value['id']] : [];
  4044. $data[$key]['deliveryNo'] = isset($value['deliveryNo']) ? $value['deliveryNo'] : '';
  4045. $data[$key]['payAmount'] = bcsub($value['payAmount'],$value['retMoney'],2);
  4046. $data[$key]['expressMoney'] = isset($value['expressMoney']) ? $value['expressMoney'] : '';
  4047. $data[$key]['expressName'] = isset($value['expressName']) ? $value['expressName'] : '';
  4048. $data[$key]['deliveryName'] = isset(StatusCode::$deliveryType[$value['deliveryType']]) ? StatusCode::$deliveryType[$value['deliveryType']] : '';//配送方式名称
  4049. $data[$key]['orderPreferential'] = bcsub($data[$key]['totalMoney'], bcsub($data[$key]['payAmount'], $data[$key]['expressMoney'], 2), 2);//订单优惠
  4050. $data[$key]['goodsPreferential'] = isset($goods[$value['id']]['goodsPreferential']) ? $goods[$value['id']]['goodsPreferential'] : '';//商品优惠
  4051. $data[$key]['coupon'] = '0.00';
  4052. $data[$key]['salesman'] = $value['salesManName'];
  4053. $data[$key]['shopName'] = isset($shopData[$value['shopId']]['name']) ? $shopData[$value['shopId']]['name'] : '';
  4054. $data[$key]['shopLogo'] = isset($shopData[$value['shopId']]['logo']) ? $shopData[$value['shopId']]['logo'] : '';
  4055. $data[$key]['orderLog'] = isset($orderLog[$value['no']]) ? $orderLog[$value['no']] : [];
  4056. $data[$key]['allowReturn'] = StatusCode::$standard;//允许退货
  4057. if ($allowReturnDay == 0) {
  4058. //TODO(没有设置可退货时间,默认都可以退)
  4059. $data[$key]['allowReturn'] = StatusCode::$standard;//允许退货
  4060. } else {
  4061. $expire = ($allowReturnDay * 86400) + $value['successFullyTime'];
  4062. if ($nowTime > $expire) {
  4063. $data[$key]['allowReturn'] = StatusCode::$delete;//不允许退货
  4064. }
  4065. }
  4066. $data[$key]['allowReturnDay'] = $allowReturnDay;
  4067. if ($value['source'] == StatusCode::$source['manage']){
  4068. $data[$key]['orderPreferential'] = isset($value['totalReduceMoney']) ? $value['totalReduceMoney'] : 0;
  4069. }else{
  4070. $data[$key]['orderPreferential'] = bcsub($value['totalMoney'], bcsub($value['payAmount'], $value['expressMoney'], 2), 2);//订单总优惠
  4071. }
  4072. $data[$key]['paidAmount'] = $value['payStatus'] == StatusCode::$standard ? $value['payAmount'] : '0';//已付款金额
  4073. $data[$key]['customerTypeName'] = isset($customerTypeMap[$value['customerType']]) ? $customerTypeMap[$value['customerType']] : '';
  4074. $data[$key]['cashierName'] = $value['cashierName'];
  4075. $data[$key]['customerMobile'] = $value['customerMobile'];//客户手机号码
  4076. $data[$key]['guideName'] = $value['guideName'];
  4077. $data[$key]['changeAmount'] = $value['changeSubMoney'];
  4078. $data[$key]['accountList'] = empty($value['accountList']) ? [] : json_decode($value['accountList'], true);
  4079. $data[$key]['receivedName'] = isset($allOrderReceiveData[$value['id']]['realName']) ? $allOrderReceiveData[$value['id']]['realName'] : '';//收货人
  4080. $data[$key]['receivedMobile'] = isset($allOrderReceiveData[$value['id']]['mobile']) ? $allOrderReceiveData[$value['id']]['mobile'] : '';//收货电话
  4081. $data[$key]['reservoir'] = !empty($value['reservoir']) ? json_decode($value['reservoir'],true) : [];
  4082. //$data[$key]['selfRuleData'] = empty($value['selfRuleData']) ? (object)[] : json_decode($value['selfRuleData'],true);
  4083. }
  4084. $data = array_shift($data);
  4085. if ($this->isFront === false) {
  4086. $data['expressData'] = (object)[];
  4087. if ($data['deliveryType'] == StatusCode::$deliveryType['goodsDelivery'] && $data['deliveryNo']) {
  4088. $expressResult = self::getExpressInfoByOrderId($data['id']);
  4089. if ($expressResult->isSuccess()) {
  4090. $data['expressData'] = $expressResult->getData();
  4091. }
  4092. }
  4093. }
  4094. return ResultWrapper::success($data);
  4095. }
  4096. /**
  4097. * 地区
  4098. * @param $data
  4099. * @return mixed
  4100. */
  4101. public function formatSysArea($data)
  4102. {
  4103. if (empty($data)) {
  4104. return $data;
  4105. }
  4106. $objMSysAreaChina = new MSysAreaChina();
  4107. foreach ($data as $key => $val) {
  4108. if (isset($val['provinceCode']) && isset($val['cityCode']) && isset($val['districtCode'])) {
  4109. $areaName = $objMSysAreaChina->getNameByCode([
  4110. $val['provinceCode'],
  4111. $val['cityCode'],
  4112. $val['districtCode']
  4113. ]);
  4114. $data[$key]['area']['provinceName'] = isset($areaName[$val['provinceCode']]) ? $areaName[$val['provinceCode']] : '';
  4115. $data[$key]['area']['cityName'] = isset($areaName[$val['cityCode']]) ? $areaName[$val['cityCode']] : '';
  4116. $data[$key]['area']['districtName'] = isset($areaName[$val['districtCode']]) ? $areaName[$val['districtCode']] : '';
  4117. }
  4118. }
  4119. return $data;
  4120. }
  4121. /**
  4122. * 查询订单
  4123. * 全部 {"page": 1,"pageSize": 10,"orderStatus": 0}
  4124. * 待付款 {"page": 1,"pageSize": 10,"orderStatus": 2}
  4125. * 待发货 {"page": 1,"pageSize": 10,"orderStatus": 3}
  4126. * 待收货 {"page": 1,"pageSize": 10,"orderStatus": 4}
  4127. * @param $selectParams
  4128. * @return ResultWrapper
  4129. * @throws \Exception
  4130. */
  4131. public function getOrderSelect($selectParams)
  4132. {
  4133. $limit = $selectParams['limit'];
  4134. unset($selectParams['limit']);
  4135. $offset = $selectParams['offset'];
  4136. unset($selectParams['offset']);
  4137. unset($selectParams['page']);
  4138. unset($selectParams['pageSize']);
  4139. $objMCustomer = new MCustomer($this->onlineEnterpriseId, $this->onlineUserId);
  4140. $customerId = $objMCustomer->getCustomerIdByUserCenterId($this->onlineUserId);
  4141. if (empty($customerId)) {
  4142. return ResultWrapper::fail('没有找到客户信息', ErrorCode::$paramError);
  4143. }
  4144. $selectParams['customerId'] = $customerId;
  4145. $selectParams['deleteStatus'] = StatusCode::$standard;
  4146. $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);
  4147. if ($dbResult === false) {
  4148. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  4149. }
  4150. $total = $this->objDOrder->count($selectParams);
  4151. $return = [
  4152. 'data' => self::formatAndGoods($dbResult),
  4153. 'total' => ($total) ? intval($total) : 0,
  4154. ];
  4155. return ResultWrapper::success($return);
  4156. }
  4157. /**
  4158. * 格式化商品数据
  4159. *
  4160. * @param $data
  4161. * @return mixed
  4162. * @throws \Exception
  4163. */
  4164. private function formatAndGoods($data)
  4165. {
  4166. $allOrderIds = [];
  4167. $allShopIds = [];
  4168. foreach ($data as $key => $value) {
  4169. $allShopIds[] = $value['shopId'];
  4170. $allOrderIds[] = $value['id'];
  4171. }
  4172. $objMOrderGoods = new MOrderGoods($this->onlineUserId, $this->onlineEnterpriseId);
  4173. $selectParams = [
  4174. 'orderId' => $allOrderIds,
  4175. 'deleteStatus' => StatusCode::$standard,
  4176. ];
  4177. $dbResult = $objMOrderGoods->getOrderGoodsByOrderIds($selectParams);
  4178. $orderGoodsData = [];//订单商品信息
  4179. if ($dbResult->isSuccess()) {
  4180. $orderGoodsData = $dbResult->getData();
  4181. }
  4182. $allGoodsIds = array_unique(array_column($orderGoodsData, 'goodsId'));
  4183. unset($dbResult);
  4184. $objMGoods = new MGoods($this->onlineEnterpriseId, false, $this->onlineUserId);
  4185. $goodsData = $objMGoods->getGoodsNames($allGoodsIds);
  4186. if (empty($goodsData)) {
  4187. return $data;
  4188. }
  4189. $allOrderGoodsData = [];
  4190. foreach ($orderGoodsData as $key => &$value) {
  4191. $value['extends'] = !empty($value['extends']) ? json_decode($value['extends'], true) : [];
  4192. $value['images'] = isset($goodsData[$value['goodsId']]['images']) ? json_decode($goodsData[$value['goodsId']]['images'], true) : '';
  4193. // 如果是抄码商品,订单商品购买数量按照件算
  4194. if( $value['isEq'] == StatusCode::$standard){
  4195. $value['buyNum'] = isset($value['extends']['u_1_buy']) ? $value['extends']['u_1_buy'] : $value['buyNum'];
  4196. }
  4197. $allOrderGoodsData[$value['orderId']][] = $value;
  4198. }
  4199. $objMShop = new MShop($this->onlineEnterpriseId, $this->onlineUserId);
  4200. $shopData = $objMShop->getShopName($allShopIds);
  4201. foreach ($data as $key => $val) {
  4202. $data[$key]['deliveryTypeMsg'] = isset(StatusCode::$deliveryType[$val['deliveryType']]) ? StatusCode::$deliveryType[$val['deliveryType']] : '';
  4203. $data[$key]['goodsNum'] = isset($allOrderGoodsData[$val['id']]) ? array_sum(array_column($allOrderGoodsData[$val['id']], 'buyNum')) : '';
  4204. $data[$key]['shopName'] = isset($shopData[$val['shopId']]['name']) ? $shopData[$val['shopId']]['name'] : '';
  4205. $data[$key]['shopLogo'] = isset($shopData[$val['shopId']]['logo']) ? $shopData[$val['shopId']]['logo'] : '';
  4206. $data[$key]['goodsData'] = isset($allOrderGoodsData[$val['id']]) ? array_values($allOrderGoodsData[$val['id']]) : '';
  4207. }
  4208. return $data;
  4209. }
  4210. /**
  4211. * Doc: (des="订单检索条件")
  4212. * User: XMing
  4213. * Date: 2020/7/11
  4214. * Time: 9:48 上午
  4215. * @param $selectParams
  4216. * @param bool $is_export
  4217. * @return ResultWrapper
  4218. * @throws \Exception
  4219. */
  4220. public function search($selectParams, $is_export = false)
  4221. {
  4222. $defaultDSL = [
  4223. 'sort' => [
  4224. 'createTime' => [
  4225. 'order' => 'desc'
  4226. ],
  4227. ],
  4228. ];
  4229. if ($is_export === false) {
  4230. $defaultDSL['from'] = $selectParams['offset'];
  4231. $defaultDSL['size'] = $selectParams['limit'];
  4232. }
  4233. $dsl = [];
  4234. $dsl['query']['bool']['must'][] = [
  4235. 'term' => ['enterpriseId' => $this->onlineEnterpriseId],
  4236. ];
  4237. //订单编号,收货人,商品名称
  4238. if (!empty($selectParams['keyword'])) {
  4239. $dsl['query']['bool']['must'][] = [
  4240. 'multi_match' => [
  4241. 'fields' => ['no', 'verifyCode', 'mobile', 'goodsName', 'salesManName', 'customerName', 'remark'],
  4242. 'query' => $selectParams['keyword'],
  4243. //'fuzziness' => 'AUTO',
  4244. "type" => "best_fields",
  4245. "tie_breaker" => 0.3,
  4246. "minimum_should_match" => "100%"
  4247. ],
  4248. ];
  4249. }
  4250. //销售单/订单
  4251. if (isset($selectParams['orderType']) && !empty($selectParams['orderType'])) {
  4252. $dsl['query']['bool']['filter'][] =
  4253. ['term' => ['orderType' => $selectParams['orderType']]];
  4254. }
  4255. //订单状态
  4256. if (isset($selectParams['orderStatus']) && !empty($selectParams['orderStatus'])) {
  4257. $dsl['query']['bool']['filter'][] =
  4258. ['term' => ['orderStatus' => $selectParams['orderStatus']]];
  4259. }
  4260. //出库状态
  4261. if (isset($selectParams['outStatus']) && !empty($selectParams['outStatus'])) {
  4262. $dsl['query']['bool']['filter'][] =
  4263. ['term' => ['outStatus' => $selectParams['outStatus']]];
  4264. }
  4265. //退货状态
  4266. if (isset($selectParams['returnStatus']) && !empty($selectParams['returnStatus'])) {
  4267. $dsl['query']['bool']['filter'][] =
  4268. ['term' => ['returnStatus' => $selectParams['returnStatus']]];
  4269. }
  4270. //配送方式
  4271. if (isset($selectParams['deliveryType']) && !empty($selectParams['deliveryType'])) {
  4272. $dsl['query']['bool']['filter'][] =
  4273. ['term' => ['deliveryType' => $selectParams['deliveryType']]];
  4274. }
  4275. //支付状态
  4276. if (isset($selectParams['payType']) && !empty($selectParams['payType'])) {
  4277. $dsl['query']['bool']['filter'][] =
  4278. ['term' => ['payType' => $selectParams['payType']]];
  4279. }
  4280. //店铺id
  4281. parent::getAccessShopIds();
  4282. if (parent::$shopIds) {
  4283. $dsl['query']['bool']['filter'][] = [
  4284. 'terms' => ['shopId' => parent::$shopIds]
  4285. ];
  4286. }
  4287. //省code
  4288. if (isset($selectParams['provinceCode']) && !empty($selectParams['provinceCode'])) {
  4289. $dsl['query']['bool']['filter'][] =
  4290. ['term' => ['provinceCode' => $selectParams['provinceCode']]];
  4291. }
  4292. //市code
  4293. if (isset($selectParams['cityCode']) && !empty($selectParams['cityCode'])) {
  4294. $dsl['query']['bool']['filter'][] =
  4295. ['term' => ['cityCode' => $selectParams['cityCode']]];
  4296. }
  4297. //区code
  4298. if (isset($selectParams['districtCode']) && !empty($selectParams['districtCode'])) {
  4299. $dsl['query']['bool']['filter'][] =
  4300. ['term' => ['districtCode' => $selectParams['districtCode']]];
  4301. }
  4302. if (!empty($selectParams['start']) && !empty($selectParams['end'])) {
  4303. $dsl['query']['bool']['must'][] = [
  4304. 'range' => [
  4305. 'createTime' => [
  4306. 'gte' => $selectParams['start'],
  4307. 'lte' => $selectParams['end'],
  4308. ]
  4309. ]
  4310. ];
  4311. } else {
  4312. if (isset($selectParams['start']) && !empty($selectParams['start'])) {
  4313. $dsl['query']['bool']['must'][] = [
  4314. 'range' => [
  4315. 'createTime' => [
  4316. 'gte' => $selectParams['start'],
  4317. ]
  4318. ]
  4319. ];
  4320. }
  4321. if (isset($selectParams['end']) && !empty($selectParams['end'])) {
  4322. $dsl['query']['bool']['must'][] = [
  4323. 'range' => [
  4324. 'createTime' => [
  4325. 'lte' => $selectParams['end'],
  4326. ]
  4327. ]
  4328. ];
  4329. }
  4330. }
  4331. //店铺id
  4332. if (isset($selectParams['shopId']) && !empty($selectParams['shopId'])) {
  4333. $dsl['query']['bool']['filter'][] =
  4334. ['term' => ['shopId' => $selectParams['shopId']]];
  4335. }
  4336. //客户id
  4337. if (isset($selectParams['customerId']) && !empty($selectParams['customerId'])) {
  4338. $dsl['query']['bool']['filter'][] =
  4339. ['term' => ['customerId' => $selectParams['customerId']]];
  4340. }
  4341. //客户类型
  4342. if (isset($selectParams['customerType']) && !empty($selectParams['customerType'])) {
  4343. $dsl['query']['bool']['filter'][] =
  4344. ['term' => ['customerType' => $selectParams['customerType']]];
  4345. }
  4346. $flag = true;
  4347. //业务员id
  4348. if (isset($selectParams['salesManId']) && !empty($selectParams['salesManId'])) {
  4349. $dsl['query']['bool']['filter'][] =
  4350. ['term' => ['salesManId' => $selectParams['salesManId']]];
  4351. }
  4352. //销售员id
  4353. parent::getAccessSalesManIds();
  4354. if (!empty(parent::$salesManIds) && empty($selectParams['salesManId'])) {
  4355. $dsl['query']['bool']['filter'][] = [
  4356. 'terms' => ['salesManId' => parent::$salesManIds]
  4357. ];
  4358. }
  4359. if (!empty(parent::$salesManIds) && !empty($selectParams['salesManId'])) {
  4360. if (!in_array($selectParams['salesManId'], parent::$salesManIds)) {
  4361. $flag = false;
  4362. }
  4363. }
  4364. //订单来源
  4365. if (isset($selectParams['source']) && !empty($selectParams['source'])) {
  4366. $dsl['query']['bool']['filter'][] =
  4367. ['term' => ['source' => $selectParams['source']]];
  4368. }
  4369. //按照标示进行检索,等级最高
  4370. if (isset($selectParams['state']) && !empty($selectParams['state'])) {
  4371. $dsl = self::setOrderStatusDslAttr($dsl, $selectParams['state']);
  4372. }
  4373. $dsl = array_merge($defaultDSL, $dsl);
  4374. //导出
  4375. if ($is_export === true) self::exportSearch($dsl);
  4376. //V($dsl);
  4377. $result = $flag ? $this->objDOrder->getSearchQueryDsl($dsl) : [];
  4378. if (isset($result['status']) && $result['status'] == 400) {
  4379. //return ResultWrapper::fail('获取数据失败' . $result['error']['reason'], ErrorCode::$apiNotResult);
  4380. return ResultWrapper::success([
  4381. 'data' => [],
  4382. 'total' => 0
  4383. ]);
  4384. }
  4385. if (!isset($result['hits']) || $result['hits']['total'] == 0) {
  4386. return ResultWrapper::success([
  4387. 'data' => [],
  4388. 'total' => 0
  4389. ]);
  4390. }
  4391. $total = $result['hits']['total'];
  4392. $dbResult = $result['hits']['hits'];
  4393. $list = [];
  4394. foreach ($dbResult as $key => &$value) {
  4395. $data = [];
  4396. $data = $value['_source'];
  4397. //$data['id'] = $value['_id'];
  4398. $data['receiveData'] = [
  4399. 'realName' => $data['realName'],
  4400. 'mobile' => $data['mobile']
  4401. ];
  4402. unset($data['realName']);
  4403. unset($data['mobile']);
  4404. $list[] = $data;
  4405. }
  4406. $buildData = self::shiftEsReceiveData($list);
  4407. $formatResult = self::formatManageOrderList($buildData['allOrderData'], $buildData['allOrderReceiveData']);
  4408. if (!$formatResult->isSuccess()) {
  4409. return ResultWrapper::fail($formatResult->getData(), $formatResult->getErrorCode());
  4410. }
  4411. $return = [
  4412. 'data' => $formatResult->getData(),
  4413. 'total' => ($total) ? intval($total) : 0,
  4414. ];
  4415. return ResultWrapper::success($return);
  4416. }
  4417. /**
  4418. * Doc: (des="将es中查询出来的数据,统一转化为标准格式进行格式化")
  4419. * User: XMing
  4420. * Date: 2020/7/11
  4421. * Time: 6:13 下午
  4422. * @param $data
  4423. * @return array
  4424. */
  4425. private static function shiftEsReceiveData($data)
  4426. {
  4427. $orderData = [];
  4428. $orderReceiveData = [];
  4429. foreach ($data as $item) {
  4430. $orderData[] = $item;
  4431. $orderReceiveData[] = [
  4432. 'orderId' => $item['id'],
  4433. 'customerId' => $item['customerId'],
  4434. 'address' => $item['address'],
  4435. 'realName' => $item['receiveData']['realName'],
  4436. 'mobile' => $item['receiveData']['mobile'],
  4437. 'provinceCode' => $item['provinceCode'],
  4438. 'cityCode' => $item['cityCode'],
  4439. 'districtCode' => $item['districtCode']
  4440. ];
  4441. }
  4442. return [
  4443. 'allOrderData' => $orderData,
  4444. 'allOrderReceiveData' => $orderReceiveData
  4445. ];
  4446. }
  4447. /**
  4448. * 格式化订单状态
  4449. * @param $data
  4450. * @return mixed
  4451. */
  4452. private static function formatOrderStatus($data)
  4453. {
  4454. if (empty($data)) return $data;
  4455. foreach ($data as $key => $value) {
  4456. if ($value['auditStatus'] == StatusCode::$auditStatus['auditing']) {
  4457. $data[$key]['orderMsg'] = '待审核';
  4458. }
  4459. if ($value['auditStatus'] == StatusCode::$auditStatus['auditPass']) {
  4460. $data[$key]['orderMsg'] = '待出库';
  4461. if ($value['orderStatus'] == StatusCode::$orderStatus['waitReceive']) {
  4462. $data[$key]['orderMsg'] = '已出库';
  4463. if ($value['outStatus'] == 6 && $value['isRet'] != StatusCode::$standard){
  4464. $data[$key]['orderMsg'] = '部分出库';
  4465. }
  4466. }
  4467. if ($value['orderStatus'] == StatusCode::$orderStatus['finish']) {
  4468. $data[$key]['orderMsg'] = '已完成';
  4469. }
  4470. }
  4471. switch ($value['orderStatus']){
  4472. case StatusCode::$orderStatus['close']:
  4473. $data[$key]['orderMsg'] = '已关闭';
  4474. break;
  4475. case StatusCode::$orderStatus['cancelIng'];
  4476. $data[$key]['orderMsg'] = '待取消';
  4477. break;
  4478. // case StatusCode::$orderStatus['waitReceive'];
  4479. // $data[$key]['orderMsg'] = '待收货';
  4480. // break;
  4481. }
  4482. if (isset($value['payStatus'])) {
  4483. $data[$key]['payMsg'] = $value['payStatus'] == StatusCode::$standard ? '已支付' : '未支付';
  4484. }
  4485. if (isset($value['deliveryType'])) {
  4486. $data[$key]['deliveryMsg'] = isset(StatusCode::$deliveryType[$value['deliveryType']]) ? StatusCode::$deliveryType[$value['deliveryType']] : '';
  4487. }
  4488. if (isset($value['payType'])) {
  4489. $payTypeMsg = '';
  4490. if( isset(StatusCode::$payType[$value['payType']]) ){
  4491. $payTypeMsg = StatusCode::$payType[$value['payType']];
  4492. }else{// 组合支付渲染金额
  4493. if($value['extends']){
  4494. $admixPayData = json_decode($value['extends'],true);
  4495. $payTypeMsg = '组合支付(';
  4496. if(!empty($admixPayData)){
  4497. foreach ($admixPayData['admixPayData'] as $admixKey => $admixValue){
  4498. $payTypeMsg .= $admixValue['title'].'支付'.$admixValue['payMoney'].',';
  4499. }
  4500. }
  4501. $payTypeMsg .= ")";
  4502. }
  4503. }
  4504. $data[$key]['payTypeMsg'] = $payTypeMsg;
  4505. //$data[$key]['payTypeMsg'] = isset(StatusCode::$payType[$value['payType']]) ? StatusCode::$payType[$value['payType']] : '组合支付';
  4506. }
  4507. if (isset($value['source'])) {
  4508. $data[$key]['sourceMsg'] = isset(StatusCode::$source[$value['source']]) ? StatusCode::$source[$value['source']] : '';
  4509. }
  4510. if (isset($value['auditStatus'])) {
  4511. $data[$key]['auditMsg'] = isset(StatusCode::$auditStatus[$value['auditStatus']]) ? StatusCode::$auditStatus[$value['auditStatus']] : '';
  4512. }
  4513. }
  4514. return $data;
  4515. }
  4516. /**
  4517. * Doc: (des="订单标示的dsl拼接")
  4518. * User: XMing
  4519. * Date: 2020/7/11
  4520. * Time: 9:15 上午
  4521. * @param array $dsl
  4522. *
  4523. * @waitAudit:等待审核 orderStatus != 6 auditStatus = 1
  4524. * @waitOutStock:待出库 orderStatus != 6 auditPass = 2
  4525. * @hasOutStock:已出库 orderStatus = 4 auditPass = 2
  4526. * @finish:已完成 orderStatus = 5 auditPass 2
  4527. * @close:已关闭 orderStatus = 6
  4528. * @param string $states
  4529. * @return array|mixed
  4530. */
  4531. public static function setOrderStatusDslAttr(array $dsl, $states)
  4532. {
  4533. if (is_array($states)) {
  4534. $allAuditStatus = [];
  4535. $allOrderStatus = [];
  4536. foreach ($states as $state) {
  4537. $auditStatus = self::auditStatusAttrDsl($state);
  4538. $orderStatus = self::orderStatusAttrDsl($state);
  4539. $allAuditStatus = array_merge($auditStatus, $allAuditStatus);
  4540. $allOrderStatus = array_merge($orderStatus, $allOrderStatus);
  4541. }
  4542. } else {
  4543. $allAuditStatus = self::auditStatusAttrDsl($states);
  4544. $allOrderStatus = self::orderStatusAttrDsl($states);
  4545. }
  4546. if (!empty($allAuditStatus)) {
  4547. $dsl['query']['bool']['filter'][] = [
  4548. 'terms' => [
  4549. 'auditStatus' => $allAuditStatus
  4550. ]
  4551. ];
  4552. }
  4553. if (!empty($allOrderStatus)) {
  4554. $dsl['query']['bool']['filter'][] = [
  4555. 'terms' => [
  4556. 'orderStatus' => $allOrderStatus
  4557. ]
  4558. ];
  4559. }
  4560. return $dsl;
  4561. }
  4562. /**
  4563. * Doc: (des="state对应审核状态映射")
  4564. * User: XMing
  4565. * Date: 2020/7/13
  4566. * Time: 10:36 上午
  4567. * @param string $state
  4568. * @return array|mixed
  4569. */
  4570. public static function auditStatusAttrDsl(string $state)
  4571. {
  4572. $map = [
  4573. 'waitAudit' => [StatusCode::$auditStatus['auditing']],
  4574. 'waitOutStock' => [StatusCode::$auditStatus['auditPass']],
  4575. 'hasOutStock' => [StatusCode::$auditStatus['auditPass']],
  4576. 'finish' => [StatusCode::$auditStatus['auditPass']],
  4577. 'close' => [],
  4578. 'all' => []
  4579. ];
  4580. return isset($map[$state]) ? $map[$state] : [];
  4581. }
  4582. /**
  4583. * Doc: (des="state对应订单状态映射")
  4584. * User: XMing
  4585. * Date: 2020/7/13
  4586. * Time: 10:43 上午
  4587. * @param string $state
  4588. * @return array|mixed
  4589. */
  4590. public static function orderStatusAttrDsl(string $state)
  4591. {
  4592. $map = [
  4593. 'waitAudit' => [StatusCode::$orderStatus['waitPay'], StatusCode::$orderStatus['waitDelivery']],
  4594. 'waitOutStock' => [StatusCode::$orderStatus['waitPay'], StatusCode::$orderStatus['waitDelivery']],
  4595. 'hasOutStock' => [StatusCode::$orderStatus['waitReceive']],
  4596. 'finish' => [StatusCode::$orderStatus['finish']],
  4597. 'close' => [StatusCode::$orderStatus['close']],
  4598. 'all' => []
  4599. ];
  4600. return isset($map[$state]) ? $map[$state] : [];
  4601. }
  4602. /**
  4603. * 再次支付
  4604. *
  4605. * @param $params
  4606. * @param $ip
  4607. * @return ResultWrapper
  4608. * @throws \Exception
  4609. */
  4610. public function payOrder($params, $ip)
  4611. {
  4612. // 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);
  4613. //order表切表
  4614. $fix = 1;
  4615. $this->objDOrder->setTable('qianniao_order_'.$this->onlineEnterpriseId.'_'.$fix);
  4616. $this->objDOrderIndex->setTable('qianniao_order_index_'.$this->onlineEnterpriseId);
  4617. $status = $this->objDOrder->beginTransaction();
  4618. //再次支付更新extend值
  4619. $extend = [];
  4620. // 处理混合支付数据
  4621. if( !empty($params['admixPayData']) ){
  4622. $extend['admixPayData'] = $params['admixPayData'];
  4623. }
  4624. // 处理银行打款数据
  4625. if( !empty($params['bankData']) ){
  4626. $extend['bankData'] = $params['bankData'];
  4627. }
  4628. $extend = json_encode($extend);
  4629. //再次付款更新extend(付款信息)
  4630. $updateExtend = $this->objDOrder->update(['extends'=>$extend],['no' => $params['no']]);
  4631. if ($updateExtend === false) {
  4632. $this->objDOrderIndex->rollBack();
  4633. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  4634. }
  4635. if($status){
  4636. $this->objDOrder->commit();
  4637. }
  4638. $orderData = $this->objDOrder->get(['no' => $params['no']]);
  4639. if ($orderData === false) {
  4640. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  4641. }
  4642. if (empty($orderData)) {
  4643. return ResultWrapper::fail('没有找到订单', ErrorCode::$paramError);
  4644. }
  4645. $params['payType'] = explode(',', $params['payType']);
  4646. $this->objDOrder->beginTransaction();
  4647. //再次支付时订单支付方式改为了货到付款
  4648. //if ($params['payType'] == StatusCode::$payType['cashPay']) {
  4649. if ( in_array(StatusCode::$payType['cashPay'], $params['payType']) || in_array(StatusCode::$payType['bankLoans'],$params['payType'])) {
  4650. //修改订单的支付方式
  4651. if(in_array(StatusCode::$payType['cashPay'], $params['payType'])){//货到付款 订单状态为待发货
  4652. $update = [
  4653. 'payType' => StatusCode::$payType['cashPay'],
  4654. 'orderStatus' => StatusCode::$orderStatus['waitDelivery']
  4655. ];
  4656. } else{//银行打款 订单状态为代发货
  4657. $update = [
  4658. 'payType' => StatusCode::$payType['bankLoans'],
  4659. 'orderStatus' => StatusCode::$orderStatus['waitPay'],
  4660. 'payStatus' => StatusCode::$delete
  4661. ];
  4662. }
  4663. $dbResult = $this->objDOrder->update($update, ['no' => $params['no']]);
  4664. if ($dbResult === false) {
  4665. $this->objDOrderIndex->rollBack();
  4666. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  4667. }
  4668. unset($dbResult);
  4669. //修改索引表支付方式
  4670. $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId);
  4671. $dbResult = $this->objDOrderIndex->update($update, ['id' => $orderData['id']]);
  4672. if ($dbResult === false) {
  4673. $this->objDOrderIndex->rollBack();
  4674. return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
  4675. }
  4676. /*
  4677. //修改ES,支付方式
  4678. $_id = self::createEsDocumentId($orderData['id']);
  4679. $this->objDOrder->esupdateTypeFieldVaule(['payType' => StatusCode::$payType['cashPay']], $_id);*/
  4680. $this->objDOrder->commit();
  4681. //订单是否自动审核
  4682. $objMBasicSetup = new MBasicSetup($this->onlineEnterpriseId);
  4683. //获取基本配置
  4684. $setupResult = $objMBasicSetup->getBasicField('autoAuditOrder');
  4685. $autoAuditOrder = [];
  4686. if ($setupResult->isSuccess()) {
  4687. $autoAuditOrder = $setupResult->getData();//自动审核配置数据
  4688. $autoAuditOrder = isset($autoAuditOrder['autoAuditOrder']) ? $autoAuditOrder['autoAuditOrder'] : [];
  4689. }
  4690. //货到付款是否开启了自动审核
  4691. $autoAudit = isset($autoAuditOrder['cashPay']) ? $autoAuditOrder['cashPay'] : StatusCode::$delete;
  4692. if ($autoAudit == StatusCode::$standard) {
  4693. //开启了自动审核,审核订单
  4694. $auditResult = self::updateAuditStatus([
  4695. 'id' => $orderData['id'],
  4696. 'audit' => '自动审核',
  4697. 'auditId' => $this->onlineUserId,
  4698. 'auditStatus' => StatusCode::$auditStatus['auditPass']
  4699. ]);
  4700. }
  4701. return ResultWrapper::success($dbResult);
  4702. }
  4703. //获取客户信息
  4704. $objMCustomer = new MCustomer($this->onlineEnterpriseId, $this->onlineUserId);
  4705. $customerData = $objMCustomer->getCustomerInfoByUserCenterId($this->onlineUserId);
  4706. if (!$customerData->isSuccess()) {
  4707. return ResultWrapper::fail($customerData->getData(), $customerData->getErrorCode());
  4708. }
  4709. $customerData = $customerData->getData();
  4710. $payType = $params['payType'];
  4711. rsort($payType);
  4712. $payment = [];
  4713. $payParams = '';
  4714. $payStatus = StatusCode::$partion;
  4715. $orderStatus = StatusCode::$orderStatus['waitPay'];
  4716. if( in_array(StatusCode::$payType['bankLoans'],$payType) ){
  4717. $payStatus = StatusCode::$delete;
  4718. $orderStatus = StatusCode::$orderStatus['waitPay'];
  4719. }
  4720. foreach($payType as $k => $v){
  4721. // 除了余额支付其他方式都要获取支付配置
  4722. if($v != StatusCode::$payType['balance']){
  4723. $objMPaymentSetting = new MPaymentSetting($this->onlineUserId, $this->onlineEnterpriseId);
  4724. $result = $objMPaymentSetting->getPayData($v);
  4725. if (!$result->isSuccess() || empty($result->getData())) {
  4726. return ResultWrapper::fail('获取微信配置错误', ErrorCode::$configEroor);
  4727. }
  4728. $payment = $result->getData();
  4729. }
  4730. switch (true){
  4731. case in_array(StatusCode::$payType['balance'], $payType):
  4732. //余额支付
  4733. //$objMCustomer = new MCustomer($this->onlineEnterpriseId,$this->onlineUserId);
  4734. //减少余额()
  4735. $status = $this->objDOrderIndex->beginTransaction();
  4736. //新增会员流水记录
  4737. $memberBalanceDetailData = [
  4738. 'customerId' => $orderData['customerId'],
  4739. 'type' => StatusCode::$delete,
  4740. 'userCenterId' => $this->onlineUserId,
  4741. 'purpose' => '创建订单消费',
  4742. 'orderIds' =>implode(',',[$orderData['id']]),
  4743. 'remark' => '订单id'.implode(',',[$orderData['id']]),
  4744. 'financeType' => '会员余额消费'
  4745. ];
  4746. // 组合支付方式
  4747. if( !empty($params['admixPayData']) ) {
  4748. foreach ($params['admixPayData'] as $key => $value) {
  4749. if ($value['payType'] == StatusCode::$payType['balance']) {
  4750. // 本次混合支付余额支付金额
  4751. $memberBalanceDetailData['money'] = $value['payMoney'];
  4752. // 总金额 - 余额支付金额 = 剩余需要搭配支付金额
  4753. $orderData['payAmount'] = bcsub($orderData['payAmount'], $value['payMoney'], 2);
  4754. }
  4755. }
  4756. }else{
  4757. $payStatus = StatusCode::$standard;
  4758. $orderStatus = StatusCode::$orderStatus['waitDelivery'];
  4759. $memberBalanceDetailData['money'] = $orderData['payAmount'];
  4760. }
  4761. $objMMemberBalanceDetail = new MMemberBalanceDetail($this->onlineEnterpriseId,$this->onlineUserId);
  4762. $memberBalanceDbResult = $objMMemberBalanceDetail->addMemberBalanceDetail($memberBalanceDetailData);
  4763. if (!$memberBalanceDbResult->isSuccess()) {
  4764. $this->objDOrderIndex->rollBack();
  4765. return ResultWrapper::fail($memberBalanceDbResult->getData(), $memberBalanceDbResult->getErrorCode());
  4766. }
  4767. //扣除失败->订单未支付
  4768. if ($memberBalanceDbResult->isSuccess()){
  4769. $time = time();
  4770. //扣除成功->订单支付成功\
  4771. foreach ([$orderData['id']] as $orderId){
  4772. $updateIndexResult = $this->objDOrderIndex->update(['payStatus' => $payStatus,'orderStatus' => $orderStatus,'updateTime' => $time],$orderId);
  4773. if ($updateIndexResult === false){
  4774. $this->objDOrderIndex->rollBack();
  4775. return ResultWrapper::fail($this->objDOrderIndex->error(),ErrorCode::$dberror);
  4776. }
  4777. $updateIndex = $this->objDOrder->update(['payStatus' => $payStatus,'orderStatus' => $orderStatus,'payTime'=> $time,'updateTime' => $time,'payAmount'=>$memberBalanceDetailData['money']],$orderId);
  4778. if ($updateIndex === false){
  4779. $this->objDOrderIndex->rollBack();
  4780. return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror);
  4781. }
  4782. }
  4783. }
  4784. $status && $this->objDOrderIndex->commit();
  4785. $payParams = ResultWrapper::success([]);
  4786. break;
  4787. case in_array(StatusCode::$payType['aliPay'], $payType):
  4788. //ali
  4789. /*********读取支付宝支付参数(原配置)*********/
  4790. /**$aliPayConfigData = Factory::config()->get('alipay');
  4791. * if (empty($aliPayConfigData)) {
  4792. * return ResultWrapper::fail('支付宝配置错误', ErrorCode::$configEroor);
  4793. * }*/
  4794. $payOrderData = [
  4795. 'subject' => '千鸟云商',
  4796. 'out_trade_no' => $orderData['no'],
  4797. 'total_amount' => $orderData['payAmount'],
  4798. 'passback_params' => $this->onlineEnterpriseId . '|' . $this->onlineUserId . '|' . implode('|', [$orderData['id']]),
  4799. ];
  4800. $aliPayConfigData = [
  4801. 'appid' => $payment['appid'],
  4802. 'rsaPrivateKey' => $payment['rsaPrivateKey'],
  4803. 'alipayrsaPublicKey' => $payment['alipayrsaPublicKey'],
  4804. ];
  4805. $objAliPay = new aliPay($aliPayConfigData['appid'], $aliPayConfigData['rsaPrivateKey'], $aliPayConfigData['alipayrsaPublicKey']);
  4806. $payParams = $objAliPay->appPay($payOrderData);
  4807. break;
  4808. case in_array(StatusCode::$payType['wxPay'], $payType):
  4809. //wx
  4810. /********************生成小程序唤起支付用到的参数(原配置)*****/
  4811. /**$weixinConfigData = Factory::config()->get('weixin');
  4812. * if (empty($weixinConfigData)) {
  4813. * return ResultWrapper::fail('微信配置错误', ErrorCode::$configEroor);
  4814. * }*/
  4815. // 获取当前登录企业的小程序配置
  4816. $objSystemCache = new SystemCache();
  4817. $miniprogramSetting = $objSystemCache->getAppIdByEnterpriseId($this->onlineEnterpriseId);
  4818. if (empty($miniprogramSetting)) {
  4819. return ResultWrapper::fail('后台小程序配置项为空', ErrorCode::$configEroor);
  4820. }
  4821. $miniprogramSetting = json_decode($miniprogramSetting, true);//获取小程序appid
  4822. // 获取配置文件微信公众号
  4823. /**$weixinConfigData = Factory::config()->get('weixin');
  4824. * if (empty($weixinConfigData)) {
  4825. * return ResultWrapper::fail('微信配置错误', ErrorCode::$configEroor);
  4826. * }*/
  4827. switch ($params['source']) {
  4828. case StatusCode::$source['ByteProgram'];
  4829. //$appid = $weixinConfigData['offiaccount']['appid'];
  4830. $appid = $miniprogramSetting['appid'];
  4831. $paySource = 'byteDanceH5';
  4832. break;
  4833. case StatusCode::$source['miniProgram'];
  4834. $appid = $miniprogramSetting['appid'];
  4835. $paySource = 'miniProgram';
  4836. break;
  4837. default :
  4838. $appid = $payment['mobileAppid'];
  4839. $paySource = 'APP';
  4840. break;
  4841. }
  4842. $weixinConfigData = [
  4843. 'mch_id' => $payment['mchId'],
  4844. 'apiPartnerKey' => $payment['apiPartnerKey'],
  4845. 'appid' => $appid
  4846. ];
  4847. $attach = $this->onlineEnterpriseId . '|' . $this->onlineUserId . '|' . implode('|', [$orderData['id']]);
  4848. //$objPay = new Pay($appid, $weixinConfigData['pay']['mch_id'], $weixinConfigData['pay']['apiPartnerKey']);//old
  4849. $objPay = new Pay($appid, $weixinConfigData['mch_id'], $weixinConfigData['apiPartnerKey']);
  4850. $payParams = $objPay->unifiedorder($orderData['no'],$orderData['payAmount'], $ip, $paySource, '千鸟云商', $customerData['openId'], $attach);
  4851. break;
  4852. case in_array(StatusCode::$payType['byte'],$payType):
  4853. //字节跳动
  4854. $mweb_url = '';
  4855. //读取缓存配置
  4856. //$objSystemCache->getByteDanceSetting($this->onlineEnterpriseId);
  4857. // 获取配置文件字节小程序
  4858. $byteDanceConfigData = Factory::config()->getAppoint('byteDance', 'pay');
  4859. if (empty($byteDanceConfigData)) {
  4860. return ResultWrapper::fail('字节跳动配置错误', ErrorCode::$configEroor);
  4861. }
  4862. $objbytePay = new bytePay($byteDanceConfigData['appid'], $byteDanceConfigData['merchant_id'], $byteDanceConfigData['app_secret']);
  4863. unset($payParams);
  4864. $payParams = $objbytePay->pay($orderData['no'],$orderData['payAmount'], '千鸟云商', $ip, $mweb_url);
  4865. break;
  4866. case in_array(StatusCode::$payType['bankLoans'], $payType):
  4867. $payParams = ResultWrapper::success([$orderData['id']]);
  4868. break;
  4869. default:
  4870. //TODO
  4871. return ResultWrapper::fail('暂未开放的支付方式',ErrorCode::$paramError);
  4872. break;
  4873. }
  4874. unset($payType[$k]);
  4875. if (!$payParams->isSuccess()) {
  4876. return ResultWrapper::fail($payParams->getData(), $payParams->getErrorCode());
  4877. }
  4878. }
  4879. return ResultWrapper::success($payParams->getData());
  4880. }
  4881. /**
  4882. * 增加打印次数
  4883. * @param $id
  4884. * @return ResultWrapper
  4885. */
  4886. public function printIncr($id)
  4887. {
  4888. $dbResult = $this->objDOrder->set_inc('printingNum', ['id' => $id]);
  4889. if ($dbResult === false) {
  4890. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  4891. }
  4892. return ResultWrapper::success($dbResult);
  4893. }
  4894. /**
  4895. * todo(保存编辑(废弃))
  4896. *
  4897. * @param $params
  4898. * @return ResultWrapper
  4899. * @throws \Exception
  4900. */
  4901. public function saveEdit($params)
  4902. {
  4903. $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId);
  4904. $objMOrderGoods = new MOrderGoods($this->onlineUserId, $this->onlineEnterpriseId);
  4905. $objMShippingAddress = new MShippingAddress($this->onlineEnterpriseId);
  4906. $objMOrderReceive = new MOrderReceive($this->onlineUserId, $this->onlineEnterpriseId);
  4907. $order = $this->objDOrder->get(['id' => $params['orderId']]);
  4908. if ($order === false) {
  4909. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  4910. }
  4911. if (empty($order)) {
  4912. return ResultWrapper::fail('订单不存在', ErrorCode::$paramError);
  4913. }
  4914. if (!isset($order['auditStatus'])
  4915. || $order['auditStatus'] == StatusCode::$auditStatus['auditPass']
  4916. || $order['payStatus'] == StatusCode::$standard
  4917. ) {
  4918. return ResultWrapper::fail('订单不能编辑', ErrorCode::$paramError);
  4919. }
  4920. //根据地址id获取地址信息
  4921. $dbResult = $objMShippingAddress->getShippingAddressInfo($params['receiveAddressId']);
  4922. if (!$dbResult->isSuccess()) {
  4923. return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror);
  4924. }
  4925. $addressData = $dbResult->getData();
  4926. if (empty($addressData)) {
  4927. return ResultWrapper::fail('收货地址信息不存在', ErrorCode::$dberror);
  4928. }
  4929. //锁定库存 查询商铺对应的仓库
  4930. $objMWarehouse = new MWarehouse($this->onlineEnterpriseId);
  4931. $warehouseData = $objMWarehouse->getWarehouseInfo(['shopId' => $params['goodsData']['goodsData'][0]['shopId']]);
  4932. if (!$warehouseData->isSuccess()) {
  4933. return ResultWrapper::fail($params['goodsData']['goodsData'][0]['shopId'] . $warehouseData->getData(), $warehouseData->getErrorCode());
  4934. }
  4935. $warehouse = $warehouseData->getData();
  4936. $commonData = $params['goodsData'];
  4937. $this->objDOrder->beginTransaction();
  4938. //先解锁库存
  4939. // $objMInventory = new MInventory($this->onlineEnterpriseId, $this->onlineUserId);
  4940. // $unlockResult = $objMInventory->unlockInventory([$order['id']], StatusCode::$orderType['saleOrder'], $order['createTime']);
  4941. // if (!$unlockResult->isSuccess()) {
  4942. // $this->objDOrder->rollBack();
  4943. // return ResultWrapper::fail($unlockResult->getData(), ErrorCode::$dberror);
  4944. // }
  4945. $dbResult = $this->objDOrderIndex->update(['deliveryType' => $params['deliveryType']], ['id' => $params['orderId']]);
  4946. if ($dbResult === false) {
  4947. $this->objDOrder->rollBack();
  4948. return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
  4949. }
  4950. //修改Order表中的数据
  4951. $dbResult = $this->objDOrder->update([
  4952. 'totalMoney' => $commonData['totalMoney'],
  4953. 'payAmount' => $commonData['payMoney'],
  4954. 'deliveryType' => $params['deliveryType'],
  4955. 'buyTotal' => array_sum(array_column($commonData['goodsData'], 'buyNum'))
  4956. ], ['id' => $params['orderId']]);
  4957. if ($dbResult === false) {
  4958. $this->objDOrder->rollBack();
  4959. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  4960. }
  4961. unset($dbResult);
  4962. //修改OrderGoods表中的数据
  4963. if (!empty($params['delOrderGoodsIds'])) {
  4964. $dbResult = $objMOrderGoods->updateDetails(['deleteStatus' => StatusCode::$delete], ['id' => $params['delOrderGoodsIds']]);
  4965. if (!$dbResult->isSuccess()) {
  4966. $this->objDOrder->rollBack();
  4967. return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror);
  4968. }
  4969. unset($dbResult);
  4970. }
  4971. //查询当前订单商品,进行比对
  4972. $dbResult = $objMOrderGoods->getDetails([
  4973. 'orderId' => $params['orderId'],
  4974. 'deleteStatus' => StatusCode::$standard,
  4975. ]);
  4976. if (!$dbResult->isSuccess()) {
  4977. $this->objDOrder->rollBack();
  4978. return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror);
  4979. }
  4980. $oldGoodsData = $dbResult->getData();
  4981. $hash = [];
  4982. foreach ($oldGoodsData as $goods) {
  4983. $hash[] = md5($goods['goodsId'] . $goods['skuId']);
  4984. }
  4985. $lockInventoryData = [];
  4986. foreach ($commonData['goodsData'] as $value) {
  4987. foreach ($value['shopGoodsData'] as $key => $val) {
  4988. $rowHash = md5($val['goodsId'] . $val['skuId']);
  4989. if (in_array($rowHash, $hash)) {
  4990. //update
  4991. $dbResult = $objMOrderGoods->updateDetails(
  4992. [
  4993. 'buyNum' => $val['buyNum'],
  4994. 'price' => $val['price'],
  4995. 'originPrice' => $val['originPrice'],
  4996. 'totalMoney' => $val['totalMoney'],
  4997. ],
  4998. ['orderId' => $params['orderId'], 'goodsId' => $val['goodsId'], 'skuId' => $val['skuId']]
  4999. );
  5000. if (!$dbResult->isSuccess()) {
  5001. $this->objDOrder->rollBack();
  5002. return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror);
  5003. }
  5004. } else {
  5005. //insert
  5006. $dbResult = $objMOrderGoods->addOrderGoods([
  5007. 'no' => $order['no'],
  5008. 'orderId' => $params['orderId'],
  5009. 'goodsId' => $val['goodsId'],
  5010. 'goodsName' => $val['goodsName'],
  5011. 'shopId' => $val['shopId'],//商铺id
  5012. 'shopName' => $val['shopName'],//商铺名称
  5013. 'originPrice' => $val['originPrice'],
  5014. 'price' => $val['price'],
  5015. 'buyNum' => $val['buyNum'],
  5016. 'totalMoney' => $val['totalMoney'],
  5017. 'skuId' => $val['skuId'],
  5018. 'goodsBasicId' => $val['goodsBasicId'],
  5019. 'goodsCode' => $val['goodsCode'],
  5020. 'deliverNum' => $val['buyNum'],//发货数量=购买数量
  5021. 'unitName' => $val['unitName'],//单位名称
  5022. 'conversion' => $val['conversion'],//换算比率
  5023. 'preferential' => $val['preferential'],//优惠券优惠金额
  5024. 'vipDiscount' => $val['vipDiscount'],//会员卡优惠金额
  5025. ]);
  5026. if (!$dbResult->isSuccess()) {
  5027. $this->objDOrder->rollBack();
  5028. return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror);
  5029. }
  5030. }
  5031. //锁定库存数据
  5032. $lockInventoryData[] = [
  5033. 'warehouseId' => $warehouse['id'],
  5034. 'materielId' => $val['goodsBasicId'],
  5035. 'lockingNum' => empty((float)($val['conversion'])) ? $val['buyNum'] : bcdiv($val['buyNum'], $val['conversion']),
  5036. 'originId' => $params['orderId'],
  5037. 'originNo' => $order['no'],
  5038. 'source' => StatusCode::$orderType['saleOrder'],
  5039. 'sourceNo' => $order['no'],
  5040. 'operatorId' => $order['customerId'],
  5041. 'operatorName' => $order['customerName'],
  5042. 'skuId' => $val['skuId'],
  5043. ];
  5044. }
  5045. }
  5046. //锁定库存
  5047. // $lockInventoryResult = $objMInventory->updateLockInventory($lockInventoryData);
  5048. // if (!$lockInventoryResult->isSuccess()) {
  5049. // $this->objDOrder->rollBack();
  5050. // return ResultWrapper::fail($lockInventoryResult->getData(), $lockInventoryResult->getErrorCode());
  5051. // }
  5052. //修改收货人
  5053. $dbResult = $objMOrderReceive->updateReceive(
  5054. [
  5055. 'customerCode' => $addressData['customerCode'],//客户编码
  5056. 'realName' => $addressData['name'],//收货人姓名
  5057. 'mobile' => $addressData['mobile'],//收货人电话
  5058. 'address' => $addressData['address'],//收货人详细地址
  5059. 'provinceCode' => $addressData['provinceCode'],
  5060. 'cityCode' => $addressData['cityCode'],
  5061. 'districtCode' => $addressData['districtCode'],
  5062. ],
  5063. [
  5064. 'orderId' => $params['orderId']
  5065. ]
  5066. );
  5067. if (!$dbResult->isSuccess()) {
  5068. $this->objDOrder->rollBack();
  5069. return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror);
  5070. }
  5071. $this->objDOrder->commit();
  5072. /*
  5073. $_id = self::createEsDocumentId($params['orderId']);
  5074. $this->objDOrder->esupdateTypeFieldVaule([
  5075. 'totalMoney' => $commonData['totalMoney'],
  5076. 'payAmount' => $commonData['payMoney'],
  5077. 'buyTotal' => array_sum(array_column($commonData['goodsData'], 'buyNum')),//购买总数
  5078. 'deliveryType' => $params['deliveryType'],
  5079. 'realName' => $addressData['name'],//收货人姓名
  5080. 'mobile' => $addressData['mobile'],//收货人电话
  5081. 'address' => $addressData['address'],//收货详细地址
  5082. 'provinceCode' => $addressData['provinceCode'],//收货人省份编码
  5083. 'cityCode' => $addressData['cityCode'],//收货人城市编码
  5084. 'districtCode' => $addressData['districtCode'],//收货人区编码
  5085. ], $_id);
  5086. //修改es中的数据*/
  5087. return ResultWrapper::success('操作成功');
  5088. }
  5089. /**
  5090. * 订单编辑(现在只能编辑订单支付金额)
  5091. * @param $params
  5092. * @return ResultWrapper
  5093. */
  5094. public function orderEdit($params)
  5095. {
  5096. $order = $this->objDOrder->get(['id' => $params['orderId']]);
  5097. if ($order === false) {
  5098. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  5099. }
  5100. if (empty($order)) {
  5101. return ResultWrapper::fail('订单不存在', ErrorCode::$paramError);
  5102. }
  5103. if (!isset($order['auditStatus'])
  5104. || $order['auditStatus'] == StatusCode::$auditStatus['auditPass']
  5105. || $order['payStatus'] == StatusCode::$standard
  5106. ) {
  5107. return ResultWrapper::fail('订单不能编辑', ErrorCode::$paramError);
  5108. }
  5109. //修改payAmount,将payAmount复制到字段originPayAmount
  5110. $update = [
  5111. 'payAmount' => sprintf("%.2f", $params['editAmount']),
  5112. 'originPayAmount' => $order['payAmount'],//原付款金额
  5113. ];
  5114. $dbResult = $this->objDOrder->update($update, ['id' => $params['orderId']]);
  5115. if ($dbResult === false) {
  5116. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  5117. }
  5118. /*
  5119. //修改es中的数据
  5120. $_id = self::createEsDocumentId($params['orderId']);
  5121. $this->objDOrder->esupdateTypeFieldVaule([
  5122. 'payAmount' => $update['payAmount'],
  5123. 'originPayAmount' => $update['originPayAmount'],//原付款金额
  5124. ], $_id);*/
  5125. return ResultWrapper::success('操作成功');
  5126. }
  5127. /**
  5128. * Doc: (des="")
  5129. * User: XMing
  5130. * Date: 2020/9/2
  5131. * Time: 9:16 上午
  5132. * @param array $params
  5133. * @return ResultWrapper
  5134. *
  5135. * @throws \Exception
  5136. */
  5137. public function cashierOrder(array $params)
  5138. {
  5139. $objMUserCoupon = new MUserCoupon($this->onlineUserId, $this->onlineEnterpriseId);
  5140. $objMCustomer = new MCustomer($this->onlineEnterpriseId, $this->onlineUserId);
  5141. $objMCustomerBalance = new MCustomerBalance($this->onlineEnterpriseId, $this->onlineUserId);
  5142. $objMCart = new MCart($this->onlineUserId, $this->onlineEnterpriseId);
  5143. $objMOrderGoods = new MOrderGoods($this->onlineUserId, $this->onlineEnterpriseId);
  5144. $objDStaff = new DStaff();
  5145. $objStockCache = new Stock($this->onlineEnterpriseId);
  5146. $objDStaff->setTable('qianniao_staff_' . $this->onlineEnterpriseId);
  5147. $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId);
  5148. $goodsCommonData = $params['goodsData'];
  5149. //锁定库存 查询商铺对应的仓库
  5150. $objMShop = new MShop($this->onlineEnterpriseId, $this->onlineUserId);
  5151. $modelResult = $objMShop->getShopDataByShopIds(array_column($goodsCommonData['goodsData'], 'shopId'));
  5152. if (!$modelResult->isSuccess()) {
  5153. return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
  5154. }
  5155. $shopData = $modelResult->getData();
  5156. if (empty($shopData)) {
  5157. return ResultWrapper::fail('获取店铺数据失败', ErrorCode::$paramError);
  5158. }
  5159. //获取收银员信息
  5160. $allUids = [$this->loginUserCenterId];
  5161. if (isset($params['guideUids']) && !empty($params['guideUids'])) {
  5162. $ids = explode(',', $params['guideUids']);
  5163. $allUids = array_merge($allUids, $ids);
  5164. }
  5165. $userMap = [];
  5166. if (!empty($allUids)) {
  5167. $staffList = $objDStaff->select(['userCenterId' => $allUids], 'userCenterId,staffName');
  5168. if ($staffList === false) {
  5169. return ResultWrapper::fail($objDStaff->error(), ErrorCode::$dberror);
  5170. }
  5171. foreach ($staffList as $value) {
  5172. $userMap[$value['userCenterId']] = $value['staffName'];
  5173. }
  5174. }
  5175. $params['cashierName'] = isset($userMap[$this->loginUserCenterId]) ? $userMap[$this->loginUserCenterId] : '超级管理员';
  5176. $nameStr = '';
  5177. if (!empty($ids)) {
  5178. foreach ($ids as $uid) {
  5179. if (!empty($nameStr)) {
  5180. $nameStr .= ',';
  5181. }
  5182. $nameStr .= isset($userMap[$uid]) ? $userMap[$uid] : '';
  5183. }
  5184. }
  5185. $params['guideName'] = $nameStr;
  5186. $params['customerMobile'] = '';
  5187. //获取客户信息
  5188. $customerOwe = 0;
  5189. if ($this->onlineUserId == StatusCode::$noneUserCenter) {
  5190. $customerData = [
  5191. 'id' => StatusCode::$noneCustomer,
  5192. 'name' => '匿名客户'
  5193. ];
  5194. } else {
  5195. $customerDataResult = $objMCustomer->getCustomerInfoByUserCenterId($this->onlineUserId);
  5196. if (!$customerDataResult->isSuccess()) {
  5197. return ResultWrapper::fail($customerDataResult->getData(), $customerDataResult->getErrorCode());
  5198. }
  5199. $customerData = $customerDataResult->getData();
  5200. //获取客户当前欠款
  5201. if (isset($customerData['id'])) {
  5202. $customerOwe = $objMCustomerBalance->getCustomerBalance($customerData['id']);
  5203. }
  5204. //获取客户手机号
  5205. $objDUserCenter = new DUserCenter();
  5206. $userInfo = $objDUserCenter->get(['id' => $this->onlineUserId], 'mobile');
  5207. if ($userInfo === false) {
  5208. return ResultWrapper::fail($objDUserCenter->error(), ErrorCode::$dberror);
  5209. }
  5210. $params['customerMobile'] = isset($userInfo['mobile']) ? $userInfo['mobile'] : '';
  5211. }
  5212. // 生成一个临时三方流水号,用来支持多个子订单作为一个订单支付,支付成功之后更新为对应的实际外部支付流水号
  5213. $tmpOuterTradeNo = 'tmp' . createOrderSn($params['source'], StatusCode::$orderType['cashierOrder'], $this->onlineUserId);
  5214. $lockInventoryData = [];//锁定库存物料
  5215. $goodsSaleData = [];//销售数据
  5216. $allSn = [];//所有单号
  5217. $allOrderIds = [];//所有订单
  5218. $mapDetails = [];//订单商品
  5219. $createTime = time();
  5220. $allCartIds = [];
  5221. $shopName = '';
  5222. $shopId = 0;//目前只有一个
  5223. $this->objDOrder->beginTransaction();
  5224. foreach ($goodsCommonData['goodsData'] as $key => $val) {
  5225. $sn = createOrderSn($params['source'], StatusCode::$orderType['saleOrder'], $this->onlineUserId);
  5226. //将数据写入索引表
  5227. $shopId = $val['shopId'];
  5228. $orderIndexData = [
  5229. 'shopId' => $val['shopId'],
  5230. 'userCenterId' => $params['userCenterId'],
  5231. 'salesManId' => isset($customerData['salesManId']) ? $customerData['salesManId'] : 0,
  5232. 'createTime' => time(),
  5233. 'updateTime' => time(),
  5234. 'deleteStatus' => StatusCode::$standard,
  5235. 'auditStatus' => StatusCode::$auditStatus['auditing'],
  5236. 'payStatus' => StatusCode::$delete,
  5237. 'orderStatus' => StatusCode::$orderStatus['waitPay'],
  5238. 'outStatus' => StatusCode::$delete,
  5239. 'returnStatus' => StatusCode::$orderReturn['notReturn'],
  5240. 'deliveryType' => $params['deliveryType'],
  5241. 'payType' => $params['payType'],
  5242. 'customerId' => isset($customerData['id']) ? $customerData['id'] : 0,
  5243. 'no' => $sn,
  5244. 'orderType' => StatusCode::$orderType['cashierOrder'],
  5245. 'selfRuleId' => 0,
  5246. 'cashierUid' => $this->loginUserCenterId,
  5247. 'guideUids' => $params['guideUids']
  5248. ];
  5249. //1. 先写索引表
  5250. $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId);
  5251. $orderId = $this->objDOrderIndex->insert($orderIndexData);
  5252. if ($orderId === false) {
  5253. $this->objDOrder->rollBack();
  5254. return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
  5255. }
  5256. //3。上门自提订单,生成核销码
  5257. $verifyCode = self::createVerifyCode($orderId);
  5258. //兼容以前代码
  5259. $updateRes = $this->objDOrderIndex->update(['verifyCode' => $verifyCode], ['id' => $orderId]);
  5260. if ($updateRes === false) {
  5261. $this->objDOrder->rollBack();
  5262. return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
  5263. }
  5264. //订单数据
  5265. $shopName = $val['shopName'];//现在就一个店铺
  5266. $masterOrder = [
  5267. 'id' => $orderId,//订单id
  5268. 'customerId' => isset($customerData['id']) ? $customerData['id'] : 0,
  5269. 'userCenterId' => $params['userCenterId'],
  5270. 'shopId' => $val['shopId'],
  5271. 'shopName' => $val['shopName'],
  5272. 'no' => $sn,
  5273. 'outerTradeNo' => $tmpOuterTradeNo,
  5274. 'totalMoney' => $goodsCommonData['totalMoney'],
  5275. 'payAmount' => $goodsCommonData['payMoney'],
  5276. 'customerName' => isset($customerData['name']) ? $customerData['name'] : '',
  5277. 'remark' => $params['remark'],
  5278. 'deliveryType' => $params['deliveryType'],//配送方式
  5279. 'payType' => $params['payType'],//支付方式
  5280. 'salesManId' => isset($customerData['salesManId']) ? $customerData['salesManId'] : 0,
  5281. 'salesManName' => isset($customerData['salesManName']) ? $customerData['salesManName'] : '',
  5282. 'customerType' => isset($customerData['type']) ? $customerData['type'] : 0,
  5283. 'buyTotal' => array_sum(array_column($val['shopGoodsData'], 'buyNum')),
  5284. 'source' => $params['source'],//来源
  5285. 'orderStatus' => StatusCode::$orderStatus['waitPay'],
  5286. 'returnStatus' => StatusCode::$orderReturn['notReturn'],
  5287. 'outStatus' => StatusCode::$delete,
  5288. 'createTime' => time(),
  5289. 'updateTime' => time(),
  5290. 'customerOwe' => $customerOwe,//客户当前欠款
  5291. 'auditStatus' => StatusCode::$auditStatus['auditing'],
  5292. 'preferential' => $goodsCommonData['preferential'],//优惠券优惠金额
  5293. 'vipDiscount' => isset($goodsCommonData['vipDiscount']) ? $goodsCommonData['vipDiscount'] : 0,//会员卡优惠金额
  5294. 'vipDoubleDiscount' => isset($goodsCommonData['vipDoubleDiscount']) ? $goodsCommonData['vipDoubleDiscount'] : 0,//会员卡折上折优惠金额
  5295. 'originPayAmount' => $goodsCommonData['payMoney'],//原支付金额,
  5296. 'orderType' => StatusCode::$orderType['cashierOrder'],
  5297. 'verifyCode' => $verifyCode,
  5298. 'expressMoney' => isset($goodsCommonData['expressMoney']) ? $goodsCommonData['expressMoney'] : 0,
  5299. 'cashierUid' => $this->loginUserCenterId,
  5300. 'guideUids' => $params['guideUids'],
  5301. 'cashierName' => $params['cashierName'],
  5302. 'guideName' => $params['guideName'],
  5303. 'remMoney' => isset($goodsCommonData['rem_money']) ? $goodsCommonData['rem_money'] : 0,
  5304. 'changeSubMoney' => isset($goodsCommonData['subPrice']) ? $goodsCommonData['subPrice'] : 0,
  5305. 'isNoneUser' => $this->onlineUserId == StatusCode::$noneUserCenter ? StatusCode::$standard : StatusCode::$delete,
  5306. 'customerMobile' => $params['customerMobile'],
  5307. 'serialNum' => $objStockCache->createSerialSn(0,'Order'),
  5308. 'operatorName' => isset($params['operatorName']) ? $params['operatorName'] : '',
  5309. 'operatorId' => isset($params['operatorId']) ? $params['operatorId'] : 0,
  5310. ];
  5311. $allOrderIds[] = $orderId;
  5312. //2。订单表
  5313. $orderId = $this->objDOrder->insert($masterOrder);
  5314. if ($orderId === false) {
  5315. $this->objDOrder->rollBack();
  5316. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  5317. }
  5318. $masterOrder['goodsName'] = '';
  5319. foreach ($val['shopGoodsData'] as $k => &$v) {
  5320. $addOrderGoods = [
  5321. 'no' => $sn,
  5322. 'orderId' => $orderId,
  5323. 'goodsId' => $v['goodsId'],
  5324. 'goodsName' => $v['goodsName'],
  5325. 'shopId' => $val['shopId'],//商铺id
  5326. 'shopName' => $val['shopName'],//商铺名称
  5327. 'originPrice' => $v['originPrice'],
  5328. 'price' => $v['price'],
  5329. 'buyNum' => $v['buyNum'],
  5330. 'totalMoney' => $v['totalMoney'],
  5331. 'skuId' => $v['skuId'],
  5332. 'goodsBasicId' => $v['goodsBasicId'],
  5333. 'goodsCode' => $v['goodsCode'],
  5334. 'deliverNum' => $v['buyNum'],//发货数量=购买数量
  5335. 'unitName' => $v['unitName'],//单位名称
  5336. 'conversion' => $v['conversion'],//换算比率
  5337. 'preferential' => $v['preferential'],//优惠券优惠金额
  5338. 'vipDiscount' => $v['vipDiscount'],//会员卡优惠金额
  5339. 'categoryPath' => isset($v['categoryPath']) ? $v['categoryPath'] : '',//分类路径
  5340. 'brandId' => isset($v['brandId']) ? $v['brandId'] : 0,//品牌id
  5341. 'specGroup' => isset($v['specGroup']) && !empty($v['specGroup']) ? json_encode($v['specGroup']) : NULL,
  5342. 'goodsImages' => isset($v['goodsImages']) && is_string($v['goodsImages']) ? $v['goodsImages'] : '',
  5343. 'barCode' => isset($v['barCode']) ? $v['barCode'] : '',
  5344. 'storageCode' => isset($v['storageCode']) ? $v['storageCode'] : '',
  5345. 'categoryName' => isset($v['categoryName']) ? $v['categoryName'] : '',
  5346. 'brandName' => isset($v['brandName']) ? $v['brandName'] : '',
  5347. 'expressMoney' => isset($v['expressMoney']) ? $v['expressMoney'] : 0,
  5348. 'outNum' => 0,//已出库数量
  5349. 'outOfNum' => getArrayItem($v, 'buyNum', 0),//未出库数量
  5350. 'isEq' => getArrayItem($v,'isEq',StatusCode::$delete),
  5351. 'extends' => json_encode(getArrayItem($v, 'extends', null)),
  5352. ];
  5353. $lockInventoryData[] = [
  5354. 'warehouseId' => $shopData[$v['shopId']]['warehouseId'],
  5355. 'materielId' => $v['goodsBasicId'],
  5356. 'materielCode' => $v['goodsCode'],
  5357. 'lockingNum' => $v['buyNum'],
  5358. 'originId' => $orderId,
  5359. 'originNo' => $sn,
  5360. 'source' => StatusCode::$orderType['saleOrder'],
  5361. 'sourceNo' => $sn,
  5362. 'operatorId' => $masterOrder['customerId'],
  5363. 'operatorName' => $masterOrder['customerName'],
  5364. 'skuId' => $v['skuId'],
  5365. ];
  5366. $goodsSaleData [] = [
  5367. 'goodsId' => $addOrderGoods['goodsId'],
  5368. 'skuId' => $addOrderGoods['skuId'],
  5369. 'buyNum' => $addOrderGoods['buyNum'],
  5370. ];
  5371. //活动商品数据
  5372. if ($this->isFront) {
  5373. if (isset($v['activityId']) && $v['activityId'] != 0) {
  5374. $activityData[] = [
  5375. 'goodsId' => $v['goodsId'],
  5376. 'skuId' => $v['skuId'],
  5377. 'activityId' => $v['activityId'],
  5378. 'buyNum' => $v['buyNum']
  5379. ];
  5380. }
  5381. }
  5382. $masterOrder['goodsName'] .= $v['goodsName'] . ' ';
  5383. $result = $objMOrderGoods->addOrderGoods($addOrderGoods);
  5384. if (!$result->isSuccess()) {
  5385. $this->objDOrder->rollBack();
  5386. return ResultWrapper::fail($result->getData(), ErrorCode::$dberror);
  5387. }
  5388. $allCartIds[] = $v['cartId'];
  5389. }
  5390. //存入ES
  5391. $masterOrder['verifyCode'] = isset($verifyCode) ? $verifyCode : '';
  5392. self::updateEsData($orderId, $masterOrder, [], $masterOrder['goodsName']);
  5393. $allSn[] = $sn;//所有订单号
  5394. }
  5395. $this->objDOrder->commit();
  5396. $this->objDOrder->beginTransaction();
  5397. //删除购物车内已生成订单商品
  5398. $objMCashierCart = new MCashierCart($this->onlineUserId, $this->onlineEnterpriseId, $this->loginUserCenterId);
  5399. $result = $objMCashierCart->delCart($allCartIds, true);
  5400. if (!$result->isSuccess()) {
  5401. $this->objDOrder->rollBack();
  5402. return ResultWrapper::fail($result->getData(), ErrorCode::$dberror);
  5403. }
  5404. //将优惠券改为已使用
  5405. if (isset($goodsCommonData['useCoupon']) && !empty($goodsCommonData['useCoupon'])) {
  5406. $result = $objMUserCoupon->updateIsUse(['id' => $goodsCommonData['useCoupon']['id']], ['isUse' => StatusCode::$delete, 'useTime' => time()]);
  5407. if (!$result->isSuccess()) {
  5408. $this->objDOrder->rollBack();
  5409. return ResultWrapper::fail($result->getData(), ErrorCode::$dberror);
  5410. }
  5411. }
  5412. //锁定库存商品数量
  5413. $objMInventory = new MInventory($this->onlineEnterpriseId, $this->onlineUserId);
  5414. $lockInventoryResult = $objMInventory->updateLockInventory($shopId,$lockInventoryData);
  5415. if (!$lockInventoryResult->isSuccess()) {
  5416. $this->objDOrder->rollBack();
  5417. return ResultWrapper::fail($lockInventoryResult->getData(), $lockInventoryResult->getErrorCode());
  5418. }
  5419. //增加销量
  5420. $objMGoods = new MGoods($this->onlineEnterpriseId, false, $this->onlineUserId);
  5421. if (!empty($goodsSaleData)) {
  5422. foreach ($goodsSaleData as $value) {
  5423. $res = $objMGoods->updateSalesNum($value['goodsId'], $value['skuId'], $value['buyNum']);
  5424. if ($res === false) {
  5425. Logger::logs(E_USER_ERROR, '错误', __CLASS__, __LINE__, '商品增加销量失败');
  5426. }
  5427. }
  5428. }
  5429. //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);
  5430. $this->objSaleOrder->setGoodsDetails($mapDetails);
  5431. //统计订单信息
  5432. self::noticeStatistics([
  5433. 'userCenterId' => $params['userCenterId'],
  5434. 'enterpriseId' => $this->onlineEnterpriseId,
  5435. 'customerId' => $params['customerId'],
  5436. 'no' => $allSn,
  5437. 'noticeType' => 'create',
  5438. ], 'MOrderStatistics');
  5439. //写日志
  5440. foreach ($allSn as $sn) {
  5441. parent::saveLog([
  5442. 'no' => $sn,
  5443. 'actionType' => '创建订单',//创建订单
  5444. 'operationData' => '',
  5445. 'userCenterId' => $params['userCenterId'],
  5446. 'enterpriseId' => $this->onlineEnterpriseId,
  5447. 'createTime' => time(),
  5448. ]);
  5449. }
  5450. //自动审核订单
  5451. $objMInventoryOut = new MInventoryOut($this->onlineEnterpriseId, $this->onlineUserId);
  5452. foreach ($allOrderIds as $key => $id) {
  5453. //自动审核订单
  5454. $auditResult = self::updateAuditStatus([
  5455. 'id' => $id,
  5456. 'audit' => '自动审核',
  5457. 'auditId' => $this->onlineUserId,
  5458. 'auditStatus' => StatusCode::$auditStatus['auditPass']
  5459. ]);
  5460. if (!$auditResult->isSuccess()) {
  5461. $this->objDOrder->rollBack();
  5462. return ResultWrapper::fail($auditResult->getData(), $auditResult->getErrorCode());
  5463. }
  5464. $outId = $auditResult->getData();//出库单id
  5465. //自动出库
  5466. $dbResult = $objMInventoryOut->updateInventoryOutStatus(['id' => $outId, 'auditId' => $this->loginUserCenterId, 'auditName' => '销售自动审核']);
  5467. if (!$dbResult->isSuccess()) {
  5468. $this->objDOrder->rollBack();
  5469. return ResultWrapper::fail($dbResult->getData(), $dbResult->getErrorCode());
  5470. }
  5471. }
  5472. //确认收款
  5473. $dbResult = self::updateOrderPayData(['payStatus' => StatusCode::$standard, 'payTime' => time()], ['id' => $allOrderIds]);
  5474. if (!$dbResult->isSuccess()) {
  5475. $this->objDOrder->rollBack();
  5476. return ResultWrapper::fail($dbResult->getData(), $dbResult->getErrorCode());
  5477. }
  5478. //确认收货
  5479. foreach ($allOrderIds as $orderId) {
  5480. $dbResult = self::updateOrderStatus($orderId, ['orderStatus' => StatusCode::$orderStatus['finish']], []);
  5481. if (!$dbResult->isSuccess()) {
  5482. $this->objDOrder->rollBack();
  5483. return ResultWrapper::fail($dbResult->getData(), $dbResult->getErrorCode());
  5484. }
  5485. $objMCashier = new MCashier($this->onlineUserId, $this->onlineEnterpriseId);
  5486. $cashierResult = $objMCashier->calculatePushMoney($orderId);
  5487. if (!$cashierResult->isSuccess()) {
  5488. Logger::logs(E_USER_ERROR, '订单提成计算失败', __CLASS__, __LINE__, $cashierResult->getData());
  5489. }
  5490. }
  5491. //创建收款单
  5492. $received = [
  5493. 'currentAccountName' => $params['currentAccountName'],
  5494. 'financeType' => '销售收款',
  5495. 'financeTypeId' => 2,
  5496. 'shopId' => $shopId,
  5497. 'shopName' => $shopName,
  5498. 'receiptTime' => time(),
  5499. 'operatorId' => $this->loginUserCenterId,
  5500. 'accountList' => $params['accountList'],
  5501. 'customerId' => $customerData['id'],
  5502. 'customerName' => $customerData['name'],
  5503. 'sourceNo' => $sn,
  5504. 'sourceNoMoney' => $goodsCommonData['payMoney'],
  5505. 'createTime' => time(),
  5506. 'auditStatus' => StatusCode::$auditStatus['auditing'],
  5507. 'updateTime' => time(),
  5508. ];
  5509. $objMReceived = new MReceived($this->onlineEnterpriseId, $this->loginUserCenterId);
  5510. $receivedResult = $objMReceived->addReceived($received, true);
  5511. if (!$receivedResult->isSuccess()) {
  5512. $this->objDOrder->rollBack();
  5513. return ResultWrapper::fail($receivedResult->getData(), $receivedResult->getErrorCode());
  5514. }
  5515. $this->objDOrder->commit();
  5516. if ($this->onlineUserId == StatusCode::$noneUserCenter) {
  5517. $objDCashierCustomerPrice = new DCashierCustomerPrice();
  5518. $objDCashierCustomerPrice->setTable('qianniao_cashier_customer_price_' . $this->onlineEnterpriseId);
  5519. $objDCashierCustomerPrice->delete(['cashierUid' => $this->loginUserCenterId, 'customerUid' => StatusCode::$noneUserCenter]);
  5520. }
  5521. return ResultWrapper::success($orderId);
  5522. }
  5523. /**
  5524. * 订单打印小票
  5525. */
  5526. public function printOrder()
  5527. {
  5528. $data = [];
  5529. $goodsDetails = $this->objSaleOrder->getGoodsDetails();
  5530. foreach ($goodsDetails as $value) {
  5531. $data[$value['goodsId']]['title'] = $value['goodsName'];
  5532. $data[$value['goodsId']]['skuData'][] = [
  5533. 'skuName' => isset($value['specName']) ? $value['specName'] : '',
  5534. 'unitName' => isset($value['unitName']) ? $value['unitName'] : '',
  5535. 'unitPrice' => isset($value['unitPrice']) ? $value['unitPrice'] : 0.00,
  5536. 'num' => isset($value['buyNum']) ? $value['buyNum'] : 0,
  5537. 'amountPrice' => isset($value['totalMoney']) ? $value['totalMoney'] : 0
  5538. ];
  5539. }
  5540. $printData = [
  5541. 'createTime' => $this->objSaleOrder->getCreateTime(),
  5542. 'shopName' => $this->objSaleOrder->getShopName(),
  5543. 'title' => $this->objSaleOrder->getReceiptTitle(),
  5544. 'codeName' => $this->objSaleOrder->getCodeName(),
  5545. 'code' => $this->objSaleOrder->getNo(),
  5546. 'userName' => $this->objSaleOrder->getCustomerName(),
  5547. 'mobile' => $this->objSaleOrder->getCustomerMobile(),
  5548. 'preferential' => $this->objSaleOrder->getPreferentialAmount(), //优惠金额
  5549. 'totalMoney' => $this->objSaleOrder->getTotalAmount(),
  5550. 'payAmount' => $this->objSaleOrder->getPayAmount(),
  5551. 'address' => $this->objSaleOrder->getAddress(),
  5552. 'details' => $data
  5553. ];
  5554. $formatPrint = parent::formatMsg($printData);
  5555. $objCloudPrint = new CloudPrint();
  5556. $objCloudPrint->sendMsg($formatPrint, $this->onlineEnterpriseId);
  5557. }
  5558. /**
  5559. * 将所有商品库存转换为主单位sku
  5560. * @param $data
  5561. * @return array|ResultWrapper
  5562. * @throws \Exception
  5563. */
  5564. public function formatMerge($data)
  5565. {
  5566. //将相同的商品合并到一起并启用到主单位的
  5567. $allMapping = [];
  5568. if (empty($data)) return $data;
  5569. $allMapping = [];
  5570. $all = [];
  5571. $objMSku = new MSku($this->onlineUserId, $this->onlineEnterpriseId);
  5572. $res = $objMSku->getMaterSkuId(['goodsId' => array_values(array_unique(array_column($data, 'goodsBasicId'))), 'isMaster' => StatusCode::$standard, 'deleteStatus' => StatusCode::$standard]);
  5573. if (!$res->isSuccess()) {
  5574. return ResultWrapper::fail($res->getData(), ErrorCode::$dberror);
  5575. }
  5576. $skuData = $res->getData();
  5577. foreach ($data as &$goods) {
  5578. $goods['masterSkuId'] = $skuData[$goods['goodsBasicId']];
  5579. $allMapping[$goods['goodsId']][] = [
  5580. 'buyNum' => $goods['conversion'] == 0 ? $goods['buyNum'] : bcdiv($goods['buyNum'], $goods['conversion'], 2),
  5581. 'skuId' => $goods['skuId'],
  5582. 'conversion' => $goods['conversion'],
  5583. 'goodsId' => $goods['goodsId'],
  5584. 'masterSkuId' => $goods['masterSkuId']
  5585. ];
  5586. }
  5587. unset($goods);
  5588. foreach ($allMapping as $key => $goods) {
  5589. $all[] = [
  5590. 'buyNum' => array_sum(array_column($allMapping[$key], 'buyNum')),
  5591. 'goodsId' => $goods[0]['goodsId'],
  5592. 'skuId' => $goods[0]['masterSkuId'],//都换算成主单位的
  5593. ];
  5594. }
  5595. return ResultWrapper::success($all);
  5596. }
  5597. /**
  5598. * 确认收款检测出库状态
  5599. * @param $id
  5600. * @return ResultWrapper
  5601. */
  5602. public function checkOutOrderStatus($id)
  5603. {
  5604. $dbResult = $this->objDOrder->get_field('outStatus', ['id' => $id]);
  5605. if ($dbResult === false) {
  5606. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  5607. }
  5608. if (empty($dbResult)) {
  5609. return ResultWrapper::fail('没有找到订单信息', ErrorCode::$paramError);
  5610. }
  5611. if ($dbResult == StatusCode::$delete) {
  5612. return ResultWrapper::fail('订单未出库暂时不能确认收款', ErrorCode::$paramError);
  5613. }
  5614. return ResultWrapper::success($dbResult);
  5615. }
  5616. /**
  5617. * 销售订单毛利明细
  5618. * @param $params
  5619. * @return ResultWrapper
  5620. * @throws \Exception
  5621. */
  5622. public function getOrderProfit($params,$export = 0)
  5623. {
  5624. $limit = $params['limit'];
  5625. unset($params['limit']);
  5626. $offset = $params['offset'];
  5627. unset($params['offset']);
  5628. if($export){
  5629. $limit = 999;
  5630. $offset = 0;
  5631. }
  5632. $modelResult = self::formatOrderTableName($params);
  5633. if (!$modelResult->isSuccess()) {
  5634. return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
  5635. }
  5636. $tables = $modelResult->getData();
  5637. if (empty($tables)) {
  5638. return ResultWrapper::fail('表后缀计算失败', ErrorCode::$paramError);
  5639. }
  5640. $whereSql = ' where o.shopId = ' . $params['shopId'] . ' and g.goodsId = ' . $params['goodsId'] . ' and o.createTime between ' . $params['start'] . ' and ' . $params['end'];
  5641. if (isset($params['customerId']) && !empty($params['customerId'])) {
  5642. $whereSql .= ' and customerId = ' . $params['customerId'];
  5643. }
  5644. $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';
  5645. $sql = '';
  5646. foreach ($tables as $value) {
  5647. !empty($sql) && $sql = $sql . ' union all ';
  5648. $orderTableName = 'qianniao_order_' . $this->onlineEnterpriseId . '_' . $value;
  5649. $orderGoodsTableName = 'qianniao_order_goods_' . $this->onlineEnterpriseId . '_' . $value;
  5650. $sql = '(select ' . $field . ' from ' . $orderGoodsTableName . ' g left join ' . $orderTableName . ' o on o.id = g.orderId ' . $whereSql . ')';
  5651. }
  5652. $twoField = 'orderId,no,customerId,customerName,createTime,shopId,shopName,orderStatus,outStatus,orderType,goodsId,goodsCode,goodsName,price,buyNum,discount,outCostPrice,goodsBasicId,skuId,totalMoney';
  5653. $sql = 'select ' . $twoField . ' from (' . $sql . ') as details ';
  5654. $selectSql = $sql . 'order by createTime desc limit ' . $offset . ',' . $limit;
  5655. $dbResult = $this->objDOrder->query($selectSql);
  5656. if ($dbResult === false) {
  5657. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$paramError);
  5658. }
  5659. //提取客户数据
  5660. if (empty($dbResult)) {
  5661. return ResultWrapper::fail('查询结果为空', ErrorCode::$dberror);
  5662. }
  5663. $customerData = [];
  5664. foreach ($dbResult as &$value) {
  5665. if (!isset($customerData[$value['customerId']])) {
  5666. $customerData[$value['customerId']] = [
  5667. 'id' => $value['customerId'],
  5668. 'name' => $value['customerName'],
  5669. ];
  5670. }
  5671. //销售成本
  5672. $value['saleCostAmount'] = bcmul($value['buyNum'], $value['outCostPrice'], 4);
  5673. //销售毛利
  5674. $value['saleProfitAmount'] = bcsub($value['totalMoney'], $value['saleCostAmount'], 8);
  5675. //毛利率
  5676. $value['saleProfitRate'] = "0.00";
  5677. if ($value['saleProfitAmount'] > 0 && $value['saleCostAmount'] > 0) {
  5678. $value['saleProfitRate'] = bcmul(bcdiv($value['saleProfitAmount'], $value['totalMoney'], 8), 100, 4);
  5679. }
  5680. }
  5681. unset($value);
  5682. if($export){
  5683. self::exportOrderProfit($dbResult);
  5684. exit;
  5685. }
  5686. $countSql = 'select count(orderId) as count from ( ' . $sql . ' ) as selectDetails';
  5687. $totalDbResult = $this->objDOrder->query($countSql);
  5688. if ($totalDbResult === false) {
  5689. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  5690. }
  5691. $total = array_shift($totalDbResult)['count'];
  5692. $return['data']['customerData'] = array_values($customerData);
  5693. $return['data']['data'] = $dbResult;
  5694. $return['total'] = ($total) ? intval($total) : 0;
  5695. return ResultWrapper::success($return);
  5696. }
  5697. /**
  5698. * 计算表名后缀
  5699. * @param $params
  5700. * @return ResultWrapper
  5701. * @throws \Exception
  5702. */
  5703. public function formatOrderTableName($params)
  5704. {
  5705. $whereSql = '';
  5706. if (isset($params['shopId']) && !empty($params['shopId'])) {
  5707. $whereSql = empty($whereSql) ? $whereSql . ' where ' : $whereSql . ' and ';
  5708. $whereSql .= ' shopId = ' . $params['shopId'];
  5709. }
  5710. if (isset($params['customerId']) && !empty($params['customerId'])) {
  5711. $whereSql = empty($whereSql) ? $whereSql . ' where ' : $whereSql . ' and ';
  5712. $whereSql .= ' customerId = ' . $params['customerId'];
  5713. }
  5714. if (isset($params['start']) && !empty($params['start']) && isset($params['end']) && !empty($params['end'])) {
  5715. $whereSql = empty($whereSql) ? $whereSql . ' where ' : $whereSql . ' and ';
  5716. $whereSql .= ' createTime between ' . $params['start'] . ' and ' . $params['end'];
  5717. }
  5718. $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId);
  5719. $indexSql = 'select userCenterId from ' . $this->objDOrderIndex->get_Table() . $whereSql;
  5720. $dbResult = $this->objDOrderIndex->query($indexSql);
  5721. if ($dbResult === false) {
  5722. return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$paramError);
  5723. }
  5724. if (empty($dbResult)) {
  5725. return ResultWrapper::success([]);
  5726. }
  5727. $tables = [];
  5728. foreach ($dbResult as $value) {
  5729. //格式化数据 根据userCenterId 计算所有goods表名
  5730. $num = (int)ceil($value['userCenterId'] / $this->cutTable);
  5731. $tableName = 'qianniao_order_' . $this->onlineEnterpriseId . '_' . $num;
  5732. $existsTable = $this->objDOrder->existsTable($tableName);
  5733. if ($existsTable && !in_array($num, $tables)) {
  5734. $tables[] = $num;
  5735. }
  5736. }
  5737. return ResultWrapper::success($tables);
  5738. }
  5739. /************************************************统计项 start******************************************************/
  5740. /**
  5741. * @param $key
  5742. * @param $shopId
  5743. * @return ResultWrapper
  5744. */
  5745. public function businessOverview($key, $shopId)
  5746. {
  5747. $result = $this->objOverviewCache->getBusinessOverview($this->onlineEnterpriseId, $key, $shopId);
  5748. return $result;
  5749. }
  5750. /**
  5751. * 客单价
  5752. * @param $key
  5753. * @param $shopId
  5754. * @return int|string
  5755. */
  5756. public function customerAverageMoney($key, $shopId)
  5757. {
  5758. $objCustomerCache = new CustomerCache();
  5759. $orderConfirmedMoney = $this->objOverviewCache->getBusinessOverview($this->onlineEnterpriseId, 'orderConfirmedMoney', $shopId);//营业额
  5760. $customerNum = array_sum($objCustomerCache->getTodayCustomerOrderInfo($this->onlineEnterpriseId, null, $shopId));
  5761. if ($orderConfirmedMoney == 0 || $customerNum == 0) return 0;
  5762. return bcdiv($orderConfirmedMoney, $customerNum, 2);
  5763. }
  5764. /**
  5765. * 后置操作
  5766. */
  5767. public function __destruct()
  5768. {
  5769. // TODO: Implement __destruct() method.
  5770. if ($this->isEnablePrint) self::printOrder();
  5771. }
  5772. /**
  5773. * 今日下单客户数量
  5774. * @param $shopId
  5775. * @return int
  5776. */
  5777. public function getTodayCustomerOrderNum($shopId = null)
  5778. {
  5779. $todayStart = date('Y-m-d 00:00:00', time());
  5780. $todayEnd = date('Y-m-d 23:59:59', time());
  5781. $fields = 'id';
  5782. $sql = 'SELECT ' . $fields . ' FROM qianniao_order_index_' . $this->onlineEnterpriseId . '
  5783. WHERE auditStatus = ' . StatusCode::$auditStatus['auditPass'] . ' AND
  5784. createTime BETWEEN ' . strtotime($todayStart) . ' AND ' . strtotime($todayEnd);
  5785. if (!empty($shopId)) {
  5786. $sql .= ' and shopId = ' . $shopId;
  5787. }
  5788. $sql .= ' GROUP BY customerId';
  5789. $result = $this->objDOrder->query($sql);
  5790. if ($result === false) {
  5791. Logger::logs(E_USER_ERROR, '查询错误', __CLASS__, __LINE__, $this->objDOrder->error());
  5792. return 0;
  5793. }
  5794. return count((array)$result);
  5795. }
  5796. /**
  5797. * 今日客单价
  5798. * @param null $shopId
  5799. * @return int|string|null
  5800. */
  5801. public function getTodayOrder($shopId = null)
  5802. {
  5803. $todayStart = date('Y-m-d 00:00:00', time());
  5804. $todayEnd = date('Y-m-d 23:59:59', time());
  5805. $fields = 'userCenterId';
  5806. if (!empty($shopId)) {
  5807. $shopId = ' and shopId = ' . $shopId;
  5808. }else{
  5809. $shopId = '';
  5810. }
  5811. $sql = 'select count(distinct '.$fields.') as num ,sum(payAmount) as money from qianniao_order_'. $this->onlineEnterpriseId .'_1' .
  5812. ' where auditStatus = ' . StatusCode::$auditStatus['auditPass'] .'
  5813. and createTime BETWEEN '.strtotime($todayStart). ' and '. strtotime($todayEnd).$shopId;
  5814. $result = $this->objDOrder->query($sql);
  5815. if ($result === false) {
  5816. return 0;
  5817. }
  5818. $num = $result[0]['num'];
  5819. $money = $result[0]['money'];
  5820. if (empty($money) || empty($num)) {
  5821. return 0;
  5822. }
  5823. return bcdiv($money, $num, 2);
  5824. }
  5825. /**
  5826. * Doc: (des="订单分配业务员")
  5827. * User: XMing
  5828. * Date: 2020/8/26
  5829. * Time: 3:39 下午
  5830. * @param array $params
  5831. * @return ResultWrapper
  5832. * @throws \Exception
  5833. */
  5834. public function setSalesMan(array $params)
  5835. {
  5836. //在索引表中查询订单
  5837. $orderIndex = $this->objDOrderIndex->get(['id' => $params['orderId']]);
  5838. if ($orderIndex === false) {
  5839. return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
  5840. }
  5841. if (empty($orderIndex)) {
  5842. return ResultWrapper::fail('未查询到指定订单', ErrorCode::$paramError);
  5843. }
  5844. if (!empty($orderIndex['salesManId'])) {
  5845. return ResultWrapper::fail('已分配过业务员', ErrorCode::$paramError);
  5846. }
  5847. $dbResult = $this->objDCustomer->get(['id' => $orderIndex['customerId']]);
  5848. if ($dbResult === false) {
  5849. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  5850. }
  5851. $customerInfo = $dbResult;
  5852. if (empty($customerInfo)) {
  5853. return ResultWrapper::fail('未查询到指定客户', ErrorCode::$dberror);
  5854. }
  5855. if($params['ifSalesMan'] == StatusCode::$delete){
  5856. if ( !empty($customerInfo['salesManId']) && $customerInfo['salesManId'] != $params['salesManId'] ) {
  5857. return ResultWrapper::fail('客户只能分配当前 -'.$customerInfo['salesManName'].' -业务员', ErrorCode::$paramError);
  5858. }
  5859. $salesManId = $params['salesManId'];
  5860. $salesManName = $params['salesManName'];
  5861. }else{
  5862. $salesManId = $customerInfo['salesManId'];
  5863. $salesManName = $customerInfo['salesManName'];
  5864. }
  5865. //更新数据
  5866. $time = time();
  5867. $beginStatus = $this->objDOrderIndex->beginTransaction();
  5868. //给客户分配业务员
  5869. if($params['ifSalesMan'] == StatusCode::$delete){
  5870. $dbResult = $this->objDCustomer->update(['salesManId' => $salesManId, 'salesManName' => $salesManName], ['id' => $orderIndex['customerId']]);
  5871. if ($dbResult === false) {
  5872. $this->objDOrderIndex->rollBack();
  5873. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  5874. }
  5875. }
  5876. //更新订单表
  5877. //只更新该订单
  5878. $dbResult = $this->objDOrderIndex->update(['salesManId' => $salesManId, 'updateTime' => $time], ['id' => $params['orderId']]);
  5879. if($dbResult === false){
  5880. $this->objDOrderIndex->rollBack();
  5881. return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
  5882. }
  5883. $updateData = ['salesManId' => $salesManId, 'salesManName' => $salesManName, 'updateTime' => $time];
  5884. $dbResult = $this->objDOrder->update($updateData, ['id' => $params['orderId']]);
  5885. if($dbResult === false){
  5886. $this->objDOrderIndex->rollBack();
  5887. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  5888. }
  5889. /* //获取此客户未分配业务员的订单
  5890. $orderIndexLists = $this->objDOrderIndex->select(['salesManId' => 0, 'customerId' => $orderIndex['customerId']]);
  5891. if ($orderIndexLists === false) {
  5892. $this->objDOrderIndex->rollBack();
  5893. return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
  5894. }
  5895. if (empty($orderIndexLists)) {
  5896. $this->objDOrderIndex->rollBack();
  5897. return ResultWrapper::fail('未查询到需要更新的数据', ErrorCode::$paramError);
  5898. }
  5899. //计算数据的分表
  5900. $updateData = ['salesManId' => $params['salesManId'], 'salesManName' => $params['salesManName'], 'updateTime' => $time];
  5901. $allGroupData = [];
  5902. $allOrderIds = [];
  5903. foreach ($orderIndexLists as $key => $val) {
  5904. $tableNum = ceil($val['userCenterId'] / $this->cutTable);
  5905. $allGroupData[$tableNum][] = $val['id'];
  5906. $allOrderIds[] = $val['id'];
  5907. }
  5908. //更新订单索引表
  5909. $updateOrderIndex = $this->objDOrderIndex->update(['salesManId' => $params['salesManId'], 'updateTime' => $time], ['id' => $allOrderIds]);
  5910. if ($updateOrderIndex === false) {
  5911. $this->objDOrderIndex->rollBack();
  5912. return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
  5913. }
  5914. //在对应分表中更新数据
  5915. foreach ($allGroupData as $k => $orderIds) {
  5916. $this->objDOrder->setTable('qianniao_order_' . $this->onlineEnterpriseId . '_' . $k);
  5917. $updateOrder = $this->objDOrder->update($updateData, ['id' => $orderIds]);
  5918. if ($updateOrder === false) {
  5919. $this->objDOrderIndex->rollBack();
  5920. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  5921. }
  5922. }*/
  5923. /*
  5924. //修改es
  5925. foreach ($allOrderIds as $orderId) {
  5926. $_id = self::createEsDocumentId($orderId);
  5927. $this->objDOrder->esupdateTypeFieldVaule($updateData, $_id);
  5928. }*/
  5929. $beginStatus && $this->objDOrderIndex->commit();
  5930. return ResultWrapper::success('操作成功');
  5931. }
  5932. /**
  5933. * Doc: (des="")
  5934. * User: XMing
  5935. * Date: 2020/9/4
  5936. * Time: 12:21 下午
  5937. * @param string $verifyCode
  5938. * @return ResultWrapper
  5939. * @throws \Exception
  5940. */
  5941. public function getOrderByVerifyCode(string $verifyCode)
  5942. {
  5943. $orderId = $this->objDOrderIndex->get_field('id', ['verifyCode' => $verifyCode]);
  5944. if ($orderId === false) {
  5945. return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
  5946. }
  5947. if (empty($orderId)) {
  5948. return ResultWrapper::fail('核销码已失效或不存在', ErrorCode::$paramError);
  5949. }
  5950. $orderInfoResult = self::getOrderInfoById($orderId);
  5951. if (!$orderInfoResult->isSuccess()) {
  5952. return ResultWrapper::fail($orderInfoResult->getData(), $orderInfoResult->getErrorCode());
  5953. }
  5954. return ResultWrapper::success($orderInfoResult->getData());
  5955. }
  5956. /**
  5957. * Doc: (des="核销订单")
  5958. * User: XMing
  5959. * Date: 2020/9/4
  5960. * Time: 2:34 下午
  5961. * @param int $id
  5962. * @param array $header
  5963. * @return ResultWrapper
  5964. * @throws \Exception
  5965. */
  5966. public function verification(int $id, $header)
  5967. {
  5968. $orderInfo = $this->objDOrderIndex->get(['id' => $id]);
  5969. if ($orderInfo === false) {
  5970. return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
  5971. }
  5972. if (empty($orderInfo)) {
  5973. return ResultWrapper::fail('未获取到指定订单', ErrorCode::$paramError);
  5974. }
  5975. if ($orderInfo['orderStatus'] == StatusCode::$orderStatus['close']) {
  5976. return ResultWrapper::fail('订单已取消', ErrorCode::$paramError);
  5977. }
  5978. if ($orderInfo['orderStatus'] == StatusCode::$orderStatus['finish']) {
  5979. return ResultWrapper::fail('订单已经核销过了', ErrorCode::$paramError);
  5980. }
  5981. if ($orderInfo['auditStatus'] != StatusCode::$auditStatus['auditPass']) {
  5982. return ResultWrapper::fail('订单尚未审核', ErrorCode::$paramError);
  5983. }
  5984. if ($orderInfo['outStatus'] != StatusCode::$standard) {
  5985. return ResultWrapper::fail('订单还没有出库,不能进行核销操作', ErrorCode::$paramError);
  5986. }
  5987. $orderResult = self::updateOrderStatus($id, ['orderStatus' => StatusCode::$standard], $header);
  5988. if (!$orderResult->isSuccess()) {
  5989. return ResultWrapper::fail($orderResult->getData(), $orderResult->getErrorCode());
  5990. }
  5991. return ResultWrapper::success($orderResult->getData());
  5992. }
  5993. /**
  5994. * Doc: (des="")
  5995. * User: XMing
  5996. * Date: 2020/9/8
  5997. * Time: 7:14 下午
  5998. * @param int $id
  5999. * @return ResultWrapper
  6000. */
  6001. public function getExpressInfoByOrderId(int $id)
  6002. {
  6003. $orderIndex = $this->objDOrderIndex->get(['id' => $id]);
  6004. if ($orderIndex === false) {
  6005. return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
  6006. }
  6007. if (empty($orderIndex)) {
  6008. return ResultWrapper::fail('为获取到指定订单', ErrorCode::$paramError);
  6009. }
  6010. if (empty($orderIndex['deliveryNo']) || empty($orderIndex['expressId'])) {
  6011. return ResultWrapper::success([]);
  6012. }
  6013. $objDExpressCode = new DExpressCode();
  6014. $expressCode = $objDExpressCode->get(['id' => $orderIndex['expressId']]);
  6015. if ($expressCode === false) {
  6016. return ResultWrapper::fail($objDExpressCode->error(), ErrorCode::$dberror);
  6017. }
  6018. if (empty($expressCode)) {
  6019. return ResultWrapper::fail('获取物流信息失败', ErrorCode::$paramError);
  6020. }
  6021. $objMBasicSetup = new MBasicSetup($this->onlineEnterpriseId);
  6022. $basicSetupResult = $objMBasicSetup->getBasicField('logistics_form');
  6023. if (!$basicSetupResult->isSuccess()) {
  6024. return ResultWrapper::fail($basicSetupResult->getData(), $basicSetupResult->getErrorCode());
  6025. }
  6026. $basicSetup = $basicSetupResult->getData();
  6027. $basicSetup = isset($basicSetup['logistics_form']) ? $basicSetup['logistics_form'] : [];
  6028. if (!isset($basicSetup['express_type']) || empty($basicSetup['express_type'])) {
  6029. return ResultWrapper::fail('未配置物流接口', ErrorCode::$paramError);
  6030. }
  6031. $map = [];
  6032. $return = [
  6033. 'list' => [],
  6034. 'stateMsg' => '',
  6035. 'nu' => $orderIndex['deliveryNo'],
  6036. 'expressName' => $expressCode['name']
  6037. ];
  6038. switch ($basicSetup['express_type']) {
  6039. case 'express_hundred':
  6040. $fix = ceil($orderIndex['userCenterId'] / $this->cutTable);
  6041. $this->objDOrderReceive->setTable('qianniao_order_receive_' . $this->onlineEnterpriseId . '_' . $fix);
  6042. $mobile = $this->objDOrderReceive->get_field('mobile', ['orderId' => $orderIndex['id']]);
  6043. if ($mobile === false) {
  6044. return ResultWrapper::fail($this->objDOrderReceive->error(), ErrorCode::$dberror);
  6045. }
  6046. if (!isset($basicSetup['express_hundred'])) {
  6047. return ResultWrapper::fail('快递100未进行配置', ErrorCode::$paramError);
  6048. }
  6049. $express_hundred = $basicSetup['express_hundred'];
  6050. if (!isset($express_hundred['customerCode']) || empty($express_hundred['customerCode']) ||
  6051. !isset($express_hundred['accessKey']) || empty($express_hundred['accessKey'])) {
  6052. return ResultWrapper::fail('快递100配置有误', ErrorCode::$paramError);
  6053. }
  6054. /*$kuaidi100Config = Factory::config()->get('kuaidi100');
  6055. if(empty($kuaidi100Config) || !isset($kuaidi100Config['customer']) || !isset($kuaidi100Config['key']) ){
  6056. return ResultWrapper::fail('快递100配置有误',ErrorCode::$paramError);
  6057. }*/
  6058. //$objQuery = new Query($kuaidi100Config['customer'], $kuaidi100Config['key']);
  6059. /*$kuaidiData = [
  6060. 'com' => 'yunda',
  6061. 'num' => '3103922659603',
  6062. 'phone' => 17600105150,
  6063. ];*/
  6064. $objQuery = new Query($express_hundred['customerCode'], $express_hundred['accessKey']);
  6065. $kuaidiData = [
  6066. 'com' => $expressCode['kuaidi100'],
  6067. 'num' => $orderIndex['deliveryNo'],
  6068. 'phone' => $mobile,
  6069. ];
  6070. $result = $objQuery->pollQuery($kuaidiData);
  6071. if (!$result->isSuccess()) {
  6072. return ResultWrapper::fail('获取物流信息失败', ErrorCode::$paramError);
  6073. }
  6074. $resultData = $result->getData();
  6075. $list = isset($resultData['data']) ? $resultData['data'] : [];
  6076. $return['stateMsg'] = $objQuery->getState(isset($resultData['state']) ? $resultData['state'] : 0);
  6077. $map = self::formatExpressList($list, 'express_hundred');
  6078. break;
  6079. case 'express_bird':
  6080. if (!isset($basicSetup['express_bird'])) {
  6081. return ResultWrapper::fail('快递鸟未进行配置', ErrorCode::$paramError);
  6082. }
  6083. $express_bird = $basicSetup['express_bird'];
  6084. if (!isset($express_bird['userId']) || empty($express_bird['userId']) ||
  6085. !isset($express_bird['apiKey']) || empty($express_bird['apiKey'])) {
  6086. return ResultWrapper::fail('快递鸟配置有误', ErrorCode::$paramError);
  6087. }
  6088. /*$kdniaoConfig = Factory::config()->get('kdniao');
  6089. if(empty($kdniaoConfig) || !isset($kdniaoConfig['EBusinessID']) || !isset($kdniaoConfig['key']) ){
  6090. return ResultWrapper::fail('快递鸟配置错误', ErrorCode::$configEroor);
  6091. }*/
  6092. //$objQuery = new KDNiaoQuery($kdniaoConfig['EBusinessID'], $kdniaoConfig['key']);
  6093. /*$kuaidiData = [
  6094. 'com' => 'HTKY',
  6095. 'num' => '557021498255630',
  6096. ];*/
  6097. $objQuery = new KDNiaoQuery($express_bird['userId'], $express_bird['apiKey']);
  6098. $kuaidiData = [
  6099. 'com' => $expressCode['kdniao'],
  6100. 'num' => $orderIndex['deliveryNo'],
  6101. ];
  6102. $result = $objQuery->EbusinessOrderHandle($kuaidiData);
  6103. if (!$result->isSuccess()) {
  6104. return ResultWrapper::fail('获取物流信息失败', ErrorCode::$paramError);
  6105. }
  6106. $resultData = $result->getData();
  6107. $list = isset($resultData['Traces']) ? $resultData['Traces'] : [];
  6108. $return['stateMsg'] = $objQuery->getState(isset($resultData['State']) ? $resultData['State'] : 0);
  6109. $map = self::formatExpressList($list, 'express_bird');
  6110. break;
  6111. }
  6112. $return['list'] = $map;
  6113. return ResultWrapper::success($return);
  6114. }
  6115. /**
  6116. * Doc: (des="修改订单的发货信息")
  6117. * User: XMing
  6118. * Date: 2020/9/9
  6119. * Time: 11:12 上午
  6120. * @param string $no
  6121. * @param array $params
  6122. * @param int $orderId
  6123. * @return ResultWrapper
  6124. * @throws \Exception
  6125. */
  6126. public function editOrderExpress(string $no, array $params, int $orderId = 0)
  6127. {
  6128. if (empty($orderId)) {
  6129. $orderIndex = $this->objDOrderIndex->get(['no' => $no]);
  6130. } else {
  6131. $orderIndex = $this->objDOrderIndex->get(['id' => $orderId]);
  6132. }
  6133. if ($orderIndex === false) {
  6134. return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
  6135. }
  6136. if (empty($orderIndex)) {
  6137. return ResultWrapper::fail('未获取到指定订单信息' . $no, ErrorCode::$paramError);
  6138. }
  6139. $fix = ceil($orderIndex['userCenterId'] / $this->cutTable);
  6140. $this->objDOrder->setTable('qianniao_order_' . $this->onlineEnterpriseId . '_' . $fix);
  6141. $this->objDOrderIndex->beginTransaction();
  6142. if (isset($params['deliveryType']) && $params['deliveryType'] == StatusCode::$deliveryType['logistics']){
  6143. $update = [
  6144. 'logisticsData' => json_encode($params['logisticsData']),
  6145. 'updateTime' => time(),
  6146. ];
  6147. }else{
  6148. $update = [
  6149. 'deliveryNo' => isset($params['deliveryNo']) ? $params['deliveryNo'] : '',
  6150. 'expressName' => isset($params['expressName']) ? $params['expressName'] : '',
  6151. 'expressId' => isset($params['expressId']) ? $params['expressId'] : 0,
  6152. 'updateTime' => time(),
  6153. ];
  6154. $updateIndex = $this->objDOrderIndex->update($update, ['id' => $orderIndex['id']]);
  6155. if ($updateIndex === false) {
  6156. $this->objDOrderIndex->rollBack();
  6157. return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
  6158. }
  6159. }
  6160. $updateOrder = $this->objDOrder->update($update, ['id' => $orderIndex['id']]);
  6161. if ($updateOrder === false) {
  6162. $this->objDOrderIndex->rollBack();
  6163. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  6164. }
  6165. //记录司机id
  6166. $driverId = isset($params['logisticsData']['id']) ? $params['logisticsData']['id'] : '';
  6167. $updatedriverId = $this->objDOrder->update(['driverId'=>$driverId],['id' => $orderIndex['id']]);
  6168. if ($updatedriverId === false) {
  6169. $this->objDOrderIndex->rollBack();
  6170. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  6171. }
  6172. /*
  6173. $_id = self::createEsDocumentId($orderIndex['id']);
  6174. $this->objDOrder->esupdateTypeFieldVaule($update, $_id);*/
  6175. $this->objDOrderIndex->commit();
  6176. return ResultWrapper::success(true);
  6177. }
  6178. /**
  6179. * Doc: (des="")
  6180. * User: XMing
  6181. * Date: 2020/9/8
  6182. * Time: 8:47 下午
  6183. * @param array $list
  6184. * @param string $type
  6185. * @return array
  6186. */
  6187. private function formatExpressList(array $list, string $type)
  6188. {
  6189. $map = [];
  6190. switch ($type) {
  6191. case 'express_hundred':
  6192. foreach ($list as $value) {
  6193. $map[] = [
  6194. 'context' => $value['context'],
  6195. 'time' => $value['time']
  6196. ];
  6197. }
  6198. break;
  6199. case 'express_bird':
  6200. foreach ($list as $value) {
  6201. $map[] = [
  6202. 'context' => $value['AcceptStation'],
  6203. 'time' => $value['AcceptTime']
  6204. ];
  6205. }
  6206. $map = array_reverse($map);
  6207. break;
  6208. }
  6209. return $map;
  6210. }
  6211. /**
  6212. * Doc: (des="")
  6213. * User: XMing
  6214. * Date: 2020/10/12
  6215. * Time: 5:31 下午
  6216. * @param array $params
  6217. * @return ResultWrapper
  6218. * @throws \Exception
  6219. */
  6220. public function create(array $params)
  6221. {
  6222. $objMUserCoupon = new MUserCoupon($this->onlineUserId, $this->onlineEnterpriseId);
  6223. $objMCustomer = new MCustomer($this->onlineEnterpriseId, $this->onlineUserId);
  6224. $objMCustomerBalance = new MCustomerBalance($this->onlineEnterpriseId, $this->onlineUserId);
  6225. $objMCart = new MCart($this->onlineUserId, $this->onlineEnterpriseId);
  6226. $objMOrderGoods = new MOrderGoods($this->onlineUserId, $this->onlineEnterpriseId);
  6227. $objDStaff = new DStaff();
  6228. $objStockCache = new Stock($this->onlineEnterpriseId);
  6229. $objDStaff->setTable('qianniao_staff_' . $this->onlineEnterpriseId);
  6230. $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId);
  6231. $goodsCommonData = $params['goodsData'];
  6232. //锁定库存 查询商铺对应的仓库
  6233. $objMShop = new MShop($this->onlineEnterpriseId, $this->onlineUserId);
  6234. $modelResult = $objMShop->getShopDataByShopIds(array_column($goodsCommonData['goodsData'], 'shopId'));
  6235. if (!$modelResult->isSuccess()) {
  6236. return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
  6237. }
  6238. $shopData = $modelResult->getData();
  6239. if (empty($shopData)) {
  6240. return ResultWrapper::fail('获取店铺数据失败', ErrorCode::$paramError);
  6241. }
  6242. $paramsResult = self::getIdsCashierMap($params);
  6243. if (!$paramsResult->isSuccess()) {
  6244. return ResultWrapper::fail($paramsResult->getData(), $paramsResult->getErrorCode());
  6245. }
  6246. $params = $paramsResult->getData();
  6247. //获取客户信息
  6248. $customerOwe = 0;
  6249. if ($this->onlineUserId == StatusCode::$noneUserCenter) {
  6250. $customerData = [
  6251. 'id' => StatusCode::$noneCustomer,
  6252. 'name' => '匿名客户'
  6253. ];
  6254. } else {
  6255. $customerDataResult = $objMCustomer->getCustomerInfoByUserCenterId($this->onlineUserId);
  6256. if (!$customerDataResult->isSuccess()) {
  6257. return ResultWrapper::fail($customerDataResult->getData(), $customerDataResult->getErrorCode());
  6258. }
  6259. $customerData = $customerDataResult->getData();
  6260. //获取客户当前欠款
  6261. if (isset($customerData['id'])) {
  6262. $customerOwe = $objMCustomerBalance->getCustomerBalance($customerData['id']);
  6263. }
  6264. //获取客户手机号
  6265. $objDUserCenter = new DUserCenter();
  6266. $userInfo = $objDUserCenter->get(['id' => $this->onlineUserId], 'mobile');
  6267. if ($userInfo === false) {
  6268. return ResultWrapper::fail($objDUserCenter->error(), ErrorCode::$dberror);
  6269. }
  6270. $params['customerMobile'] = isset($userInfo['mobile']) ? $userInfo['mobile'] : '';
  6271. }
  6272. // 生成一个临时三方流水号,用来支持多个子订单作为一个订单支付,支付成功之后更新为对应的实际外部支付流水号
  6273. $tmpOuterTradeNo = 'tmp' . createOrderSn($params['source'], StatusCode::$orderType['cashierOrder'], $this->onlineUserId);
  6274. $lockInventoryData = [];//锁定库存物料
  6275. $goodsSaleData = [];//销售数据
  6276. $allSn = [];//所有单号
  6277. $allOrderIds = [];//所有订单
  6278. $mapDetails = [];//订单商品
  6279. $createTime = time();
  6280. $allCartIds = [];
  6281. $shopName = '';
  6282. $shopId = 0;//目前只有一个
  6283. $this->objDOrder->beginTransaction();
  6284. foreach ($goodsCommonData['goodsData'] as $key => $val) {
  6285. $sn = createOrderSn($params['source'], StatusCode::$orderType['saleOrder'], $this->onlineUserId);
  6286. //将数据写入索引表
  6287. $shopId = $val['shopId'];
  6288. $orderIndexData = [
  6289. 'shopId' => $val['shopId'],
  6290. 'userCenterId' => $params['userCenterId'],
  6291. 'salesManId' => isset($customerData['salesManId']) ? $customerData['salesManId'] : 0,
  6292. 'createTime' => time(),
  6293. 'updateTime' => time(),
  6294. 'deleteStatus' => StatusCode::$standard,
  6295. 'auditStatus' => StatusCode::$auditStatus['auditing'],
  6296. 'payStatus' => StatusCode::$delete,
  6297. 'orderStatus' => StatusCode::$orderStatus['waitPay'],
  6298. 'outStatus' => StatusCode::$delete,
  6299. 'returnStatus' => StatusCode::$orderReturn['notReturn'],
  6300. 'deliveryType' => $params['deliveryType'],
  6301. 'payType' => $params['payType'],
  6302. 'customerId' => isset($customerData['id']) ? $customerData['id'] : 0,
  6303. 'no' => $sn,
  6304. 'orderType' => StatusCode::$orderType['cashierOrder'],
  6305. 'selfRuleId' => 0,
  6306. 'cashierUid' => $this->loginUserCenterId,
  6307. 'guideUids' => isset($params['guideUids']) ? $params['guideUids'] : '',
  6308. ];
  6309. //1. 先写索引表
  6310. $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId);
  6311. $orderId = $this->objDOrderIndex->insert($orderIndexData);
  6312. if ($orderId === false) {
  6313. $this->objDOrder->rollBack();
  6314. return ResultWrapper::fail($$this->objDOrderIndex->error(), ErrorCode::$dberror);
  6315. }
  6316. //3。上门自提订单,生成核销码
  6317. $verifyCode = self::createVerifyCode($orderId);
  6318. //兼容以前代码
  6319. $updateRes = $this->objDOrderIndex->update(['verifyCode' => $verifyCode], ['id' => $orderId]);
  6320. if ($updateRes === false) {
  6321. $this->objDOrder->rollBack();
  6322. return ResultWrapper::fail($$this->objDOrderIndex->error(), ErrorCode::$dberror);
  6323. }
  6324. //订单数据
  6325. $shopName = $val['shopName'];//现在就一个店铺
  6326. $masterOrder = [
  6327. 'id' => $orderId,//订单id
  6328. 'customerId' => isset($customerData['id']) ? $customerData['id'] : 0,
  6329. 'userCenterId' => $params['userCenterId'],
  6330. 'shopId' => $val['shopId'],
  6331. 'shopName' => $val['shopName'],
  6332. 'no' => $sn,
  6333. 'outerTradeNo' => $tmpOuterTradeNo,
  6334. 'totalMoney' => $goodsCommonData['totalMoney'],
  6335. 'payAmount' => $goodsCommonData['payMoney'],
  6336. 'customerName' => isset($customerData['name']) ? $customerData['name'] : '',
  6337. 'remark' => $params['remark'],
  6338. 'deliveryType' => $params['deliveryType'],//配送方式
  6339. 'payType' => $params['payType'],//支付方式
  6340. 'salesManId' => isset($customerData['salesManId']) ? $customerData['salesManId'] : 0,
  6341. 'salesManName' => isset($customerData['salesManName']) ? $customerData['salesManName'] : '',
  6342. 'customerType' => isset($customerData['type']) ? $customerData['type'] : 0,
  6343. 'buyTotal' => array_sum(array_column($val['shopGoodsData'], 'buyNum')),
  6344. 'source' => $params['source'],//来源
  6345. 'orderStatus' => StatusCode::$orderStatus['waitPay'],
  6346. 'returnStatus' => StatusCode::$orderReturn['notReturn'],
  6347. 'outStatus' => StatusCode::$delete,
  6348. 'createTime' => time(),
  6349. 'updateTime' => time(),
  6350. 'customerOwe' => $customerOwe,//客户当前欠款
  6351. 'auditStatus' => StatusCode::$auditStatus['auditing'],
  6352. 'preferential' => $goodsCommonData['preferential'],//优惠券优惠金额
  6353. 'vipDiscount' => isset($goodsCommonData['vipDiscount']) ? $goodsCommonData['vipDiscount'] : 0,//会员卡优惠金额
  6354. 'vipDoubleDiscount' => isset($goodsCommonData['vipDoubleDiscount']) ? $goodsCommonData['vipDoubleDiscount'] : 0,//会员卡折上折优惠金额
  6355. 'originPayAmount' => $goodsCommonData['payMoney'],//原支付金额,
  6356. 'orderType' => StatusCode::$orderType['cashierOrder'],
  6357. 'verifyCode' => $verifyCode,
  6358. 'expressMoney' => isset($goodsCommonData['expressMoney']) ? $goodsCommonData['expressMoney'] : 0,
  6359. 'cashierUid' => $this->loginUserCenterId,
  6360. 'guideUids' => isset($params['guideUids']) ? $params['guideUids'] : '',
  6361. 'cashierName' => $params['cashierName'],
  6362. 'guideName' => $params['guideName'],
  6363. 'remMoney' => isset($goodsCommonData['rem_money']) ? $goodsCommonData['rem_money'] : 0,
  6364. 'changeSubMoney' => isset($goodsCommonData['subPrice']) ? $goodsCommonData['subPrice'] : 0,
  6365. 'isNoneUser' => $this->onlineUserId == StatusCode::$noneUserCenter ? StatusCode::$standard : StatusCode::$delete,
  6366. 'customerMobile' => $params['customerMobile'],
  6367. 'serialNum' => $objStockCache->createSerialSn(0,'Order'),
  6368. 'operatorName' => isset($params['operatorName']) ? $params['operatorName'] : '',
  6369. 'operatorId' => isset($params['operatorId']) ? $params['operatorId'] : 0,
  6370. ];
  6371. $allOrderIds[] = $orderId;
  6372. //2。订单表
  6373. $orderId = $this->objDOrder->insert($masterOrder);
  6374. if ($orderId === false) {
  6375. $this->objDOrder->rollBack();
  6376. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  6377. }
  6378. $masterOrder['goodsName'] = '';
  6379. foreach ($val['shopGoodsData'] as $k => &$v) {
  6380. $addOrderGoods = [
  6381. 'no' => $sn,
  6382. 'orderId' => $orderId,
  6383. 'goodsId' => $v['goodsId'],
  6384. 'goodsName' => $v['goodsName'],
  6385. 'shopId' => $val['shopId'],//商铺id
  6386. 'shopName' => $val['shopName'],//商铺名称
  6387. 'originPrice' => $v['originPrice'],
  6388. 'price' => $v['price'],
  6389. 'buyNum' => $v['buyNum'],
  6390. 'totalMoney' => $v['totalMoney'],
  6391. 'skuId' => $v['skuId'],
  6392. 'goodsBasicId' => $v['goodsBasicId'],
  6393. 'goodsCode' => $v['goodsCode'],
  6394. 'deliverNum' => $v['buyNum'],//发货数量=购买数量
  6395. 'unitName' => $v['unitName'],//单位名称
  6396. 'conversion' => $v['conversion'],//换算比率
  6397. 'preferential' => $v['preferential'],//优惠券优惠金额
  6398. 'vipDiscount' => $v['vipDiscount'],//会员卡优惠金额
  6399. 'categoryPath' => isset($v['categoryPath']) ? $v['categoryPath'] : '',//分类路径
  6400. 'brandId' => isset($v['brandId']) ? $v['brandId'] : 0,//品牌id
  6401. 'specGroup' => isset($v['specGroup']) && !empty($v['specGroup']) ? json_encode($v['specGroup']) : NULL,
  6402. 'goodsImages' => isset($v['goodsImages']) && is_string($v['goodsImages']) ? $v['goodsImages'] : '',
  6403. 'barCode' => isset($v['barCode']) ? $v['barCode'] : '',
  6404. 'storageCode' => isset($v['storageCode']) ? $v['storageCode'] : '',
  6405. 'categoryName' => isset($v['categoryName']) ? $v['categoryName'] : '',
  6406. 'brandName' => isset($v['brandName']) ? $v['brandName'] : '',
  6407. 'expressMoney' => isset($v['expressMoney']) ? $v['expressMoney'] : 0,
  6408. ];
  6409. $lockInventoryData[] = [
  6410. 'warehouseId' => $shopData[$v['shopId']]['warehouseId'],
  6411. 'materielId' => $v['goodsBasicId'],
  6412. 'materielCode' => $v['goodsCode'],
  6413. 'lockingNum' => $v['buyNum'],
  6414. 'originId' => $orderId,
  6415. 'originNo' => $sn,
  6416. 'source' => StatusCode::$orderType['saleOrder'],
  6417. 'sourceNo' => $sn,
  6418. 'operatorId' => $masterOrder['customerId'],
  6419. 'operatorName' => $masterOrder['customerName'],
  6420. 'skuId' => $v['skuId'],
  6421. ];
  6422. $goodsSaleData [] = [
  6423. 'goodsId' => $addOrderGoods['goodsId'],
  6424. 'skuId' => $addOrderGoods['skuId'],
  6425. 'buyNum' => $addOrderGoods['buyNum'],
  6426. ];
  6427. //活动商品数据
  6428. if ($this->isFront) {
  6429. if (isset($v['activityId']) && $v['activityId'] != 0) {
  6430. $activityData[] = [
  6431. 'goodsId' => $v['goodsId'],
  6432. 'skuId' => $v['skuId'],
  6433. 'activityId' => $v['activityId'],
  6434. 'buyNum' => $v['buyNum']
  6435. ];
  6436. }
  6437. }
  6438. $masterOrder['goodsName'] .= $v['goodsName'] . ' ';
  6439. $result = $objMOrderGoods->addOrderGoods($addOrderGoods);
  6440. if (!$result->isSuccess()) {
  6441. $this->objDOrder->rollBack();
  6442. return ResultWrapper::fail($result->getData(), ErrorCode::$dberror);
  6443. }
  6444. $allCartIds[] = $v['cartId'];
  6445. }
  6446. //存入ES
  6447. $masterOrder['verifyCode'] = isset($verifyCode) ? $verifyCode : '';
  6448. self::updateEsData($orderId, $masterOrder, [], $masterOrder['goodsName']);
  6449. $allSn[] = $sn;//所有订单号
  6450. }
  6451. //将优惠券改为已使用
  6452. if (isset($goodsCommonData['useCoupon']) && !empty($goodsCommonData['useCoupon'])) {
  6453. $result = $objMUserCoupon->updateIsUse(['id' => $goodsCommonData['useCoupon']['id']], ['isUse' => StatusCode::$delete, 'useTime' => time()]);
  6454. if (!$result->isSuccess()) {
  6455. $this->objDOrder->rollBack();
  6456. return ResultWrapper::fail($result->getData(), ErrorCode::$dberror);
  6457. }
  6458. }
  6459. //锁定库存商品数量
  6460. $objMInventory = new MInventory($this->onlineEnterpriseId, $this->onlineUserId);
  6461. $lockInventoryResult = $objMInventory->updateLockInventory($lockInventoryData);
  6462. if (!$lockInventoryResult->isSuccess()) {
  6463. $this->objDOrder->rollBack();
  6464. return ResultWrapper::fail($lockInventoryResult->getData(), $lockInventoryResult->getErrorCode());
  6465. }
  6466. //增加销量
  6467. $objMGoods = new MGoods($this->onlineEnterpriseId, false, $this->onlineUserId);
  6468. if (!empty($goodsSaleData)) {
  6469. foreach ($goodsSaleData as $value) {
  6470. $res = $objMGoods->updateSalesNum($value['goodsId'], $value['skuId'], $value['buyNum']);
  6471. if ($res === false) {
  6472. Logger::logs(E_USER_ERROR, '错误', __CLASS__, __LINE__, '商品增加销量失败');
  6473. }
  6474. }
  6475. }
  6476. //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);
  6477. $this->objSaleOrder->setGoodsDetails($mapDetails);
  6478. //统计订单信息
  6479. self::noticeStatistics([
  6480. 'userCenterId' => $params['userCenterId'],
  6481. 'enterpriseId' => $this->onlineEnterpriseId,
  6482. 'customerId' => $params['customerId'],
  6483. 'no' => $allSn,
  6484. 'noticeType' => 'create',
  6485. ], 'MOrderStatistics');
  6486. //写日志
  6487. foreach ($allSn as $sn) {
  6488. parent::saveLog([
  6489. 'no' => $sn,
  6490. 'actionType' => '创建订单',//创建订单
  6491. 'operationData' => '',
  6492. 'userCenterId' => $params['userCenterId'],
  6493. 'enterpriseId' => $this->onlineEnterpriseId,
  6494. 'createTime' => time(),
  6495. ]);
  6496. }
  6497. $this->objDOrder->commit();
  6498. return ResultWrapper::success(['orderId' => $orderId, 'shopName' => $shopName, 'out_trade_no' => $tmpOuterTradeNo, 'total_fee' => $goodsCommonData['payMoney']]);
  6499. }
  6500. /**
  6501. * Doc: (des="订单确认收款")
  6502. * User: XMing
  6503. * Date: 2020/10/12
  6504. * Time: 4:11 下午
  6505. * @param array $params
  6506. * @return ResultWrapper
  6507. * @throws \Exception
  6508. */
  6509. public function confirm(array $params)
  6510. {
  6511. $orderIndex = $this->objDOrderIndex->get(['id' => $params['orderId']]);
  6512. if ($orderIndex === false) {
  6513. return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
  6514. }
  6515. if (empty($orderIndex)) {
  6516. return ResultWrapper::fail('获取订单信息失败', ErrorCode::$paramError);
  6517. }
  6518. if ($orderIndex['payStatus'] != StatusCode::$delete) {
  6519. return ResultWrapper::fail('订单已付款', ErrorCode::$paramError);
  6520. }
  6521. $fix = $fix = ceil($orderIndex['userCenterId'] / $this->cutTable);;
  6522. $this->objDOrder->setTable('qianniao_order_' . $this->onlineEnterpriseId . '_' . $fix);
  6523. $orderData = $this->objDOrder->get(['id' => $params['orderId']]);
  6524. if ($orderData === false) {
  6525. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  6526. }
  6527. if (empty($orderData)) {
  6528. return ResultWrapper::fail('获取订单信息失败', ErrorCode::$paramError);
  6529. }
  6530. $paramsResult = self::getIdsCashierMap($params);
  6531. if (!$paramsResult->isSuccess()) {
  6532. return ResultWrapper::fail($paramsResult->getData(), $paramsResult->getErrorCode());
  6533. }
  6534. $params = $paramsResult->getData();
  6535. $this->objDOrderIndex->beginTransaction();
  6536. //修稿订单信息
  6537. $update = [
  6538. 'payType' => $params['payType'],
  6539. 'updateTime' => time(),
  6540. 'cashierUid' => $this->loginUserCenterId,
  6541. 'guideUids' => $params['guideUids'],
  6542. ];
  6543. $updateIndex = $this->objDOrderIndex->update($update, ['id' => $params['orderId']]);
  6544. if ($updateIndex === false) {
  6545. $this->objDOrderIndex->rollBack();
  6546. return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
  6547. }
  6548. $update['guideName'] = $params['guideName'];
  6549. $updateOrder = $this->objDOrder->update($update, ['id' => $params['orderId']]);
  6550. if ($updateOrder === false) {
  6551. $this->objDOrderIndex->rollBack();
  6552. return ResultWrapper::fail($this->objDOrder->error(), ErrorCode::$dberror);
  6553. }
  6554. /*
  6555. //更新es
  6556. $_id = self::createEsDocumentId($params['orderId']);
  6557. $this->objDOrder->esupdateTypeFieldVaule($update, $_id);*/
  6558. //清空此收银员的购物车
  6559. $objMCashierCart = new MCashierCart($this->onlineUserId, $this->onlineEnterpriseId, $this->loginUserCenterId);
  6560. $result = $objMCashierCart->clearCart();
  6561. if (!$result->isSuccess()) {
  6562. $this->objDOrderIndex->rollBack();
  6563. return ResultWrapper::fail($result->getData(), ErrorCode::$dberror);
  6564. }
  6565. //自动审核订单
  6566. $objMInventoryOut = new MInventoryOut($this->onlineEnterpriseId, $this->onlineUserId);
  6567. $auditResult = self::updateAuditStatus([
  6568. 'id' => $params['orderId'],
  6569. 'audit' => '自动审核',
  6570. 'auditId' => $this->onlineUserId,
  6571. 'auditStatus' => StatusCode::$auditStatus['auditPass']
  6572. ]);
  6573. if (!$auditResult->isSuccess()) {
  6574. $this->objDOrderIndex->rollBack();
  6575. return ResultWrapper::fail($auditResult->getData(), $auditResult->getErrorCode());
  6576. }
  6577. $outId = $auditResult->getData();//出库单id
  6578. //自动出库
  6579. $dbResult = $objMInventoryOut->updateInventoryOutStatus(['id' => $outId, 'auditId' => $this->loginUserCenterId, 'auditName' => '销售自动审核']);
  6580. if (!$dbResult->isSuccess()) {
  6581. $this->objDOrderIndex->rollBack();
  6582. return ResultWrapper::fail($dbResult->getData(), $dbResult->getErrorCode());
  6583. }
  6584. //确认收款
  6585. $dbResult = self::updateOrderPayData(['payStatus' => StatusCode::$standard, 'payTime' => time()], ['id' => [$params['orderId']]]);
  6586. if (!$dbResult->isSuccess()) {
  6587. $this->objDOrderIndex->rollBack();
  6588. return ResultWrapper::fail($dbResult->getData(), $dbResult->getErrorCode());
  6589. }
  6590. //确认收货
  6591. $dbResult = self::updateOrderStatus($params['orderId'], ['orderStatus' => StatusCode::$orderStatus['finish']], []);
  6592. if (!$dbResult->isSuccess()) {
  6593. $this->objDOrder->rollBack();
  6594. return ResultWrapper::fail($dbResult->getData(), $dbResult->getErrorCode());
  6595. }
  6596. $objMCashier = new MCashier($this->onlineUserId, $this->onlineEnterpriseId);
  6597. $cashierResult = $objMCashier->calculatePushMoney($params['orderId']);
  6598. if (!$cashierResult->isSuccess()) {
  6599. Logger::logs(E_USER_ERROR, '订单提成计算失败', __CLASS__, __LINE__, $cashierResult->getData());
  6600. }
  6601. //创建收款单
  6602. $received = [
  6603. 'currentAccountName' => $params['currentAccountName'],
  6604. 'financeType' => '销售收款',
  6605. 'financeTypeId' => 2,
  6606. 'shopId' => $orderData['shopId'],
  6607. 'shopName' => $orderData['shopName'],
  6608. 'receiptTime' => time(),
  6609. 'operatorId' => $this->loginUserCenterId,
  6610. 'accountList' => $params['accountList'],
  6611. 'customerId' => $orderData['customerId'],
  6612. 'customerName' => $orderData['customerName'],
  6613. 'sourceNo' => $orderData['no'],
  6614. 'sourceNoMoney' => $orderData['payAmount'],
  6615. 'createTime' => time(),
  6616. 'auditStatus' => StatusCode::$auditStatus['auditing'],
  6617. 'updateTime' => time(),
  6618. ];
  6619. $objMReceived = new MReceived($this->onlineEnterpriseId, $this->loginUserCenterId);
  6620. $receivedResult = $objMReceived->addReceived($received, true);
  6621. if (!$receivedResult->isSuccess()) {
  6622. $this->objDOrderIndex->rollBack();
  6623. return ResultWrapper::fail($receivedResult->getData(), $receivedResult->getErrorCode());
  6624. }
  6625. $this->objDOrderIndex->commit();
  6626. if ($this->onlineUserId == StatusCode::$noneUserCenter) {
  6627. $objDCashierCustomerPrice = new DCashierCustomerPrice();
  6628. $objDCashierCustomerPrice->setTable('qianniao_cashier_customer_price_' . $this->onlineEnterpriseId);
  6629. $objDCashierCustomerPrice->delete(['cashierUid' => $this->loginUserCenterId, 'customerUid' => StatusCode::$noneUserCenter]);
  6630. }
  6631. return ResultWrapper::success(true);
  6632. }
  6633. /**
  6634. * Doc: (des="获取收银员工信息")
  6635. * User: XMing
  6636. * Date: 2020/10/12
  6637. * Time: 5:50 下午
  6638. * @param array $params
  6639. * @return ResultWrapper
  6640. * @throws \Exception
  6641. */
  6642. private function getIdsCashierMap(array $params)
  6643. {
  6644. $objDStaff = new DStaff();
  6645. $objDStaff->setTable('qianniao_staff_' . $this->onlineEnterpriseId);
  6646. //获取收银员信息
  6647. $allUids = [$this->loginUserCenterId];
  6648. if (isset($params['guideUids']) && !empty($params['guideUids'])) {
  6649. $ids = explode(',', $params['guideUids']);
  6650. $allUids = array_merge($allUids, $ids);
  6651. }
  6652. $userMap = [];
  6653. if (!empty($allUids)) {
  6654. $staffList = $objDStaff->select(['userCenterId' => $allUids], 'userCenterId,staffName');
  6655. if ($staffList === false) {
  6656. return ResultWrapper::fail($objDStaff->error(), ErrorCode::$dberror);
  6657. }
  6658. foreach ($staffList as $value) {
  6659. $userMap[$value['userCenterId']] = $value['staffName'];
  6660. }
  6661. }
  6662. $params['cashierName'] = isset($userMap[$this->loginUserCenterId]) ? $userMap[$this->loginUserCenterId] : '超级管理员';
  6663. $nameStr = '';
  6664. if (!empty($ids)) {
  6665. foreach ($ids as $uid) {
  6666. if (!empty($nameStr)) {
  6667. $nameStr .= ',';
  6668. }
  6669. $nameStr .= isset($userMap[$uid]) ? $userMap[$uid] : '';
  6670. }
  6671. }
  6672. $params['guideName'] = $nameStr;
  6673. $params['customerMobile'] = '';
  6674. return ResultWrapper::success($params);
  6675. }
  6676. public function fix_ex()
  6677. {
  6678. $_id = self::createEsDocumentId(144);
  6679. $this->objDOrder->esupdateTypeFieldVaule(['salesManId' => 1, 'salesManName' => '杨明霞', 'updateTime' => time()], $_id);
  6680. }
  6681. /**
  6682. * 查询索引表信息
  6683. */
  6684. public function getOrderIndexData($where)
  6685. {
  6686. $dbResult = $this->objDOrderIndex->get($where);
  6687. if ($dbResult === false) {
  6688. return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
  6689. }
  6690. return ResultWrapper::success($dbResult);
  6691. }
  6692. /**
  6693. * Doc: (des="根据订单id获取订单信息")
  6694. * User: XMing
  6695. * Date: 2020/12/7
  6696. * Time: 4:05 下午
  6697. * @param int $id
  6698. * @return ResultWrapper
  6699. * @throws \Exception
  6700. */
  6701. public function getOrderByOrderId(int $id): ResultWrapper
  6702. {
  6703. $orderIndex = $this->objDOrderIndex->get($id);
  6704. if ($orderIndex === false){
  6705. return ResultWrapper::fail($this->objDOrderIndex->error,ErrorCode::$dberror);
  6706. }
  6707. if (empty($orderIndex)){
  6708. return ResultWrapper::fail('未获取到订单信息',ErrorCode::$paramError);
  6709. }
  6710. $fix = ceil($orderIndex['userCenterId'] / $this->cutTable);
  6711. $this->objDOrder->setTable('qianniao_order_'.$this->onlineEnterpriseId.'_'.$fix);
  6712. $order = $this->objDOrder->get($id);
  6713. if ($order === false){
  6714. return ResultWrapper::fail($this->objDOrder->error,ErrorCode::$paramError);
  6715. }
  6716. if (empty($order)){
  6717. return ResultWrapper::fail('未获取到订单信息',ErrorCode::$paramError);
  6718. }
  6719. return ResultWrapper::success($order);
  6720. }
  6721. /**
  6722. * Doc: (des="")
  6723. * User: XMing
  6724. * Date: 2020/12/8
  6725. * Time: 10:43 上午
  6726. * @param int $id
  6727. * @return ResultWrapper
  6728. * @throws \Exception
  6729. */
  6730. public function updateSettel(int $id): ResultWrapper
  6731. {
  6732. $orderIndex = $this->objDOrderIndex->get($id);
  6733. if ($orderIndex === false){
  6734. return ResultWrapper::fail($this->objDOrderIndex->error,ErrorCode::$dberror);
  6735. }
  6736. if (empty($orderIndex)){
  6737. return ResultWrapper::fail('未获取到订单信息',ErrorCode::$paramError);
  6738. }
  6739. $fix = ceil($orderIndex['userCenterId'] / $this->cutTable);
  6740. $this->objDOrder->setTable('qianniao_order_'.$this->onlineEnterpriseId.'_'.$fix);
  6741. $order = $this->objDOrder->update(['isSettel' => StatusCode::$standard],$id);
  6742. if ($order === false){
  6743. return ResultWrapper::fail($this->objDOrder->error,ErrorCode::$paramError);
  6744. }
  6745. return ResultWrapper::success(true);
  6746. }
  6747. /**
  6748. * Doc: (des="")
  6749. * User: XMing
  6750. * Date: 2021/2/4
  6751. * Time: 12:06 下午
  6752. * @param array $selectParams
  6753. * @return ResultWrapper
  6754. */
  6755. public function getStatistics(array $selectParams):ResultWrapper
  6756. {
  6757. //默认今日的
  6758. $todayStart = strtotime(date('Y-m-d 00:00:00', time()));
  6759. $todayEnd = strtotime(date('Y-m-d 23:59:59', time()));
  6760. if (isset($selectParams['start']) && !empty($selectParams['start'])){
  6761. $todayStart = $selectParams['start'];
  6762. }
  6763. if (isset($selectParams['end']) && !empty($selectParams['end'])){
  6764. $todayEnd = $selectParams['end'];
  6765. }
  6766. $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
  6767. (
  6768. 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
  6769. LEFT JOIN qianniao_order_goods_'.$this->onlineEnterpriseId.'_1 as g ON g.orderId = o.id
  6770. WHERE o.outStatus in(5,6) AND g.deleteStatus = 5 AND o.createTime BETWEEN '.$todayStart.' AND '.$todayEnd.'
  6771. UNION ALL
  6772. 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
  6773. LEFT JOIN qianniao_order_return_details_'.$this->onlineEnterpriseId.' as d ON d.linkId=r.id
  6774. WHERE r.auditStatus = 2 AND d.deleteStatus = 5 AND r.updateTime BETWEEN '.$todayStart.' AND '. $todayEnd.'
  6775. )
  6776. AS order_view GROUP BY skuId';
  6777. $countSql = 'SELECT order_view.id as id FROM
  6778. (
  6779. SELECT o.id,g.skuId FROM qianniao_order_'.$this->onlineEnterpriseId.'_1 as o
  6780. LEFT JOIN qianniao_order_goods_'.$this->onlineEnterpriseId.'_1 as g ON g.orderId = o.id
  6781. WHERE o.outStatus in(5,6) AND g.deleteStatus = 5 AND o.createTime BETWEEN '.$todayStart.' AND '.$todayEnd.'
  6782. UNION ALL
  6783. SELECT r.id,d.skuId FROM qianniao_order_return_'.$this->onlineEnterpriseId.' as r
  6784. LEFT JOIN qianniao_order_return_details_'.$this->onlineEnterpriseId.' as d ON d.linkId=r.id
  6785. WHERE r.auditStatus = 2 AND d.deleteStatus = 5 AND r.updateTime BETWEEN '.$todayStart.' AND '. $todayEnd.'
  6786. ) AS order_view GROUP BY skuId';
  6787. $sql .= ' LIMIT '.$selectParams['offset'].','.$selectParams['limit'];
  6788. $lists = $this->objDOrderIndex->query($sql);
  6789. if ($lists === false){
  6790. return ResultWrapper::fail($this->objDOrderIndex->error(),ErrorCode::$dberror);
  6791. }
  6792. $goodsBasicDate = [];
  6793. //获取商品资料
  6794. $goodsBasicIds = array_column($lists,'goodsBasicId');
  6795. $objGoodsDate = new MGoodsBasic($this->onlineUserId,$this->onlineEnterpriseId);
  6796. $result = $objGoodsDate->getBasicGoodsFieldByIds($goodsBasicIds);
  6797. if ( !$result->isSuccess() ){
  6798. return ResultWrapper::fail($result->getData(),$result->getErrorCode());
  6799. }
  6800. $goodsBasicDate = $result->getData();
  6801. $skuIds = [];
  6802. foreach ($lists as &$list){
  6803. $list['isEq'] = isset($goodsBasicDate[$list['goodsBasicId']]['isEq']) ? $goodsBasicDate[$list['goodsBasicId']]['isEq'] : 4;
  6804. $list['specGroup'] = json_decode($list['specGroup'],true);
  6805. if (is_array($list['specGroup'])){
  6806. $arr = array_column($list['specGroup'],'specValueName');
  6807. $str = implode('_',$arr);
  6808. $list['specGroup'] = $str;
  6809. }
  6810. $list['subProMoney'] = floatval(bcsub($list['totalMoney'],$list['outCostPrice'],2));//毛利
  6811. $skuIds[] = $list['skuId'];
  6812. }
  6813. unset($list);
  6814. $thisRetMap = [];//本期
  6815. $lastRetMap = [];//上期
  6816. if (!empty($skuIds)){
  6817. $str = implode(',',$skuIds);
  6818. //本期退货数量
  6819. $fields = ' SUM(d.num) as thisRetNum,d.skuId as skuId,SUM(d.returnTotalPrice) as thisReturnTotalPrice ';
  6820. $sql = 'SELECT '.$fields.' FROM qianniao_order_' . $this->onlineEnterpriseId . '_1 AS o
  6821. LEFT JOIN qianniao_order_return_'.$this->onlineEnterpriseId.' AS r
  6822. ON r.originId = o.id LEFT JOIN qianniao_order_return_details_'.$this->onlineEnterpriseId.' AS d
  6823. ON d.linkId = r.id
  6824. WHERE r.auditStatus = 2 AND d.deleteStatus = 5 AND
  6825. o.createTime BETWEEN '.$todayStart.' AND '. $todayEnd.' AND
  6826. r.updateTime BETWEEN '.$todayStart.' AND '. $todayEnd.' AND
  6827. d.skuId IN('.$str.') GROUP BY d.skuId';
  6828. $retLists = $this->objDOrderIndex->query($sql);
  6829. if ($retLists === false){
  6830. return ResultWrapper::fail($this->objDOrderIndex->error(),ErrorCode::$dberror);
  6831. }
  6832. unset($sql);
  6833. //上期退货
  6834. $fields = ' SUM(d.num) as lastRetNum,d.skuId as skuId,SUM(d.returnTotalPrice) as lastReturnTotalPrice ';
  6835. $sql = 'SELECT '.$fields.' FROM qianniao_order_' . $this->onlineEnterpriseId . '_1 AS o
  6836. LEFT JOIN qianniao_order_return_'.$this->onlineEnterpriseId.' AS r
  6837. ON r.originId = o.id LEFT JOIN qianniao_order_return_details_'.$this->onlineEnterpriseId.' AS d
  6838. ON d.linkId = r.id
  6839. WHERE r.auditStatus = 2 AND d.deleteStatus = 5 AND
  6840. o.createTime < '.$todayStart.' AND
  6841. r.updateTime BETWEEN '.$todayStart.' AND '. $todayEnd.' AND
  6842. d.skuId IN('.$str.') GROUP BY d.skuId';
  6843. $lastRetLists = $this->objDOrderIndex->query($sql);
  6844. if ($lastRetLists === false){
  6845. return ResultWrapper::fail($this->objDOrderIndex->error(),ErrorCode::$dberror);
  6846. }
  6847. unset($sql);
  6848. foreach ($retLists as $val){
  6849. $thisRetMap[$val['skuId']] = [
  6850. 'thisRetNum' => $val['thisRetNum'],
  6851. 'thisReturnTotalPrice' => $val['thisReturnTotalPrice'],
  6852. ];
  6853. }
  6854. foreach ($lastRetLists as $val){
  6855. $lastRetMap[$val['skuId']] = [
  6856. 'lastRetNum' => $val['lastRetNum'],
  6857. 'lastReturnTotalPrice' => $val['lastReturnTotalPrice']
  6858. ];
  6859. }
  6860. }
  6861. foreach ($lists as &$item){
  6862. if (!isset($thisRetMap[$item['skuId']])){
  6863. $item['thisRetNum'] = 0;
  6864. $item['thisReturnTotalPrice'] = 0;
  6865. }else{
  6866. $item['thisRetNum'] = floatval($thisRetMap[$item['skuId']]['thisRetNum']);
  6867. $item['thisReturnTotalPrice'] = floatval($thisRetMap[$item['skuId']]['thisReturnTotalPrice']);
  6868. }
  6869. if (!isset($lastRetMap[$item['skuId']])){
  6870. $item['lastRetNum'] = 0;
  6871. $item['lastReturnTotalPrice'] = 0;
  6872. }else{
  6873. $item['lastRetNum'] = floatval($lastRetMap[$item['skuId']]['lastRetNum']);
  6874. $item['lastReturnTotalPrice'] = floatval($lastRetMap[$item['skuId']]['lastReturnTotalPrice']);
  6875. }
  6876. $item['retNum'] = bcadd($item['thisRetNum'],$item['lastRetNum'],2);
  6877. $item['returnTotalPrice'] = bcadd($item['thisReturnTotalPrice'],$item['lastReturnTotalPrice'],2);
  6878. }
  6879. unset($item);
  6880. $count = $this->objDOrderIndex->query($countSql);
  6881. if ($count === false){
  6882. return ResultWrapper::fail($this->objDOrderIndex->error(),ErrorCode::$dberror);
  6883. }
  6884. $data = [
  6885. 'total' => count($count),
  6886. 'data' => $lists
  6887. ];
  6888. return ResultWrapper::success($data);
  6889. }
  6890. /**
  6891. * Doc: (des="")
  6892. * User: XMing
  6893. * Date: 2021/3/10
  6894. * Time: 11:05 上午
  6895. * @param array $params
  6896. * @return ResultWrapper
  6897. * @throws \Exception
  6898. */
  6899. public function getGoodsListsByUserCenterId(array $params): ResultWrapper
  6900. {
  6901. $fix = 1;
  6902. if (isset($params['userCenterId']) && !empty($params['userCenterId'])){
  6903. $fix = ceil($params['userCenterId'] / $this->cutTable);
  6904. }
  6905. $this->objDOrder->setTable('qianniao_order_'.$this->onlineEnterpriseId.'_'.$fix);
  6906. $fields = ' id,customerName,customerId ';
  6907. $where = '';
  6908. if (isset($params['startTime']) && !empty($params['startTime']) && isset($params['endTime']) && !empty($params['endTime'])){
  6909. $where .= ' AND `createTime` BETWEEN '.$params['startTime'].' AND '.$params['endTime'];
  6910. }
  6911. $sql = 'SELECT '.$fields.' FROM qianniao_order_'.$this->onlineEnterpriseId.'_'.$fix.' WHERE deleteStatus = '.StatusCode::$standard.$where;
  6912. if (isset($params['userCenterId']) && !empty($params['userCenterId'])){
  6913. $sql .= ' AND userCenterId = '.$params['userCenterId'];
  6914. }
  6915. $sql .= ' order by createTime desc';
  6916. $lists = $this->objDOrder->query($sql);
  6917. if ($lists === false){
  6918. return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror);
  6919. }
  6920. if (empty($lists)){
  6921. return ResultWrapper::success(['data' => [],'total' => 0]);
  6922. }
  6923. unset($sql);
  6924. unset($where);
  6925. unset($fields);
  6926. $orderIds = [];
  6927. $orderRelMap = [];
  6928. foreach ($lists as $item){
  6929. $orderIds[] = $item['id'];
  6930. $orderRelMap[$item['id']] = $item;
  6931. }
  6932. $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 ';
  6933. $where = '';
  6934. if (!empty($orderIds)){
  6935. $str = trim(implode(',',$orderIds),',');
  6936. $where .= ' AND `orderId` IN ('.$str.')';
  6937. }
  6938. if (isset($params['categoryId']) && !empty($params['categoryId'])){
  6939. $categoryId = (int)$params['categoryId'];
  6940. $where .= ' AND FIND_IN_SET('.$categoryId.',`categoryPath`) ';
  6941. }
  6942. if (isset($params['brandId']) && !empty($params['brandId'])){
  6943. $brandId = (int)$params['brandId'];
  6944. $where .= ' AND `brandId` = '.$brandId;
  6945. }
  6946. if (isset($params['barCode']) && !empty($params['barCode'])){
  6947. $barCode = (string)$params['barCode'];
  6948. $where .= ' AND `barCode` = "'.$barCode.'"';
  6949. }
  6950. if (isset($params['shopId']) && !empty($params['shopId'])){
  6951. $shopId = (int)$params['shopId'];
  6952. $where .= ' AND `shopId` = '.$shopId;
  6953. }
  6954. if (isset($params['keyword']) && !empty($params['keyword'])){
  6955. $keyword = '"%'.$params['keyword'].'%"';
  6956. $where .= ' AND (`goodsName` LIKE '.$keyword.' OR `goodsCode` LIKE '.$keyword.') ';
  6957. }
  6958. $sql = 'SELECT '.$fields.' FROM qianniao_order_goods_'.$this->onlineEnterpriseId.'_'.$fix.'
  6959. WHERE `deleteStatus` = '.StatusCode::$standard.$where.'
  6960. GROUP BY skuId ORDER BY createTime DESC ';
  6961. $count = $this->objDOrderGoods->query($sql);
  6962. if ($count === false){
  6963. return ResultWrapper::fail($this->objDOrderGoods->error(),ErrorCode::$dberror);
  6964. }
  6965. if (isset($params['limit']) && !empty($params['limit'])){
  6966. $sql .= ' LIMIT '.$params['offset'].','.$params['limit'];
  6967. }
  6968. $lists = $this->objDOrderGoods->query($sql);
  6969. if ($lists === false){
  6970. return ResultWrapper::fail($this->objDOrderGoods->error(),ErrorCode::$dberror);
  6971. }
  6972. if (empty($lists)){
  6973. return ResultWrapper::success(['data'=>[],'total'=>0]);
  6974. }
  6975. if ($lists === false){
  6976. return ResultWrapper::fail($this->objDOrderGoods->error(),ErrorCode::$dberror);
  6977. }
  6978. $goodsBasicDate = [];
  6979. //获取商品资料
  6980. $goodsBasicIds = array_column($lists,'goodsBasicId');
  6981. $objGoodsDate = new MGoodsBasic($this->onlineUserId,$this->onlineEnterpriseId);
  6982. $result = $objGoodsDate->getBasicGoodsFieldByIds($goodsBasicIds);
  6983. if ( !$result->isSuccess() ){
  6984. return ResultWrapper::fail($result->getData(),$result->getErrorCode());
  6985. }
  6986. $goodsBasicDate = $result->getData();
  6987. foreach ($lists as &$item){
  6988. if (isset($item['specGroup']) && !empty($item['specGroup'])){
  6989. $item['specGroup'] = json_decode($item['specGroup'],true);
  6990. }
  6991. $item['customerName'] = isset($orderRelMap[$item['orderId']]) ? $orderRelMap[$item['orderId']]['customerName'] : '';
  6992. $item['customerId'] = isset($orderRelMap[$item['orderId']]) ? $orderRelMap[$item['orderId']]['customerId'] : 0;
  6993. $item['isEq'] = isset($goodsBasicDate[$item['goodsBasicId']]['isEq']) ? $goodsBasicDate[$item['goodsBasicId']]['isEq'] : 4;
  6994. }
  6995. return ResultWrapper::success([
  6996. 'data' => $lists,
  6997. 'total' => (int)count($count)
  6998. ]);
  6999. }
  7000. /**
  7001. * Doc: (des="缺货单列表")
  7002. * User: XMing
  7003. * Date: 2021/3/11
  7004. * Time: 6:44 下午
  7005. * @param array $selectParams
  7006. * @return ResultWrapper
  7007. * @throws \Exception
  7008. */
  7009. public function getDistributionAll(array $selectParams): ResultWrapper
  7010. {
  7011. //{"page":1,"pageSize":10,"search":{},"state":"all"}
  7012. $selectParams['state'] = 'state';
  7013. $selectParams['outStatus'] = 6;
  7014. $orderListsResult = self::getAllOrder($selectParams,[]);
  7015. if (!$orderListsResult->isSuccess()){
  7016. return ResultWrapper::fail($orderListsResult->getData(),$orderListsResult->getErrorCode());
  7017. }
  7018. $total = $orderListsResult->getData()['total'];
  7019. $orderLists = $orderListsResult->getData()['data'];
  7020. if (empty($orderLists)){
  7021. return ResultWrapper::success(['data' => [],'total' => 0]);
  7022. }
  7023. $arrayLists = [];
  7024. $orderIds = [];
  7025. foreach ($orderLists as $item){
  7026. $infoResult = self::getOrderInfoById($item['id']);
  7027. if (!$infoResult->isSuccess()){
  7028. return ResultWrapper::fail($infoResult->getData(),$infoResult->getErrorCode());
  7029. }
  7030. $infoResult = $infoResult->getData();
  7031. $goodsData = $infoResult['goodsData'];
  7032. foreach ($goodsData as $key => $item){
  7033. if ($item['outOfNum'] == 0){
  7034. unset($goodsData[$key]);
  7035. continue;
  7036. }
  7037. $infoResult['goodsData'] = array_values($goodsData);
  7038. }
  7039. $arrayLists[] = $infoResult;
  7040. }
  7041. return ResultWrapper::success(['data' => $arrayLists,'total' => $total]);
  7042. }
  7043. /**
  7044. * Doc: (des="业务员销售排行")
  7045. * User: XMing
  7046. * Date: 2021/3/15
  7047. * Time: 10:09 上午
  7048. * @param array $params
  7049. * @param $export
  7050. * @return ResultWrapper
  7051. */
  7052. public function salesManRank(array $params,$export = 0): ResultWrapper
  7053. {
  7054. $sortFields = ['dealCustomerNum','orderNum','dealAmount','skuNum','buyNum'];
  7055. $sort = ['ASC','DESC'];
  7056. if (!in_array($params['sortField'],$sortFields)){
  7057. return ResultWrapper::fail('sortField字段异常',ErrorCode::$paramError);
  7058. }
  7059. if (!in_array($params['sort'],$sort)){
  7060. return ResultWrapper::fail('sort字段异常',ErrorCode::$paramError);
  7061. }
  7062. $where = '';
  7063. $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 ';
  7064. if (isset($params['startTime']) && !empty($params['startTime']) && isset($params['endTime']) && !empty($params['endTime'])){
  7065. $where .= ' AND o.createTime BETWEEN '.$params['startTime'].' AND '.$params['endTime'];
  7066. }
  7067. if ( !empty($params['orderStatus'])&& isset($params['orderStatus']) ){//删选
  7068. $orderStatus = implode(',',$params['orderStatus']);
  7069. $where .= ' AND o.orderStatus IN ('.$orderStatus.')';
  7070. }
  7071. $sql = 'SELECT '.$fields.' FROM qianniao_order_'.$this->onlineEnterpriseId.'_1 as o
  7072. LEFT JOIN qianniao_order_goods_'.$this->onlineEnterpriseId.'_1 as g ON g.orderId = o.id
  7073. WHERE o.deleteStatus = 5
  7074. AND o.salesManId IS NOT NULL
  7075. AND o.salesManId != 0 '.$where;
  7076. $sql .= ' GROUP BY o.salesManName ';
  7077. if (isset($params['sortField']) && !empty($params['sortField']) && isset($params['sort']) && !empty($params['sort'])){
  7078. $sql .= ' ORDER BY '.$params['sortField'].' '.$params['sort'];
  7079. }
  7080. $count = $this->objDOrder->query($sql);
  7081. if ($count === false){
  7082. return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror);
  7083. }
  7084. if (count((array)$count) == 0){
  7085. return ResultWrapper::success(['data' => [],'total' => 0]);
  7086. }
  7087. if($export){
  7088. $params['limit'] = null;
  7089. $params['offset'] = null;
  7090. }
  7091. if (isset($params['limit']) && !empty($params['limit'])){
  7092. $sql .= ' LIMIT '.$params['offset'].','.$params['limit'];
  7093. }
  7094. //导出
  7095. if($export){
  7096. $lists = $this->objDOrder->query($sql);
  7097. if ($lists === false){
  7098. return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror);
  7099. }
  7100. self::exportsalesManRank($lists);
  7101. exit;
  7102. }else{
  7103. $lists = $this->objDOrder->query($sql);
  7104. if ($lists === false){
  7105. return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror);
  7106. }
  7107. foreach ($lists as &$list){
  7108. $list['dealAmount'] = sprintf('%.2f', $list['dealAmount']);
  7109. }
  7110. }
  7111. return ResultWrapper::success(['data' => $lists,'total' => count($count)]);
  7112. }
  7113. /**
  7114. * Doc: (des="")
  7115. * User: XMing
  7116. * Date: 2021/3/17
  7117. * Time: 10:47 上午
  7118. * @param array $orderIds
  7119. * @param array $params
  7120. * @return ResultWrapper
  7121. * @throws \Exception
  7122. */
  7123. public function updateCostPriceBySku(array $orderIds,array $params): ResultWrapper
  7124. {
  7125. Logger::logs(E_USER_ERROR,'params',__CLASS__,__LINE__,$params);
  7126. Logger::logs(E_USER_ERROR,'orderIds',__CLASS__,__LINE__,$orderIds);
  7127. if (empty($orderIds)){
  7128. return ResultWrapper::success();
  7129. }
  7130. $lists = $this->objDOrderIndex->select($orderIds,'id,userCenterId');
  7131. if ($lists === false){
  7132. return ResultWrapper::fail($this->objDOrderIndex->error(),ErrorCode::$dberror);
  7133. }
  7134. $tables = [];
  7135. foreach ($lists as $list){
  7136. $fix = ceil($list['userCenterId'] / $this->cutTable);
  7137. $tables[$fix][] = $list['id'];
  7138. }
  7139. if (empty($tables)){
  7140. return ResultWrapper::success('没有更新的表');
  7141. }
  7142. $status = $this->objDOrderGoods->beginTransaction();
  7143. foreach ($params as $value){
  7144. $where = $value['where'];
  7145. $update = $value['update'];
  7146. foreach ($tables as $fix => $orderIds){
  7147. $this->objDOrderGoods->setTable('qianniao_order_goods_'.$this->onlineEnterpriseId.'_'.$fix);
  7148. Logger::logs(E_USER_ERROR,'update',__CLASS__,__LINE__,$update);
  7149. Logger::logs(E_USER_ERROR,'where',__CLASS__,__LINE__,$where);
  7150. $updateResult = $this->objDOrderGoods->update($update,$where);
  7151. if ($updateResult === false){
  7152. $this->objDOrderGoods->rollBack();
  7153. return ResultWrapper::fail($this->objDOrderGoods->error(),ErrorCode::$dberror);
  7154. }
  7155. }
  7156. }
  7157. $status && $this->objDOrderGoods->commit();
  7158. return ResultWrapper::success(true);
  7159. }
  7160. /*
  7161. * 设置物流信息
  7162. * */
  7163. public function addLogistics($params)
  7164. {
  7165. $logisticsData = $params['logisticsData'];
  7166. if(empty($logisticsData['id'])){
  7167. $objMDriver = new MDriver($this->onlineEnterpriseId, $this->onlineUserId);
  7168. $paramsDriver = [
  7169. 'enterpriseId'=> $this->onlineEnterpriseId,
  7170. 'driverName' => $logisticsData['name'],
  7171. 'phone' => $logisticsData['truckTel'],
  7172. 'plateNumber' => $logisticsData['truckName'],
  7173. 'remark' => $logisticsData['remark']
  7174. ];
  7175. $addDriver = $objMDriver->addDriver($paramsDriver);
  7176. if ( !$addDriver->isSuccess() ){
  7177. return ResultWrapper::fail($addDriver->getData(),$addDriver->getErrorCode());
  7178. }
  7179. $driverId = $addDriver->getData();
  7180. $params['logisticsData']['id']= $driverId;
  7181. }
  7182. //去掉订单id剩下的数据就是物流数据
  7183. $orderId = $params['orderId'];
  7184. unset($params['orderId']);
  7185. $orderNo = $params['no'];
  7186. unset($params['no']);
  7187. $updateLogistics = self::editOrderExpress($orderNo,$params,$orderId);
  7188. if (!$updateLogistics->isSuccess()){
  7189. $this->objDOrder->rollBack();
  7190. return ResultWrapper::fail($updateLogistics->getData(),$updateLogistics->getErrorCode());
  7191. }
  7192. return ResultWrapper::success($updateLogistics);
  7193. }
  7194. /**
  7195. * 业务员订单表导出方法
  7196. * @param $result
  7197. * @return void
  7198. * @throws Exception
  7199. */
  7200. public function exportsalesManRank($result)
  7201. {
  7202. //导出到本地
  7203. header("Content-type:application/vnd.ms-excel");
  7204. header("Content-Disposition:filename=业务员订单记录表.csv");
  7205. header('Cache-Control: max-age=0');
  7206. $fp = fopen('php://output', 'a');
  7207. $head = ['销售员','成交客户','sku数量','订单数','销售数量','成交金额']; //定义标题
  7208. foreach ($head as $i => $v) {
  7209. $head[$i] = mb_convert_encoding($v, 'GBK', 'utf-8'); //将中文标题转换编码,否则乱码
  7210. }
  7211. fputcsv($fp, $head);
  7212. $limit = 10000;
  7213. $num = 0; //计数器
  7214. foreach ($result as $v) { //循环数据
  7215. $num++;
  7216. if ($num == $limit) {
  7217. ob_flush(); //释放内存
  7218. flush();
  7219. }
  7220. $rows['salesManName'] = isset($v['salesManName']) ? $v['salesManName'] : '';//销售员
  7221. $rows['dealCustomerNum'] = isset($v['dealCustomerNum']) ? $v['dealCustomerNum'] : '';//成交客户
  7222. $rows['skuNum'] = isset($v['skuNum']) ? $v['skuNum'] : '';//SKU数量
  7223. $rows['orderNum'] = isset($v['orderNum']) ? $v['orderNum'] : '';//订单数
  7224. $rows['buyNum'] = isset($v['buyNum']) ? $v['buyNum'] : '';//销售数量
  7225. $rows['dealAmount'] = isset($v['dealAmount']) ? $v['dealAmount'] : '';//成交金额
  7226. foreach ($rows as $kk => $vv) {
  7227. $rs[$kk] = mb_convert_encoding($vv, 'GBK', 'utf-8'); //转译编码
  7228. }
  7229. fputcsv($fp, $rs);
  7230. $rows = [];
  7231. }
  7232. }
  7233. /**
  7234. * 导出方法
  7235. *
  7236. * @param $orderProfit
  7237. */
  7238. private static function exportOrderProfit($orderProfit)
  7239. {
  7240. //导出到本地
  7241. header("Content-type:application/vnd.ms-excel");
  7242. header("Content-Disposition:filename=销售毛利明细表记录.csv");
  7243. header('Cache-Control: max-age=0');
  7244. $fp = fopen('php://output', 'a');
  7245. $head = ['商品名','单据类型', '单据日期', '客户名', '数量','其他单位','销售价', '成本价', '销售收入','销售成本', '销售毛利', '销售毛利率']; //定义标题
  7246. foreach ($head as $i => $v) {
  7247. $head[$i] = mb_convert_encoding($v, 'GBK', 'utf-8'); //将中文标题转换编码,否则乱码
  7248. }
  7249. fputcsv($fp, $head);
  7250. $limit = 10000;
  7251. $num = 0;//计数器
  7252. foreach ($orderProfit as $v) {
  7253. //循环数据
  7254. $num++;
  7255. if ($num == $limit) {
  7256. ob_flush();//释放内存
  7257. flush();
  7258. }
  7259. $rows['goodsName'] = isset($v['goodsName']) ? $v['goodsName'] : '';//商品名
  7260. $rows['orderType'] = $v['orderType'] === 1 ? '销售订单' : '销售单';//单据类型
  7261. $rows['createTime'] = isset($v['createTime']) ? date('Y-m-d H:i:s',$v['createTime']) : '';//单据日期
  7262. $rows['customerName'] = isset($v['customerName']) ? $v['customerName'] : '';//客户名
  7263. $rows['buyNum'] = isset($v['buyNum']) ? $v['buyNum'] : '';//数量
  7264. $rows['otherNum'] = isset($v['otherNum']) ? $v['otherNum'] : 0;//其他单位
  7265. $rows['price'] = isset($v['price']) ? $v['price'] : '';//销售价
  7266. $rows['outCostPrice'] = isset($v['outCostPrice']) ? $v['outCostPrice'] : '';//成本价
  7267. $rows['totalMoney'] = isset($v['totalMoney']) ? $v['totalMoney'] : '';//销售收入
  7268. $rows['saleCostAmount'] = isset($v['saleCostAmount']) ? $v['saleCostAmount'] : '';//销售成本
  7269. $rows['saleProfitAmount'] = isset($v['saleProfitAmount']) ? $v['saleProfitAmount'] : '';//销售毛利
  7270. $rows['saleProfitRate'] = isset($v['saleProfitRate']) ? $v['saleProfitRate'].'%' : '';//销售毛利率
  7271. foreach ($rows as $kk => $vv) {
  7272. $rs[$kk] = mb_convert_encoding($vv, 'GBK', 'utf-8'); //转译编码
  7273. }
  7274. fputcsv($fp, $rs);
  7275. $rows = [];
  7276. }
  7277. exit;
  7278. }
  7279. /**
  7280. * 拣货回写订单拣货状态
  7281. */
  7282. public function updateOrderPicking($orderIds,$orderPickStatus)
  7283. {
  7284. $tableName = $this->objDOrder->getTableName('qianniao_order_' . $this->onlineEnterpriseId, $this->onlineUserId, $this->cutTable);
  7285. $this->objDOrder->setTable($tableName);
  7286. if(!empty($orderIds)){
  7287. foreach ($orderIds as $orderId){
  7288. $dbResult = $this->objDOrder->update(['pickingStatus'=>$orderPickStatus],['id'=>$orderId]);
  7289. if ($dbResult === false){
  7290. return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror);
  7291. }
  7292. }
  7293. }
  7294. return ResultWrapper::success([]);
  7295. }
  7296. /**
  7297. *
  7298. *用户订单状态数量统计
  7299. */
  7300. public function getOrderStatusNum()
  7301. {
  7302. // 2待支付 3代发货 4待收货 5已完成 10退货
  7303. $returnData = [
  7304. '2' => 0,
  7305. '3' => 0,
  7306. '4' => 0,
  7307. '5' => 0,
  7308. '10' => 0
  7309. ];
  7310. // 查询订单各状态对应的总条数
  7311. $sql = 'SELECT count(orderStatus) as total,orderStatus FROM qianniao_order_index_'.$this->onlineEnterpriseId.' WHERE deleteStatus = '.StatusCode::$standard.' AND userCenterId = '.$this->onlineUserId.' GROUP BY orderStatus';
  7312. $dbResult = $this->objDOrderIndex->query($sql);
  7313. if($dbResult === false){
  7314. return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
  7315. }
  7316. if (!empty($dbResult)){
  7317. foreach ($dbResult as $key => $value){
  7318. $returnData[$value['orderStatus']] = $value['total'];
  7319. }
  7320. }
  7321. // 查询退货状态总条数
  7322. unset($dbResult);
  7323. $sql = 'SELECT count(id) as total FROM qianniao_order_return_'.$this->onlineEnterpriseId.' WHERE deleteStatus = '.StatusCode::$standard.' AND userCenterId = '.$this->onlineUserId;
  7324. $dbResult = $this->objDOrderIndex->query($sql);
  7325. if($dbResult === false){
  7326. return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
  7327. }
  7328. if (!empty($dbResult)){
  7329. $returnData[10] = $dbResult[0]['total'];
  7330. }
  7331. return ResultWrapper::success($returnData);
  7332. }
  7333. }