WholeController.php 283 KB

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