WholeController.php 286 KB

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