WholeController.php 285 KB

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