WholeController.php 233 KB

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