WholeController.php 297 KB

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