WholeController.php 287 KB

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