WholeController.php 287 KB

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