WholeController.php 284 KB

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