WholeController.php 207 KB

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