WholeController.php 229 KB

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