OrderServiceImpl.java 233 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527
  1. package com.kmall.admin.service.impl;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.fasterxml.jackson.core.type.TypeReference;
  5. import com.google.common.collect.ImmutableBiMap;
  6. import com.google.common.collect.Lists;
  7. import com.google.common.collect.Maps;
  8. import com.google.gson.Gson;
  9. import com.google.gson.internal.LinkedTreeMap;
  10. import com.kmall.admin.biz.CustomsClearanceTimeliness;
  11. import com.kmall.admin.dao.*;
  12. import com.kmall.admin.dao.alarm.Mall2LowPriceWarningDao;
  13. import com.kmall.admin.dao.mk.Mk2GoodsTopicPriceDao;
  14. import com.kmall.admin.dao.mk.Mk2MemberBirthdayDao;
  15. import com.kmall.admin.dao.mk.store.MkStorePromOrderRealDao;
  16. import com.kmall.admin.dao.mk.store.MkStorePromTypeDao;
  17. import com.kmall.admin.dao.mk.store.StoreTopicDao;
  18. import com.kmall.admin.dao.vip.Mall2MemberConsumptionRecordsDao;
  19. import com.kmall.admin.dao.vip.Mall2MemberPointsDao;
  20. import com.kmall.admin.dao.vip.Mall2PointsRulesDao;
  21. import com.kmall.admin.dto.*;
  22. import com.kmall.admin.entity.*;
  23. import com.kmall.admin.entity.kmall2eccs.KtoEccsEntity;
  24. import com.kmall.admin.entity.mk.MkActivitiesEntity;
  25. import com.kmall.admin.entity.mk.store.MkStorePromOrderRealEntity;
  26. import com.kmall.admin.entity.record.NewRetailOrderRestoreStockRecordEntity;
  27. import com.kmall.admin.entity.vip.Mall2MemberConsumptionRecordsEntity;
  28. import com.kmall.admin.entity.vip.Mall2MemberPointsEntity;
  29. import com.kmall.admin.entity.vip.Mall2PointsRulesEntity;
  30. import com.kmall.admin.fromcomm.dao.SysConfigDao;
  31. import com.kmall.admin.fromcomm.entity.SysUserEntity;
  32. import com.kmall.admin.haikong.constant.Constants;
  33. import com.kmall.admin.haikong.dto.WareQueryStockResponseDTO;
  34. import com.kmall.admin.haikong.utils.ListUtils;
  35. import com.kmall.admin.haikong.vo.QueryGoodsVo;
  36. import com.kmall.admin.haikong.client.HaiKongMemberTemplate;
  37. import com.kmall.admin.haikong.client.HaiKongWarehouseTemplate;
  38. import com.kmall.admin.haikong.config.HaiKongProperties;
  39. import com.kmall.admin.haikong.dto.MemberInfoDTO;
  40. import com.kmall.admin.haikong.utils.Response;
  41. import com.kmall.admin.service.*;
  42. import com.kmall.admin.service.kmall2eccs.KtoEccsService;
  43. import com.kmall.admin.service.mk.MkActivitiesService;
  44. import com.kmall.admin.service.mk.store.MkStoreCampMinusService;
  45. import com.kmall.admin.service.mk.store.MkStoreTicketDiscountService;
  46. import com.kmall.admin.service.record.NewRetailOrderRestoreStockRecordService;
  47. import com.kmall.admin.utils.CalculateTax;
  48. import com.kmall.admin.utils.ShiroUtils;
  49. import com.kmall.admin.utils.data.response.ResponseMessage;
  50. import com.kmall.admin.utils.data.response.ResponseMessageData;
  51. import com.kmall.admin.utils.jackson.JacksonUtil;
  52. import com.kmall.admin.utils.oms.OmsSign;
  53. import com.kmall.admin.utils.pdf.BarcodeUtil;
  54. import com.kmall.admin.vo.CalculateOrderDiscountPriceVo;
  55. import com.kmall.admin.websocket.WebSocketServer;
  56. import com.kmall.api.entity.OrderGoodsRestoreVo;
  57. import com.kmall.api.entity.OrderGoodsVo;
  58. import com.kmall.api.entity.OrderVo;
  59. import com.kmall.api.util.CommonUtil;
  60. import com.kmall.common.constant.Dict;
  61. import com.kmall.common.utils.*;
  62. import com.kmall.common.utils.print.ticket.item.*;
  63. import com.kmall.common.utils.wechat.WechatMicropayApiResult;
  64. import com.kmall.common.utils.wechat.WechatRefundApiResult;
  65. import com.kmall.common.utils.wechat.WechatReverseApiResult;
  66. import com.kmall.manager.manager.alipay.AliPayMicropayApiResult;
  67. import com.kmall.manager.manager.alipay.AliPayRequestParams;
  68. import com.kmall.manager.manager.alipay.AliPayUtil;
  69. import com.kmall.manager.manager.express.kdn.KdniaoUtil;
  70. import com.kmall.manager.manager.express.sf.ServiceException;
  71. import com.kmall.manager.manager.express.sf.entity.RouteEntity;
  72. import com.kmall.manager.manager.express.sf.entity.RouteResponseEntity;
  73. import com.kmall.manager.manager.express.sf.entity.SfRouteServiceResponseEntity;
  74. import com.kmall.manager.manager.express.sf.properties.SFPropertiesBuilder;
  75. import com.kmall.manager.manager.express.sf.properties.SFUtil;
  76. import com.kmall.manager.manager.merch.OmsMerchProperties;
  77. import com.kmall.manager.manager.merch.OmsMerchPropertiesBuilder;
  78. import com.kmall.manager.manager.print.ticket.PrintTicketPropertiesBuilder;
  79. import com.kmall.manager.manager.print.ticket.TicketPrintUtil;
  80. import com.kmall.manager.manager.redis.JedisUtil;
  81. import com.kmall.manager.manager.wechat.WechatUtil;
  82. import com.kmall.manager.manager.wechat.wxglobal.dto.WechatGlobalRefundApiResult;
  83. import com.qiniu.util.Json;
  84. import okhttp3.Request;
  85. import org.apache.shiro.crypto.hash.Hash;
  86. import org.slf4j.Logger;
  87. import org.slf4j.LoggerFactory;
  88. import org.springframework.beans.BeanUtils;
  89. import org.springframework.beans.factory.annotation.Autowired;
  90. import org.springframework.stereotype.Service;
  91. import org.springframework.transaction.annotation.Transactional;
  92. import org.springframework.util.CollectionUtils;
  93. import java.io.IOException;
  94. import java.math.BigDecimal;
  95. import java.math.RoundingMode;
  96. import java.net.InetAddress;
  97. import java.net.URLDecoder;
  98. import java.text.ParseException;
  99. import java.text.SimpleDateFormat;
  100. import java.util.*;
  101. import java.util.concurrent.*;
  102. import java.util.concurrent.atomic.AtomicBoolean;
  103. import java.util.concurrent.atomic.AtomicReference;
  104. import java.util.stream.Collectors;
  105. @Service("orderService")
  106. public class OrderServiceImpl implements OrderService {
  107. private final Logger LOGGER = LoggerFactory.getLogger(OrderServiceImpl.class);
  108. @Autowired
  109. private OmsMerchProperties omsMerchProperties;
  110. @Autowired
  111. private OrderDao orderDao;
  112. @Autowired
  113. private ShippingDao shippingDao;
  114. @Autowired
  115. private OrderGoodsDao orderGoodsDao;
  116. @Autowired
  117. private OrderGoodsService orderGoodsService;
  118. @Autowired
  119. private ProductStoreRelaService productStoreRelaService;
  120. @Autowired
  121. private NewRetailOrderRestoreStockRecordService newRetailOrderRestoreStockRecordService;
  122. @Autowired
  123. private SysPrinterDao printerDao;
  124. @Autowired
  125. private UserDao userDao;
  126. @Autowired
  127. private UserCouponDao userCouponDao;
  128. @Autowired
  129. private ProductStoreRelaDao productStoreRelaDao;
  130. @Autowired
  131. private OrderProcessRecordDao orderProcessRecordDao;
  132. @Autowired
  133. private OrderRefundDao orderRefundDao;
  134. @Autowired
  135. private StoreDao storeDao;
  136. @Autowired
  137. private OfflineCartDao offlineCartDao;
  138. @Autowired
  139. private GoodsDao goodsDao;
  140. @Autowired
  141. private MerchDao merchDao;
  142. @Autowired
  143. private MngChangeDao mngChangeDao;
  144. @Autowired
  145. private StoreMngChangeDao storeMngChangeDao;
  146. @Autowired
  147. private ThirdMerchExpressDao thirdMerchExpressDao;
  148. @Autowired
  149. private MkStorePromOrderRealDao mkStorePromOrderRealDao;
  150. @Autowired
  151. private UserCampMinusDao userCampMinusDao;
  152. @Autowired
  153. private UserService userService;
  154. @Autowired
  155. private SysConfigDao sysConfigDao;
  156. @Autowired
  157. private ProductDao productDao;
  158. @Autowired
  159. private GoodsService goodsService;
  160. @Autowired
  161. private OrderWXPayRecordService orderWXPayRecordService;
  162. @Autowired
  163. private StoreService storeService;
  164. @Autowired
  165. private PickUpCodeService pickUpCodeService;
  166. @Autowired
  167. private MkStoreCampMinusService mkStoreCampMinusService;
  168. @Autowired
  169. private MkStoreTicketDiscountService mkStoreTicketDiscountService;
  170. @Autowired
  171. private CashierDao cashierDao; // 收银机查询
  172. @Autowired
  173. private CashierLoginRecordDao cashierLoginRecordDao; // 收银员登录记录
  174. @Autowired
  175. private SaleRecordDao saleRecordDao; // 销售记录
  176. @Autowired
  177. private StoreTopicDao storeTopicDao; // 查询是否有门店活动
  178. @Autowired
  179. private Mk2GoodsTopicPriceDao mk2GoodsTopicPriceDao; // 门店商品价格
  180. @Autowired
  181. private Mall2PointsRulesDao pointsRulesDao; // 积分规则
  182. @Autowired
  183. private Mall2MemberPointsDao memberPointsDao; // 用户积分
  184. @Autowired
  185. private Mall2MemberConsumptionRecordsDao memberConsumptionRecordsDao; // 会员消费记录
  186. @Autowired
  187. private MkStorePromTypeDao storePromTypeDao; // 优惠类型
  188. @Autowired
  189. private Mk2MemberBirthdayDao memberBirthdayDao; // 生日优惠
  190. @Autowired
  191. private MerchUserDao merchUserDao;
  192. @Autowired
  193. private Mall2LowPriceWarningDao lowPriceWarningDao;
  194. @Autowired
  195. private OrderRefundService orderRefundService;
  196. @Autowired
  197. private OrderExceptionRecordService orderExceptionRecordService;
  198. @Autowired
  199. private AddressInfoService addressInfoService;
  200. @Autowired
  201. private KtoEccsService ktoEccsService;
  202. @Autowired
  203. private CustomsClearanceTimeliness customsClearanceTimeliness;
  204. @Autowired
  205. private HaiKongMemberTemplate haiKongMemberTemplate;
  206. @Autowired
  207. private HaiKongWarehouseTemplate haiKongWarehouseTemplate;
  208. @Autowired
  209. private HaiKongProperties haiKongProperties;
  210. @Autowired
  211. private MkActivitiesService mkActivitiesService;
  212. /**
  213. * 满赠
  214. */
  215. @Autowired
  216. private MkActivitiesFullGiftService mkActivitiesFullGiftService;
  217. /**
  218. * 优惠券
  219. */
  220. @Autowired
  221. private MkActivitiesCouponService mkActivitiesCouponService;
  222. /**
  223. * 限时特价
  224. */
  225. @Autowired
  226. private MkActivitiesPromotionService mkActivitiesPromotionService;
  227. @Override
  228. public OrderEntity queryObject(Long id) {
  229. return orderDao.queryObject(id);
  230. }
  231. @Override
  232. public Double getTotalActualPrice(String merchOrderSn) {
  233. return orderDao.getTotalActualPrice(merchOrderSn);
  234. }
  235. @Override
  236. public List<OrderEntity> queryList(Map<String, Object> map) {
  237. return orderDao.queryList(map);
  238. }
  239. @Override
  240. public int queryTotal(Map<String, Object> map) {
  241. return orderDao.queryTotal(map);
  242. }
  243. @Override
  244. public int save(OrderEntity order) {
  245. return orderDao.save(order);
  246. }
  247. @Override
  248. public int update(OrderEntity order) {
  249. return orderDao.update(order);
  250. }
  251. /**
  252. * 取消订单
  253. *
  254. * @param order
  255. */
  256. @Override
  257. public void cancelOrder(OrderEntity order) {
  258. boolean needUpdateStock = true;
  259. if (order.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_0.getItem())) {
  260. order.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_101.getItem()));
  261. }
  262. orderDao.update(order);
  263. if (!needUpdateStock) {
  264. return;
  265. }
  266. // 更新库存
  267. updateStock(order, "管理后台取消订单");
  268. // 释放优惠券
  269. UserCouponEntity couponVo = userCouponDao.queryByOrderId(order.getId());
  270. if (null != couponVo) {
  271. userCouponDao.cancelOrder(couponVo);
  272. }
  273. //释放促销满减券
  274. UserCampMinusEntity userCampMinusVo = userCampMinusDao.queryUserCampByOrderId(order.getId());
  275. if (null != userCampMinusVo) {
  276. userCampMinusDao.cancelUserCampOrder(userCampMinusVo);
  277. }
  278. }
  279. @Override
  280. public int delete(Long id) {
  281. return orderDao.delete(id);
  282. }
  283. @Override
  284. public int deleteBatch(Long[] ids) {
  285. return orderDao.deleteBatch(ids);
  286. }
  287. @Override
  288. public int confirm(Long id) {
  289. OrderEntity orderEntity = queryObject(id);
  290. Integer shippingStatus = orderEntity.getShippingStatus();//发货状态
  291. Integer payStatus = orderEntity.getPayStatus();//付款状态
  292. if (2 != payStatus) {
  293. throw new RRException("此订单未付款,不能确认收货!");
  294. }
  295. if (4 == shippingStatus) {
  296. throw new RRException("此订单处于退货状态,不能确认收货!");
  297. }
  298. if (0 == shippingStatus) {
  299. throw new RRException("此订单未发货,不能确认收货!");
  300. }
  301. if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_301.getItem())) {
  302. throw new RRException("此订单已完成!");
  303. }
  304. if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_0.getItem())) {
  305. throw new RRException("此订单待付款!");
  306. }
  307. if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_100.getItem())) {
  308. throw new RRException("此订单付款中!");
  309. }
  310. if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_101.getItem())) {
  311. throw new RRException("此订单已取消!");
  312. }
  313. if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_102.getItem())) {
  314. throw new RRException("此订单已删除!");
  315. }
  316. if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())) {
  317. throw new RRException("此订单还未发货!");
  318. }
  319. if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_401.getItem())) {
  320. throw new RRException("此订单已退款!");
  321. }
  322. if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_402.getItem())) {
  323. throw new RRException("此订单已退款!");
  324. }
  325. orderEntity.setShippingStatus(2);
  326. orderEntity.setOrderStatus(301);
  327. orderEntity.setConfirmTime(new Date());
  328. orderDao.update(orderEntity);
  329. return 0;
  330. }
  331. @Override
  332. public int sendGoods(OrderEntity order) {
  333. Integer payStatus = order.getPayStatus();//付款状态
  334. if (2 != payStatus) {
  335. throw new RRException("此订单未付款!");
  336. }
  337. ShippingEntity shippingEntity = shippingDao.queryObject(order.getShippingId());
  338. if (null != shippingEntity) {
  339. order.setShippingName(shippingEntity.getName());
  340. }
  341. order.setOrderStatus(300);//订单已发货
  342. order.setShippingStatus(1);//已发货
  343. return orderDao.update(order);
  344. }
  345. @Override
  346. public Ticket printMsg(Long id) {
  347. OrderEntity orderEntity = queryInfos(id);
  348. List<OrderGoodsEntity> orderGoodsEntityList = orderEntity.getOrderGoodsEntityList();
  349. // 获取门店
  350. StoreEntity storeEntity = storeDao.queryObject(orderEntity.getStoreId());
  351. // 获取清关信息
  352. OrderProcessRecordEntity orderProcessRecordEntity =
  353. orderProcessRecordDao.queryObjectByOrderSn(orderEntity.getOrderSn());
  354. // 小票头
  355. TicketHead head = new TicketHead();
  356. head.setTitle(OmsMerchPropertiesBuilder.instance().getMerchName() + storeEntity.getStoreName());
  357. // head.setMemberId(orderEntity.getUserName().toString());
  358. head.setOrderId(orderEntity.getOrderSn());
  359. head.setTradeTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss EEE").format(new Date()));
  360. // 商品信息
  361. Integer goodsTotal = 0; // 商品总个数
  362. BigDecimal total = Constant.ZERO; // 商品总计
  363. BigDecimal taxTotal = Constant.ZERO; //税费总计
  364. List<Goods> goodsList = new ArrayList<>();
  365. for (OrderGoodsEntity orderGoods : orderGoodsEntityList) {
  366. goodsTotal += orderGoods.getNumber();
  367. total = total.add(orderGoods.getRetailPrice().multiply(new BigDecimal(orderGoods.getNumber())))
  368. .setScale(2, BigDecimal.ROUND_HALF_UP);
  369. BigDecimal currentTax = orderGoods.getGoodsRate().multiply(orderGoods.getRetailPrice().multiply(new BigDecimal(orderGoods.getNumber())))
  370. .setScale(2, BigDecimal.ROUND_HALF_UP);
  371. taxTotal = taxTotal.add(currentTax);
  372. Goods goods = new Goods(orderGoods.getGoodsName(),
  373. orderGoods.getRetailPrice().toString(),
  374. currentTax.toString(),
  375. orderGoods.getNumber().toString(),
  376. new BigDecimal(orderGoods.getNumber()).multiply(orderGoods.getRetailPrice()).setScale(2, RoundingMode.HALF_UP).toString());
  377. goodsList.add(goods);
  378. LOGGER.info(goods.toString());
  379. }
  380. // 收银信息
  381. CashInfo cashInfo = new CashInfo();
  382. cashInfo.setGoodsTotal(goodsTotal.toString());
  383. cashInfo.setTotal(total.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
  384. cashInfo.setTaxTotal(taxTotal.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
  385. cashInfo.setReceipts(orderEntity.getActualPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
  386. cashInfo.setOddChange("0.00");
  387. cashInfo.setCoupon(orderEntity.getCouponPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
  388. cashInfo.setFreight(
  389. new BigDecimal(orderEntity.getFreightPrice()).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
  390. cashInfo.setPaymentMode("微信支付");
  391. // 海关清单
  392. CusListing cusListing = new CusListing();
  393. cusListing.setOrderId(orderEntity.getOrderSn());
  394. if (!orderEntity.getOrderBizType().equalsIgnoreCase(Dict.orderBizType.item_11.getItem())) {
  395. cusListing.setWaybillId(orderProcessRecordEntity.getLogisticsNo());
  396. cusListing.setInvtNo(orderProcessRecordEntity.getInvtNo());
  397. cusListing.setConsignee(orderEntity.getConsignee());
  398. cusListing.setConsigneeTel(orderEntity.getMobile());
  399. }
  400. cusListing.setOriginAddress(PrintTicketPropertiesBuilder.instance().getAddress());
  401. cusListing.setDeliveryAddress(storeEntity.getStoreAddress());
  402. return TicketPrintUtil.print(head, goodsList, cashInfo, cusListing);
  403. }
  404. @Override
  405. public Ticket printMsg(Long id, String sessionId) {
  406. OrderEntity orderEntity = queryInfos(id);
  407. List<OrderGoodsEntity> orderGoodsEntityList = orderEntity.getOrderGoodsEntityList();
  408. // 获取门店
  409. StoreEntity storeEntity = storeDao.queryObject(orderEntity.getStoreId());
  410. // 获取清关信息
  411. OrderProcessRecordEntity orderProcessRecordEntity =
  412. orderProcessRecordDao.queryObjectByOrderSn(orderEntity.getOrderSn());
  413. // 小票头
  414. TicketHead head = new TicketHead();
  415. head.setTitle(storeEntity.getStoreName());
  416. // head.setMemberId(orderEntity.getUserName().toString());
  417. head.setOrderId(orderEntity.getOrderSn());
  418. head.setTradeTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss EEE").format(orderEntity.getPayTime()));
  419. // 商品信息
  420. Integer goodsTotal = 0; // 商品总个数
  421. BigDecimal total = Constant.ZERO; // 商品总计
  422. BigDecimal taxTotal = Constant.ZERO; //税费总计
  423. List<Goods> goodsList = new ArrayList<>();
  424. BigDecimal discountedPrice = Constant.ZERO; // 优惠金额
  425. for (OrderGoodsEntity orderGoods : orderGoodsEntityList) {
  426. goodsTotal += orderGoods.getNumber();
  427. total = total.add(orderGoods.getRetailPrice().multiply(new BigDecimal(orderGoods.getNumber())))
  428. .setScale(2, BigDecimal.ROUND_HALF_UP);
  429. discountedPrice = discountedPrice.add(orderGoods.getDiscountedPrice());
  430. // 税前价
  431. BigDecimal beforeTaxPrice = orderGoods.getRetailPrice().divide(new BigDecimal(1).add(orderGoods.getGoodsRate()), 2, RoundingMode.HALF_UP);
  432. GoodsEntity goodsEntity = goodsService.queryObject(orderGoods.getGoodsId());
  433. BigDecimal goodsTax = CalculateTax.calculateFinalTax(goodsEntity, orderGoods.getRetailPrice(), goodsService).setScale(3, RoundingMode.HALF_UP);
  434. goodsTax = goodsTax.multiply(new BigDecimal(orderGoods.getNumber())).setScale(2, RoundingMode.HALF_UP);
  435. taxTotal = taxTotal.add(goodsTax).setScale(2, RoundingMode.HALF_UP);
  436. Goods goods = new Goods(orderGoods.getGoodsName(),
  437. orderGoods.getRetailPrice().toString(), // 含税价
  438. // beforeTaxPrice.toString(),// 税前价
  439. goodsTax.toString(),
  440. orderGoods.getNumber().toString(),
  441. new BigDecimal(orderGoods.getNumber()).multiply(orderGoods.getRetailPrice()).setScale(2, RoundingMode.HALF_UP).toString(),
  442. orderGoods.getDiscountedPrice().toString());
  443. goodsList.add(goods);
  444. }
  445. // 收银信息
  446. CashInfo cashInfo = new CashInfo();
  447. cashInfo.setGoodsTotal(goodsTotal.toString());
  448. cashInfo.setTotal(total.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
  449. cashInfo.setTaxTotal(taxTotal.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
  450. cashInfo.setReceipts(orderEntity.getActualPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
  451. cashInfo.setOddChange(discountedPrice.toString());
  452. cashInfo.setCoupon(orderEntity.getCouponPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
  453. cashInfo.setFreight(
  454. new BigDecimal(orderEntity.getFreightPrice()).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
  455. if ("alipay".equals(orderEntity.getPayFlag())) {
  456. cashInfo.setPaymentMode("支付宝支付");
  457. } else {
  458. cashInfo.setPaymentMode("微信支付");
  459. }
  460. // 海关清单
  461. CusListing cusListing = new CusListing();
  462. cusListing.setOrderId(orderEntity.getOrderSn());
  463. if (!orderEntity.getOrderBizType().equalsIgnoreCase(Dict.orderBizType.item_11.getItem())) {
  464. cusListing.setWaybillId(orderProcessRecordEntity.getLogisticsNo());
  465. cusListing.setInvtNo(orderProcessRecordEntity.getInvtNo());
  466. cusListing.setConsignee(orderEntity.getConsignee());
  467. // 脱敏设置
  468. if (StringUtils.isNotEmpty(cusListing.getConsignee()) && cusListing.getConsignee().length() > 1) {
  469. cusListing.setConsignee(new StringBuilder(cusListing.getConsignee()).replace(1, 2, "*").toString());
  470. }
  471. cusListing.setConsigneeTel(orderEntity.getMobile());
  472. if (StringUtils.isNotEmpty(cusListing.getConsigneeTel())) {
  473. cusListing.setConsigneeTel(new StringBuilder(cusListing.getConsigneeTel()).replace(3, 7, "****").toString());
  474. // cusListing.setConsigneeTel(cusListing.getConsigneeTel());
  475. }
  476. }
  477. cusListing.setOriginAddress(PrintTicketPropertiesBuilder.instance().getAddress());
  478. cusListing.setDeliveryAddress(storeEntity.getStoreAddress());
  479. // 尝试在取货码表中查询数据,如果有的话就改变状态
  480. String orderSn = orderEntity.getOrderSn();
  481. PickUpCodeEntity pickUpCodeEntity = pickUpCodeService.queryObject(orderSn);
  482. if (pickUpCodeEntity != null) {
  483. pickUpCodeEntity.setPickUpCodeStatus("1");
  484. pickUpCodeService.update(pickUpCodeEntity);
  485. // try {
  486. // WebSocketServer.delete(sessionId,orderEntity.getStoreId(),pickUpCodeEntity);
  487. // } catch (IOException e) {
  488. // e.printStackTrace();
  489. // }
  490. }
  491. TicketMailInfo mailInfo = new TicketMailInfo();
  492. String exprNo = orderProcessRecordEntity.getLogisticsNo();
  493. if (StringUtils.isNullOrEmpty(exprNo)) {
  494. throw new RRException("快递面单为空,请联系客服");
  495. }
  496. //图片地址
  497. mailInfo.setStoreImgUrl(storeEntity.getStoreImgUrl()==null?"/statics/img/cw_qrcode.png":storeEntity.getStoreImgUrl().trim());
  498. mailInfo.setExprNo(exprNo);
  499. String logoUrl = "/statics/img/yto_logo.jpg";
  500. Map<String, String> logoMap = new HashMap<>();
  501. logoMap.put("yto", "/statics/img/yto_logo.jpg");
  502. logoMap.put("best", "/statics/img/bestex_logo3.png");
  503. if (StringUtils.isNotEmpty(orderEntity.getShippingCode()) && logoMap.containsKey(orderEntity.getShippingCode())) {
  504. logoUrl = logoMap.get(orderEntity.getShippingCode());
  505. }
  506. mailInfo.setExprLogoUrl(logoUrl);
  507. byte[] barCode128 = BarcodeUtil.generateBarCode128(exprNo, 6.0D, null, true, false);
  508. String exprNoBase64Img = new String(Base64.getEncoder().encode(barCode128));
  509. mailInfo.setShopTel(storeEntity.getTelephoneNumber()==null?"0752-2688660":storeEntity.getTelephoneNumber().trim());
  510. // 发货人
  511. mailInfo.setSenderTel("0752-2688660");
  512. mailInfo.setSenderName("CW澳洲大药房");
  513. mailInfo.setSenderProvince("广东省");
  514. mailInfo.setSenderCity("深圳市");
  515. mailInfo.setSenderDistrict("南山区");
  516. mailInfo.setSenderAddress("前海综合保税区W104");
  517. // 收货人
  518. mailInfo.setConsigneeMob(new StringBuilder(orderEntity.getMobile()).replace(3, 7, "****").toString());
  519. // mailInfo.setConsigneeMob(orderEntity.getMobile());
  520. mailInfo.setConsigneeName(new StringBuilder(orderEntity.getConsignee()).replace(1, 2, "*").toString());
  521. mailInfo.setConsigneeProvince(orderEntity.getProvince());
  522. mailInfo.setConsigneeCity(orderEntity.getCity());
  523. mailInfo.setConsigneeDistrict(orderEntity.getDistrict());
  524. mailInfo.setConsigneeAddress(orderEntity.getAddress());
  525. mailInfo.setExprNoBase64Img(exprNoBase64Img);
  526. return TicketPrintUtil.print(head, goodsList, cashInfo, cusListing, mailInfo);
  527. }
  528. /**
  529. * 退款
  530. */
  531. @Transactional
  532. public void refund(OrderEntity order) {
  533. boolean needUpdateStock = true;
  534. if (order.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())) {
  535. order.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_401.getItem()));
  536. }
  537. if (Dict.payFlag.item_cash.getItem().equals(order.getPayFlag())) {
  538. order.setPayStatus(Integer.parseInt(Dict.payStatus.item_4.getItem()));
  539. }
  540. orderDao.update(order);//修改为退款中
  541. // TODO: 2019/6/13 定时任务查询退款成功后释放库存、优惠券
  542. /*// 判断是否有优惠券
  543. UserCouponEntity couponVo = userCouponDao.queryByOrderId(order.getId());
  544. if (null != couponVo) {
  545. userCouponDao.cancelOrder(couponVo);
  546. }
  547. if (!needUpdateStock) {
  548. return;
  549. }
  550. // 更新库存
  551. updateStock(order, "管理后台订单退款");*/
  552. // updateStock(order, "管理后台订单退款");
  553. queryStorePromRealUpdateIsScan(order);
  554. }
  555. /**
  556. * 退款
  557. */
  558. @Transactional
  559. public void refund(OrderEntity order, WechatRefundApiResult result) {
  560. boolean needUpdateStock = true;
  561. if (order.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())) {
  562. order.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_401.getItem()));
  563. }
  564. if (Dict.payFlag.item_cash.getItem().equals(order.getPayFlag())) {
  565. order.setPayStatus(Integer.parseInt(Dict.payStatus.item_4.getItem()));
  566. } else {
  567. order.setPayStatus(Integer.parseInt(Dict.payStatus.item_5.getItem()));
  568. OrderRefundEntity mallOrderRefund = orderRefundDao.queryObjectByOrderId(order.getId());
  569. OrderRefundEntity orderRefund = new OrderRefundEntity();
  570. orderRefund.setRefundId(result.getRefund_id());
  571. try {
  572. orderRefund.setOutRefundNo(result.getOut_trade_no());
  573. } catch (Exception e) {
  574. e.printStackTrace();
  575. }
  576. orderRefund.setRefundMoney(BigDecimal.valueOf(Long.valueOf(result.getRefund_fee())).divide(Constant.ONE_HUNDRED));
  577. orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_5.getItem()));//退款处理中
  578. orderRefund.setModTime(new Date());
  579. if (mallOrderRefund != null) {
  580. orderRefund.setId(mallOrderRefund.getId());
  581. orderRefund.setRefundType(mallOrderRefund.getRefundType());
  582. orderRefundDao.update(orderRefund);
  583. } else {
  584. orderRefund.setOrderId(Integer.parseInt(order.getId() + ""));
  585. orderRefund.setUserId(Integer.parseInt(order.getUserId() + ""));
  586. orderRefund.setCreateTime(new Date());
  587. List<OrderEntity> list = orderDao.queryObjectByMerchOrderSn(order.getMerchOrderSn());
  588. if (list.size() > 1) {//多条订单
  589. orderRefund.setRefundType(Integer.parseInt(Dict.RefundType.item_2.getItem()));//部分退款
  590. } else {
  591. orderRefund.setRefundType(Integer.parseInt(Dict.RefundType.item_1.getItem()));//用户全额退款
  592. }
  593. orderRefundDao.save(orderRefund);//退款记录
  594. }
  595. }
  596. orderDao.update(order);//
  597. // TODO: 2019/6/13 定时任务查询退款成功后释放库存、优惠券
  598. /*// 判断是否有优惠券
  599. UserCouponEntity couponVo = userCouponDao.queryByOrderId(order.getId());
  600. if (null != couponVo) {
  601. userCouponDao.cancelOrder(couponVo);
  602. }
  603. if (!needUpdateStock) {
  604. return;
  605. }
  606. // 更新库存
  607. updateStock(order, "管理后台订单退款");*/
  608. // updateStock(order, "管理后台订单退款");
  609. queryStorePromRealUpdateIsScan(order);
  610. }
  611. @Transactional
  612. public void refund(OrderEntity order, AliPayMicropayApiResult result) {
  613. if (order.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())) {
  614. order.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_401.getItem()));
  615. }
  616. if (Dict.payFlag.item_cash.getItem().equals(order.getPayFlag())) {
  617. order.setPayStatus(Integer.parseInt(Dict.payStatus.item_4.getItem()));
  618. } else {
  619. order.setPayStatus(Integer.parseInt(Dict.payStatus.item_4.getItem()));
  620. OrderRefundEntity mallOrderRefund = orderRefundDao.queryObjectByOrderId(order.getId());
  621. OrderRefundEntity orderRefund = new OrderRefundEntity();
  622. orderRefund.setRefundId(result.getTradeNo());
  623. orderRefund.setOutRefundNo(result.getOutTradeNo());
  624. orderRefund
  625. .setRefundMoney(new BigDecimal(result.getRefundFee()).divide(Constant.ONE_HUNDRED));
  626. orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_2.getItem()));//退款处理中
  627. orderRefund.setModTime(new Date());
  628. if (mallOrderRefund != null) {
  629. orderRefund.setId(mallOrderRefund.getId());
  630. orderRefund.setRefundType(mallOrderRefund.getRefundType());
  631. orderRefundDao.update(orderRefund);
  632. } else {
  633. orderRefund.setOrderId(Integer.parseInt(order.getId() + ""));
  634. orderRefund.setUserId(Integer.parseInt(order.getUserId() + ""));
  635. orderRefund.setCreateTime(new Date());
  636. List<OrderEntity> list = orderDao.queryObjectByMerchOrderSn(order.getMerchOrderSn());
  637. if (list.size() > 1) {//多条订单
  638. orderRefund.setRefundType(Integer.parseInt(Dict.RefundType.item_2.getItem()));//部分退款
  639. } else {
  640. orderRefund.setRefundType(Integer.parseInt(Dict.RefundType.item_1.getItem()));//用户全额退款
  641. }
  642. orderRefundDao.save(orderRefund);//退款记录
  643. }
  644. }
  645. orderDao.update(order);//修改为退款中
  646. updateStock(order, "收银端退款");
  647. }
  648. /**
  649. * 平安退款逻辑处理
  650. *
  651. * @param order
  652. * @param result
  653. */
  654. @Transactional
  655. public void pinganRefund(OrderEntity order, net.sf.json.JSONObject result, String refundId) {
  656. boolean needUpdateStock = true;
  657. if (order.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())) {
  658. order.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_401.getItem()));
  659. }
  660. order.setPayStatus(Integer.parseInt(Dict.payStatus.item_3.getItem()));
  661. OrderRefundEntity orderRefund = new OrderRefundEntity();
  662. orderRefund.setRefundId(refundId);
  663. orderRefund.setOutRefundNo(result.getString("ord_no"));
  664. orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_5.getItem()));//退款处理中
  665. orderRefund.setModTime(new Date());
  666. orderRefund.setRefundMoney(BigDecimal.valueOf(result.getInt("trade_amount")).divide(Constant.ONE_HUNDRED));
  667. OrderRefundEntity mallOrderRefund = orderRefundDao.queryObjectByOrderId(order.getId());
  668. if (mallOrderRefund != null) {
  669. orderRefund.setRefundType(mallOrderRefund.getRefundType());
  670. orderRefund.setId(mallOrderRefund.getId());
  671. orderRefundDao.update(orderRefund);
  672. } else {//退款记录不存在
  673. orderRefund.setOrderId(Integer.parseInt(order.getId() + ""));
  674. orderRefund.setUserId(Integer.parseInt(order.getUserId() + ""));
  675. orderRefund.setCreateTime(new Date());
  676. orderRefundDao.save(orderRefund);//退款记录
  677. }
  678. orderDao.update(order);//修改为退款中
  679. // TODO: 2019/6/13 定时任务查询退款成功后释放库存、优惠券
  680. /*// 判断是否有优惠券
  681. UserCouponEntity couponVo = userCouponDao.queryByOrderId(order.getId());
  682. if (null != couponVo) {
  683. userCouponDao.cancelOrder(couponVo);
  684. }
  685. if (!needUpdateStock) {
  686. return;
  687. }
  688. // 更新库存
  689. updateStock(order, "管理后台平安退款订单");*/
  690. queryStorePromRealUpdateIsScan(order);
  691. }
  692. /**
  693. * 微信国际退款逻辑处理
  694. *
  695. * @param order
  696. * @param result
  697. */
  698. @Transactional
  699. public void globalRefund(OrderEntity order, WechatGlobalRefundApiResult result) {
  700. boolean needUpdateStock = true;
  701. if (order.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())) {
  702. order.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_401.getItem()));
  703. }
  704. order.setPayStatus(Integer.parseInt(Dict.payStatus.item_3.getItem()));
  705. OrderRefundEntity orderRefund = new OrderRefundEntity();
  706. orderRefund.setRefundId(result.getRefund_id());
  707. orderRefund.setOutRefundNo(result.getOut_refund_no());
  708. orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_5.getItem()));//退款处理中
  709. orderRefund.setModTime(new Date());
  710. orderRefund.setRefundMoney(BigDecimal.valueOf(Long.valueOf(result.getRefund_fee())).divide(Constant.ONE_HUNDRED));
  711. orderRefund.setRefundFeeType(result.getRefund_fee_type());
  712. if (org.apache.commons.lang3.StringUtils.isNotEmpty(result.getTotal_fee())) {
  713. orderRefund.setTotalFee(Integer.parseInt(BigDecimal.valueOf(Long.valueOf(result.getTotal_fee())).divide(Constant.ONE_HUNDRED).toString()));
  714. }
  715. orderRefund.setFeeType(result.getFee_type());
  716. if (org.apache.commons.lang3.StringUtils.isNotEmpty(result.getCash_fee())) {
  717. orderRefund.setCashFee(Integer.parseInt(BigDecimal.valueOf(Long.valueOf(result.getCash_fee())).divide(Constant.ONE_HUNDRED).toString()));
  718. }
  719. orderRefund.setCashFeeType(result.getCash_fee_type());
  720. if (org.apache.commons.lang3.StringUtils.isNotEmpty(result.getCash_refund_fee())) {
  721. orderRefund.setCashRefundFee(Integer.parseInt(BigDecimal.valueOf(Long.valueOf(result.getCash_refund_fee())).divide(Constant.ONE_HUNDRED).toString()));
  722. }
  723. orderRefund.setCashRefundFeeType(result.getCash_refund_fee_type());
  724. OrderRefundEntity mallOrderRefund = orderRefundDao.queryObjectByOrderId(order.getId());
  725. if (mallOrderRefund != null) {
  726. orderRefund.setRefundType(mallOrderRefund.getRefundType());
  727. orderRefund.setId(mallOrderRefund.getId());
  728. orderRefundDao.update(orderRefund);
  729. } else {//退款记录不存在
  730. orderRefund.setOrderId(Integer.parseInt(order.getId() + ""));
  731. orderRefund.setUserId(Integer.parseInt(order.getUserId() + ""));
  732. orderRefund.setCreateTime(new Date());
  733. orderRefundDao.save(orderRefund);//退款记录
  734. }
  735. orderDao.update(order);//修改为退款中
  736. // TODO: 2019/6/13 定时任务查询退款成功后释放库存、优惠券
  737. /*// 判断是否有优惠券
  738. UserCouponEntity couponVo = userCouponDao.queryByOrderId(order.getId());
  739. if (null != couponVo) {
  740. userCouponDao.cancelOrder(couponVo);
  741. }
  742. if (!needUpdateStock) {
  743. return;
  744. }
  745. // 更新库存
  746. updateStock(order, "管理后台微信国际退款订单");*/
  747. queryStorePromRealUpdateIsScan(order);
  748. }
  749. private synchronized void restoreInventory(OrderEntity order, String changeReason) {
  750. Map<String, Object> map = new HashMap();
  751. SysUserEntity user = ShiroUtils.getUserEntity();
  752. map.put("orderId", order.getId());
  753. List<OrderGoodsEntity> orderGoodsVoList = orderGoodsDao.queryList(map);
  754. for (OrderGoodsEntity orderGoodsEntity : orderGoodsVoList) {
  755. ProductStoreRelaEntity storeRelaEntity = productStoreRelaDao
  756. .queryByGoodsIdAndStoreId(order.getStoreId().longValue(), orderGoodsEntity.getGoodsId().longValue());
  757. if (null == storeRelaEntity || null == storeRelaEntity.getSellVolume()) {
  758. storeRelaEntity.setSellVolume(0);
  759. }
  760. BigDecimal sellVolume = new BigDecimal(storeRelaEntity.getSellVolume() - orderGoodsEntity.getNumber());//销售量
  761. if (sellVolume.compareTo(Constant.ZERO) < 0) {
  762. sellVolume = Constant.ZERO;
  763. }
  764. // GoodsEntity goodsEntity = goodsDao.queryObject(orderGoodsEntity.getGoodsId());
  765. // if (goodsEntity != null) {
  766. // stockNum = goodsEntity.getGoodsNumber();
  767. // //还原商户商品库存
  768. // resetGoodsStock(stockNum, storeRelaEntity, orderGoodsEntity, sellVolume, changeReason, user);
  769. // }
  770. Integer stockNum = 0;
  771. if (null != storeRelaEntity.getStockNum()) {
  772. stockNum = storeRelaEntity.getStockNum();
  773. resetStoreGoodsStock(stockNum, storeRelaEntity, orderGoodsEntity, sellVolume, changeReason, user);//还原门店库存
  774. }
  775. }
  776. }
  777. private synchronized void updateStock(OrderEntity order, String changeReason) {
  778. Map<String, Object> map = new HashMap();
  779. SysUserEntity user = ShiroUtils.getUserEntity();
  780. map.put("orderId", order.getId());
  781. List<OrderGoodsEntity> orderGoodsVoList = orderGoodsDao.queryList(map);
  782. for (OrderGoodsEntity orderGoodsEntity : orderGoodsVoList) {
  783. ProductStoreRelaEntity storeRelaEntity = productStoreRelaDao
  784. .queryByGoodsIdAndStoreId(order.getStoreId().longValue(), orderGoodsEntity.getGoodsId().longValue());
  785. // .queryByStoreIdProductId(Long.valueOf(order.getStoreId()),Long.valueOf(orderGoodsEntity.getProductId()));
  786. if (null == storeRelaEntity || null == storeRelaEntity.getSellVolume()) {
  787. storeRelaEntity.setSellVolume(0);
  788. }
  789. BigDecimal sellVolume = new BigDecimal(storeRelaEntity.getSellVolume() - orderGoodsEntity.getNumber());//销售量
  790. if (sellVolume.compareTo(Constant.ZERO) < 0) {
  791. sellVolume = Constant.ZERO;
  792. }
  793. Integer stockNum = 0;
  794. GoodsEntity goodsEntity = goodsDao.queryObject(orderGoodsEntity.getGoodsId());
  795. if (goodsEntity != null) {
  796. stockNum = goodsEntity.getGoodsNumber();
  797. //还原商户商品库存
  798. resetGoodsStock(stockNum, storeRelaEntity, orderGoodsEntity, sellVolume, changeReason, user);
  799. }
  800. if (null != storeRelaEntity.getStockNum()) {
  801. stockNum = storeRelaEntity.getStockNum();
  802. //普通商品不受共享库存影响,直接取门店配置库存
  803. //该商品所属第三方商户不是共享库存
  804. if (goodsEntity.getIsStockShare().equalsIgnoreCase(Dict.isStockShare.item_0.getItem())) {
  805. resetStoreGoodsStock(stockNum, storeRelaEntity, orderGoodsEntity, sellVolume, changeReason, user);//还原门店库存
  806. } else {
  807. //该商品所属第三方商户是共享库存,但商品业务类型不是00保税备货
  808. if (!goodsEntity.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_00.getItem())) {
  809. resetStoreGoodsStock(stockNum, storeRelaEntity, orderGoodsEntity, sellVolume, changeReason, user);//还原门店库存
  810. }
  811. }
  812. }
  813. //该商品所属第三方商户为共享库存,且是保税备货商品,取消订单时改变
  814. updateGoodsByIsShareStock(goodsEntity);
  815. }
  816. }
  817. /**
  818. * 更新商品库存数量变化后是否已共享为0“未共享”
  819. *
  820. * @param goodsInfo
  821. */
  822. private void updateGoodsByIsShareStock(GoodsEntity goodsInfo) {
  823. //该商品所属第三方商户为共享库存,且是保税备货商品
  824. if (goodsInfo.getIsStockShare().equalsIgnoreCase(Dict.isStockShare.item_1.getItem())
  825. && goodsInfo.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_00.getItem())) {
  826. GoodsEntity goodsVo = new GoodsEntity();
  827. goodsVo.setId(goodsInfo.getId());
  828. //商品库存数量变化后是否已共享,0:否,1:是(下单、退款、取消订单触发)
  829. goodsVo.setIsGoodsShareStock(Dict.isGoodsShareStock.item_0.getItem());
  830. goodsDao.update(goodsVo);
  831. }
  832. }
  833. /**
  834. * 还原商品总库存
  835. *
  836. * @param stockNum
  837. * @param storeRelaEntity
  838. * @param orderGoodsEntity
  839. * @param sellVolume
  840. * @param changeReason
  841. * @param user
  842. */
  843. private void resetGoodsStock(Integer stockNum, ProductStoreRelaEntity storeRelaEntity,
  844. OrderGoodsEntity orderGoodsEntity, BigDecimal sellVolume, String changeReason, SysUserEntity user) {
  845. GoodsEntity goodsEntity = goodsDao.queryObject(storeRelaEntity.getGoodsId());
  846. if (goodsEntity != null) {
  847. goodsEntity.setGoodsNumber(stockNum + orderGoodsEntity.getNumber());
  848. // goodsEntity.setSellVolume(Integer.parseInt(goodsSellVolume.toString()));
  849. if ("oms退单成功,恢复库存".equals(changeReason)) {
  850. goodsEntity.setToBeRestored(goodsEntity.getToBeRestored() - orderGoodsEntity.getNumber());
  851. }
  852. goodsDao.update(goodsEntity);
  853. String username = "system";
  854. if (user != null) {
  855. username = user.getUsername();
  856. }
  857. MngChangeEntity mngChangeEntity = new MngChangeEntity();
  858. mngChangeEntity.setGoodsId(Integer.parseInt(String.valueOf(goodsEntity.getId())));
  859. mngChangeEntity.setThirdPartyMerchCode(goodsEntity.getThirdPartyMerchCode());
  860. mngChangeEntity.setChangeReason(changeReason);
  861. mngChangeEntity.setChangeType(Dict.changeType.item_0.getItem());
  862. mngChangeEntity.setChangeNum(orderGoodsEntity.getNumber());//变化数
  863. mngChangeEntity.setOriginalNum(stockNum);//原库存数
  864. mngChangeEntity.setValidNum(stockNum + orderGoodsEntity.getNumber());//可用数
  865. mngChangeEntity.setCreateTime(new Date());
  866. mngChangeEntity.setModTime(new Date());
  867. mngChangeEntity.setCreaterSn(username);
  868. mngChangeEntity.setModerSn(username);
  869. mngChangeEntity.setIsValid(0);
  870. mngChangeEntity.setMerchSn(goodsEntity.getMerchSn());
  871. mngChangeDao.save(mngChangeEntity);
  872. }
  873. }
  874. /**
  875. * 还原门店商品库存
  876. *
  877. * @param stockNum
  878. * @param storeRelaEntity
  879. * @param orderGoodsEntity
  880. * @param sellVolume
  881. * @param changeReason
  882. * @param user
  883. */
  884. private void resetStoreGoodsStock(Integer stockNum, ProductStoreRelaEntity storeRelaEntity,
  885. OrderGoodsEntity orderGoodsEntity, BigDecimal sellVolume, String changeReason, SysUserEntity user) {
  886. storeRelaEntity.setSellVolume(Integer.parseInt(sellVolume.toString())); // 减退库存
  887. storeRelaEntity.setStockNum(stockNum + orderGoodsEntity.getNumber());//库存数量
  888. if ("oms退单成功,恢复库存".equals(changeReason)) {
  889. storeRelaEntity.setToBeRestored(storeRelaEntity.getToBeRestored() - orderGoodsEntity.getNumber());
  890. }
  891. productStoreRelaDao.update(storeRelaEntity);
  892. String username = "system";
  893. if (user != null) {
  894. username = user.getUsername();
  895. }
  896. StoreMngChangeEntity storeMngChangeEntity = new StoreMngChangeEntity();
  897. storeMngChangeEntity.setChangeType(Dict.changeType.item_0.getItem());
  898. storeMngChangeEntity.setChangeReason(changeReason);
  899. storeMngChangeEntity.setGoodsId(Integer.parseInt(String.valueOf(storeRelaEntity.getGoodsId())));
  900. storeMngChangeEntity.setStoreId(Integer.parseInt(String.valueOf(storeRelaEntity.getStoreId())));
  901. storeMngChangeEntity.setMerchSn(storeRelaEntity.getMerchSn());
  902. storeMngChangeEntity.setStoreChangeNum(orderGoodsEntity.getNumber());
  903. storeMngChangeEntity.setStoreOriginalNum(stockNum);
  904. storeMngChangeEntity.setStoreValidNum(stockNum + orderGoodsEntity.getNumber());
  905. storeMngChangeEntity.setCreateTime(new Date());
  906. storeMngChangeEntity.setModTime(new Date());
  907. storeMngChangeEntity.setCreaterSn(username);
  908. storeMngChangeEntity.setModerSn(username);
  909. storeMngChangeEntity.setIsValid(0);
  910. storeMngChangeDao.save(storeMngChangeEntity);
  911. }
  912. /**
  913. * 查询该退款订单编号是否是推广渠道订单,是则修改渠道定时扫描状态
  914. *
  915. * @param orderInfo
  916. */
  917. private void queryStorePromRealUpdateIsScan(OrderEntity orderInfo) {
  918. Map map = new HashMap();
  919. map.put("orderId", orderInfo.getId());
  920. List<MkStorePromOrderRealEntity> list = mkStorePromOrderRealDao.queryPromRealListByMap(map);
  921. if (list.size() > 0) {
  922. for (MkStorePromOrderRealEntity mkStorePromOrderRealEntity : list) {
  923. mkStorePromOrderRealEntity.setIsPromStatScan(Dict.isDistSellScan.item_0.getItem());
  924. mkStorePromOrderRealDao.update(mkStorePromOrderRealEntity);
  925. }
  926. }
  927. }
  928. /**
  929. * 处理用户退款申请
  930. *
  931. * @param orderInfo
  932. */
  933. @Transactional
  934. public void applyRefundDeal(OrderEntity orderInfo, OrderRefundEntity refundEntity) {
  935. refundEntity.setApprovalTime(new Date());
  936. // refundEntity.setApprover(ShiroUtils.getUserId());
  937. // 退积分
  938. try {
  939. Integer integral = 1;
  940. if (orderInfo.getActualPrice().intValue() > 0) {
  941. integral = orderInfo.getActualPrice().intValue();
  942. }
  943. if (refundEntity.getRefundStatus() == 2) {
  944. orderInfo.setOrderStatus(401);
  945. // UserEntity entity = userDao.queryObject(orderInfo.getUserId());
  946. } else {
  947. orderInfo.setOrderStatus(201);
  948. }
  949. } catch (Exception e) {
  950. e.printStackTrace();
  951. }
  952. orderRefundDao.update(refundEntity);
  953. orderDao.update(orderInfo);
  954. }
  955. @Override
  956. public OrderRefundEntity queryRefundObject(Long refundId) {
  957. return orderRefundDao.queryObject(refundId);
  958. }
  959. @Override
  960. public List<OrderRefundEntity> queryRefundList(Map<String, Object> map) {
  961. return orderRefundDao.queryList(map);
  962. }
  963. @Override
  964. public int queryRefundTotal(Map<String, Object> map) {
  965. return orderRefundDao.queryTotal(map);
  966. }
  967. @Override
  968. public int getUserOrderInfo(Map<String, Object> map) {
  969. int result = 0;
  970. String type = (String) map.get("type");
  971. if ("yfkOrderUserSum".equals(type)) {
  972. result = orderDao.getYfkOrderUserSum(map);
  973. } else if ("oderUserSum".equals(type)) {
  974. result = orderDao.getOderUserSum(map);
  975. } else if ("todayUserOrder".equals(type)) {
  976. result = orderDao.getTodayUserOrder(map);
  977. } else if ("todayUserSales".equals(type)) {
  978. result = orderDao.getTodayUserSales(map);
  979. } else if ("incomeSum".equals(type)) {
  980. result = orderDao.getIncomeSum(map);
  981. } else if ("payedOrderCount".equals(type)) {
  982. result = orderDao.getPayedOrderCount(map);
  983. }
  984. return result;
  985. }
  986. @Override
  987. public Map getLogistics(Long id) {
  988. OrderEntity orderEntity = queryObject(id);
  989. if (orderEntity == null) {
  990. throw new RRException("此订单不存在!");
  991. }
  992. if (orderEntity.getShippingStatus() == 0) {
  993. if (orderEntity.getOrderBizType().equalsIgnoreCase(Dict.orderBizType.item_00.getItem()) ||
  994. orderEntity.getOrderBizType().equalsIgnoreCase(Dict.orderBizType.item_02.getItem())) {
  995. throw new RRException("此订单还未发货!");
  996. } else {
  997. if (StringUtils.isNullOrEmpty(orderEntity.getShippingNo())) {
  998. throw new RRException("此订单还未发货!");
  999. }
  1000. }
  1001. }
  1002. Map logisticsInfo = Maps.newHashMap();
  1003. List<WuliuEntity> wuliuEntityList = new ArrayList<>();
  1004. OrderProcessRecordEntity orderProcessRecordEntity =
  1005. orderProcessRecordDao.queryObjectByOrderSn(orderEntity.getOrderSn());
  1006. if (orderProcessRecordEntity != null) {
  1007. if (orderEntity.getOrderBizType().equals(Dict.orderBizType.item_10.getItem()) ||
  1008. orderEntity.getOrderBizType().equals(Dict.orderBizType.item_02.getItem())) {
  1009. WuliuEntity wuliuEntity = new WuliuEntity();
  1010. wuliuEntity.setAcceptTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
  1011. .format(orderProcessRecordEntity.getCustomsSuccTime()));
  1012. wuliuEntity.setAcceptStation(PrintTicketPropertiesBuilder.instance().getAddress() + "送达" +
  1013. storeDao.queryObject(orderEntity.getStoreId()).getStoreAddress() +
  1014. ";交易完成,用户已提走");
  1015. wuliuEntityList.add(wuliuEntity);
  1016. }
  1017. if (StringUtils.isNotEmpty(orderEntity.getShippingCode()) &&
  1018. StringUtils.isNotEmpty(orderEntity.getShippingNo()) &&
  1019. orderProcessRecordEntity.getShipmentStartTime() != null) {
  1020. if (orderEntity.getShippingCode().equalsIgnoreCase("SF")) {
  1021. StoreEntity storeEntity = storeDao.queryObject(orderEntity.getStoreId());
  1022. if (storeEntity == null) {
  1023. throw new RRException("查询顺丰订单异常,订单的门店信息不存在");
  1024. }
  1025. ThirdMerchExpressEntity thirdMerchExpressEntity = thirdMerchExpressDao.getThirdMerchExpressByThirdCode(storeEntity.getThirdPartyMerchCode());
  1026. if (thirdMerchExpressEntity == null) {
  1027. throw new RRException("查询顺丰订单异常,缺失商户快递账号信息");
  1028. }
  1029. SfRouteServiceResponseEntity entity = SFUtil.routeService(orderEntity.getShippingNo(), thirdMerchExpressEntity.getExpressAccount(),
  1030. thirdMerchExpressEntity.getExpressPwd(), SFPropertiesBuilder.instance().getUrl());
  1031. // SfRouteServiceResponseEntity entity = SFUtil.routeService("254355029325", thirdMerchExpressEntity.getExpressAccount(),
  1032. // thirdMerchExpressEntity.getExpressPwd(), SFPropertiesBuilder.instance().getUrl());//444072971585
  1033. if (entity.getHead().equalsIgnoreCase("OK")) {
  1034. if (entity.getBody() == null) {
  1035. WuliuEntity wuliuEntity = new WuliuEntity();
  1036. wuliuEntity.setAcceptStation("暂无物流轨迹");
  1037. wuliuEntityList.add(wuliuEntity);
  1038. } else {
  1039. if (entity.getBody().getRouteResponse() == null) {
  1040. WuliuEntity wuliuEntity = new WuliuEntity();
  1041. wuliuEntity.setAcceptStation("暂无物流轨迹");
  1042. wuliuEntityList.add(wuliuEntity);
  1043. } else {
  1044. RouteResponseEntity routeResponseEntity = entity.getBody().getRouteResponse().get(0);
  1045. if (routeResponseEntity != null) {
  1046. List<RouteEntity> entityList = routeResponseEntity.getRouteResponse();
  1047. for (RouteEntity route : entityList) {
  1048. WuliuEntity wuliuEntity = new WuliuEntity();
  1049. wuliuEntity.setAcceptTime(route.getAccept_time());
  1050. wuliuEntity.setAcceptStation(route.getAccept_address() + route.getRemark());
  1051. wuliuEntityList.add(wuliuEntity);
  1052. }
  1053. }
  1054. }
  1055. }
  1056. } else {
  1057. throw new RRException("查询顺丰订单异常," + entity.getErrors());
  1058. }
  1059. } else {
  1060. JSONObject traces =
  1061. KdniaoUtil.getOrderTracesByJson(orderEntity.getShippingCode(), orderEntity.getShippingNo());
  1062. List<Map> mapList = (List<Map>) traces.get("Traces");
  1063. if (mapList != null && mapList.size() > 0) {
  1064. for (Map map : mapList) {
  1065. WuliuEntity wuliuEntity = new WuliuEntity();
  1066. wuliuEntity.setAcceptTime(map.get("AcceptTime").toString());
  1067. wuliuEntity.setAcceptStation(map.get("AcceptStation").toString());
  1068. wuliuEntityList.add(wuliuEntity);
  1069. }
  1070. }
  1071. String state = traces.get("State") + "";
  1072. if (Dict.logisticsStatus.item_0.getItem().equals(state) && traces.getBoolean("Success")) {
  1073. String reason = traces.get("Reason") + "";
  1074. WuliuEntity wuliuEntity = new WuliuEntity();
  1075. wuliuEntity.setAcceptStation(reason);
  1076. wuliuEntityList.add(wuliuEntity);
  1077. }
  1078. }
  1079. }
  1080. if (Dict.isSend.item_1.getItem().equalsIgnoreCase(orderProcessRecordEntity.getIsCustomsSend()) &&
  1081. orderProcessRecordEntity.getShipmentStartTime() != null) {
  1082. WuliuEntity wuliuEntity = new WuliuEntity();
  1083. wuliuEntity.setAcceptStation("订单已出库");
  1084. wuliuEntity.setAcceptTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
  1085. .format(orderProcessRecordEntity.getShipmentStartTime()));
  1086. wuliuEntityList.add(wuliuEntity);
  1087. }
  1088. if (Dict.isSend.item_1.getItem().equals(orderProcessRecordEntity.getIsCustomsSend())) {
  1089. WuliuEntity wuliuEntity = new WuliuEntity();
  1090. wuliuEntity.setAcceptStation("订单清关完成,等待仓库发货");
  1091. wuliuEntity.setAcceptTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
  1092. .format(orderProcessRecordEntity.getCustomsSuccTime()));
  1093. wuliuEntityList.add(wuliuEntity);
  1094. }
  1095. if (Dict.isSend.item_0.getItem().equalsIgnoreCase(orderProcessRecordEntity.getIsCustomsSend())) {
  1096. WuliuEntity wuliuEntity = new WuliuEntity();
  1097. wuliuEntity.setAcceptStation("订单清关失败");
  1098. wuliuEntityList.add(wuliuEntity);
  1099. }
  1100. if (Dict.isSend.item_1.getItem().equalsIgnoreCase(orderProcessRecordEntity.getIsEleOrderSend()) &&
  1101. orderProcessRecordEntity.getWaybillSuccTime() != null) {
  1102. WuliuEntity wuliuEntity = new WuliuEntity();
  1103. wuliuEntity.setAcceptStation("海关三单发送成功");
  1104. wuliuEntity.setAcceptTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
  1105. .format(orderProcessRecordEntity.getWaybillSuccTime()));
  1106. wuliuEntityList.add(wuliuEntity);
  1107. }
  1108. if (Dict.isSend.item_1.getItem().equals(orderProcessRecordEntity.getIsPaymentSend())) {
  1109. WuliuEntity wuliuEntity = new WuliuEntity();
  1110. wuliuEntity.setAcceptStation("订单支付成功");
  1111. wuliuEntity.setAcceptTime(
  1112. new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(orderProcessRecordEntity.getPaySuccTime()));
  1113. wuliuEntityList.add(wuliuEntity);
  1114. }
  1115. if (Dict.isSend.item_1.getItem().equalsIgnoreCase(orderProcessRecordEntity.getIsAddOrderSend())) {
  1116. WuliuEntity wuliuEntity = new WuliuEntity();
  1117. wuliuEntity.setAcceptStation("订单下单成功");
  1118. wuliuEntity.setAcceptTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
  1119. .format(orderProcessRecordEntity.getAddOrderSuccTime()));
  1120. wuliuEntityList.add(wuliuEntity);
  1121. }
  1122. }
  1123. logisticsInfo.put("tracesList", wuliuEntityList);
  1124. logisticsInfo.put("logisticCode", orderEntity.getShippingNo());
  1125. logisticsInfo.put("shipperCode", orderEntity.getShippingCode());
  1126. return logisticsInfo;
  1127. }
  1128. @Override
  1129. public OrderEntity queryInfos(Long id) {
  1130. OrderEntity orderEntity = orderDao.queryObject(id);
  1131. Map<String, Object> map = new HashMap<String, Object>();
  1132. map.put("orderId", id);
  1133. List<OrderGoodsEntity> orderGoodsEntityList = orderGoodsDao.queryList(map);
  1134. orderEntity.setOrderGoodsEntityList(orderGoodsEntityList);
  1135. return orderEntity;
  1136. }
  1137. /**
  1138. * 普货商品生成线下订单
  1139. *
  1140. * @param offlineCartList
  1141. * @param user
  1142. * @return
  1143. */
  1144. @Transactional
  1145. @Override
  1146. public Map orderSubmit(List<OfflineCartEntity> offlineCartList, SysUserEntity user) {
  1147. Map resultObj = Maps.newHashMap();
  1148. try {
  1149. if (user == null) {
  1150. resultObj.put("errno", 400);
  1151. resultObj.put("errmsg", "用户登录超时,请重新登录");
  1152. return resultObj;
  1153. }
  1154. if (!user.getRoleType().equalsIgnoreCase("2")) {
  1155. resultObj.put("errno", 400);
  1156. resultObj.put("errmsg", "该操作只允许店员账户操作");
  1157. return resultObj;
  1158. }
  1159. if (org.apache.commons.lang3.StringUtils.isEmpty(user.getMerchSn())) {
  1160. resultObj.put("errno", 400);
  1161. resultObj.put("errmsg", "操作用户的商户编号为空,请先维护用户商户编号信息再来操作");
  1162. return resultObj;
  1163. }
  1164. Long userId = user.getUserId();
  1165. Integer storeId = user.getStoreId();
  1166. //获取要购买的商品
  1167. Map param = Maps.newHashMap();
  1168. param.put("userId", userId);
  1169. param.put("storeId", storeId);
  1170. if (null == offlineCartList && offlineCartList.size() == 0) {
  1171. resultObj.put("errno", 400);
  1172. resultObj.put("errmsg", "购买商品数据为空");
  1173. return resultObj;
  1174. }
  1175. List<OfflineCartEntity> offlineCartEntityList = offlineCartDao.queryOfflineCartByBizType(param);
  1176. if (offlineCartEntityList.size() == 0 && offlineCartList.size() > 0) {
  1177. resultObj.put("errno", 0);
  1178. resultObj.put("errmsg", "该单已下单成功,请重新扫描商品进行购买");
  1179. return resultObj;
  1180. }
  1181. // 检查库存和更新库存
  1182. for (OfflineCartEntity cartEntity : offlineCartEntityList) {
  1183. GoodsEntity goodsEntity = goodsDao.queryObject(cartEntity.getGoodsId());
  1184. if (goodsEntity == null) {
  1185. resultObj.put("errno", 400);
  1186. resultObj.put("errmsg", "订单提交失败:商品不存在");
  1187. return resultObj;
  1188. }
  1189. //取得规格的信息,判断规格库存
  1190. ProductStoreRelaEntity productInfo = productStoreRelaDao
  1191. .queryByGoodsIdAndStoreId(Long.valueOf(storeId), Long.valueOf(cartEntity.getGoodsId()));
  1192. synchronized (productInfo) {
  1193. if (null == productInfo || null == productInfo.getStockNum() ||
  1194. productInfo.getStockNum() < cartEntity.getNumber()) {
  1195. resultObj.put("errno", 400);
  1196. resultObj.put("errmsg", "库存不足,仅剩余" + productInfo.getStockNum());
  1197. return resultObj;
  1198. } else {
  1199. productInfo.setStockNum(productInfo.getStockNum() - cartEntity.getNumber());
  1200. productInfo.setStoreId(Long.valueOf(storeId));
  1201. productInfo.addSellVolume();
  1202. productStoreRelaDao.updateStockNum(productInfo);//修改普通商品库存
  1203. if (goodsEntity != null) {
  1204. goodsEntity.setGoodsNumber(goodsEntity.getGoodsNumber() - cartEntity.getNumber());
  1205. goodsDao.update(goodsEntity);
  1206. }
  1207. }
  1208. }
  1209. }
  1210. String merchOrderSn = "EMATO" + CommonUtil.generateOrderNumber();
  1211. OrderEntity order = setOrderVo(user, offlineCartEntityList, user.getMerchSn());
  1212. order.setStoreId(storeId);
  1213. order.setMerchOrderSn(merchOrderSn);
  1214. //开启事务,插入订单信息和订单商品
  1215. if (order != null) {
  1216. orderDao.save(order);
  1217. if (null == order.getId()) {
  1218. resultObj.put("errno", 400);
  1219. resultObj.put("errmsg", "订单提交失败");
  1220. return resultObj;
  1221. }
  1222. for (OfflineCartEntity cartEntity : offlineCartEntityList) {
  1223. OrderGoodsEntity orderGoodsEntity = setOrderGoodsVo(order, cartEntity);
  1224. //新增订单详情
  1225. orderGoodsDao.save(orderGoodsEntity);
  1226. }
  1227. //清空预订单商品临时表
  1228. offlineCartDao.deleteByUserId(userId);
  1229. Map orderInfoMap = Maps.newHashMap();
  1230. orderInfoMap.put("orderInfo", order);
  1231. resultObj.put("errno", 0);
  1232. resultObj.put("errmsg", "订单提交成功");
  1233. resultObj.put("data", orderInfoMap);
  1234. }
  1235. } catch (Exception e) {
  1236. e.printStackTrace();
  1237. resultObj.put("errno", 400);
  1238. resultObj.put("errmsg", "订单异常");
  1239. return resultObj;
  1240. }
  1241. return resultObj;
  1242. }
  1243. /**
  1244. * 设置订单数据
  1245. *
  1246. * @param loginUser
  1247. * @return
  1248. */
  1249. public OrderEntity setOrderVo(SysUserEntity loginUser, List<OfflineCartEntity> offlineCartEntityList,
  1250. String merchSn) {
  1251. OrderEntity orderInfo = new OrderEntity();
  1252. BigDecimal freightPrice = new BigDecimal(0.00);
  1253. BigDecimal goodsTotalPrice = new BigDecimal(0.00);
  1254. for (OfflineCartEntity offlineCartEntity : offlineCartEntityList) {
  1255. goodsTotalPrice = goodsTotalPrice
  1256. .add(offlineCartEntity.getRetailPrice().multiply(new BigDecimal(offlineCartEntity.getNumber())));
  1257. }
  1258. //订单价格计算:订单的总价+运费
  1259. BigDecimal orderTotalPrice = goodsTotalPrice.add(freightPrice);
  1260. //查询未使用的优惠券
  1261. /*String couponName = "";
  1262. BigDecimal fullCutCouponDec = Constant.ZERO;
  1263. UserCouponVo couponVo = null;*/
  1264. BigDecimal couponPrice = new BigDecimal(0.00);
  1265. //减去其它支付的金额后,要实际支付的金额 订单的总价+运费-优惠券金额
  1266. BigDecimal actualPrice = orderTotalPrice.subtract(couponPrice);
  1267. //商户(拼音首字母)+业务类型+编号
  1268. // String merchSn = OmsMerchPropertiesBuilder.instance().getMerchSn();
  1269. // String merchShortName = OmsMerchPropertiesBuilder.instance().getMerchShortName();
  1270. MerchEntity merchEntity = merchDao.findByMerchSn(merchSn);
  1271. String merchShortName = "";
  1272. if (merchEntity != null) {
  1273. merchShortName = merchEntity.getMerchShortName();
  1274. }
  1275. String orderSn = merchShortName + Dict.orderBizType.item_11.getItem() + CommonUtil.generateOrderNumber();
  1276. orderInfo.setOrderSn(orderSn);
  1277. orderInfo.setMerchSn(merchSn);
  1278. orderInfo.setUserId(Integer.parseInt(loginUser.getUserId() + ""));
  1279. orderInfo.setFreightPrice(freightPrice.intValue());
  1280. orderInfo.setOrderBizType(Dict.orderBizType.item_11.getItem());
  1281. /*orderInfo.setCoupon_id(userCouponId);
  1282. orderInfo.setCoupon_name(couponName);*/
  1283. // orderInfo.setFullCutPrice(fullCutCouponDec);//使用的优惠券
  1284. orderInfo.setCouponPrice(couponPrice);
  1285. orderInfo.setPostscript("");//留言
  1286. orderInfo.setAddTime(new Date());
  1287. orderInfo.setGoodsPrice(goodsTotalPrice);
  1288. orderInfo.setOrderPrice(orderTotalPrice);
  1289. orderInfo.setActualPrice(actualPrice);
  1290. orderInfo.setOrderType("1");
  1291. orderInfo.setOrderStatus(0);// 待付款
  1292. orderInfo.setShippingStatus(0);
  1293. orderInfo.setPayStatus(0);
  1294. orderInfo.setShippingId(0L);
  1295. orderInfo.setShippingFee(Constant.ZERO);
  1296. orderInfo.setIntegral(0);
  1297. orderInfo.setIntegralMoney(Constant.ZERO);
  1298. orderInfo.setCreateTime(new Date());
  1299. orderInfo.setModTime(new Date());
  1300. orderInfo.setIsOnfflineOrder(Dict.isOnfflineOrder.item_1.getItem());//线下购买
  1301. /*//标记该订单已使用优惠券
  1302. if(couponVo != null){
  1303. couponVo.setUsed_time(new Date());
  1304. couponVo.setIsUsed(Dict.isUsed.item_1.getItem());
  1305. apiUserCouponMapper.update(couponVo);
  1306. }*/
  1307. return orderInfo;
  1308. }
  1309. /**
  1310. * 设置订单数据
  1311. *
  1312. * @param
  1313. * @return
  1314. */
  1315. public OrderEntity setOrder(Integer userId, List<LinkedHashMap> goodsList,
  1316. String merchSn) {
  1317. OrderEntity orderInfo = new OrderEntity();
  1318. BigDecimal freightPrice = new BigDecimal(0.00);
  1319. BigDecimal goodsTotalPrice = new BigDecimal(0.00);
  1320. for (LinkedHashMap goods : goodsList) {
  1321. goodsTotalPrice = goodsTotalPrice
  1322. .add(new BigDecimal(goods.get("retailPrice").toString()).multiply(new BigDecimal(goods.get("sellVolume").toString())));
  1323. }
  1324. //订单价格计算:订单的总价+运费
  1325. BigDecimal orderTotalPrice = goodsTotalPrice.add(freightPrice);
  1326. //查询未使用的优惠券
  1327. /*String couponName = "";
  1328. BigDecimal fullCutCouponDec = Constant.ZERO;
  1329. UserCouponVo couponVo = null;*/
  1330. BigDecimal couponPrice = new BigDecimal(0.00);
  1331. //减去其它支付的金额后,要实际支付的金额 订单的总价+运费-优惠券金额
  1332. BigDecimal actualPrice = orderTotalPrice.subtract(couponPrice);
  1333. //商户(拼音首字母)+业务类型+编号
  1334. // String merchSn = OmsMerchPropertiesBuilder.instance().getMerchSn();
  1335. // String merchShortName = OmsMerchPropertiesBuilder.instance().getMerchShortName();
  1336. MerchEntity merchEntity = merchDao.findByMerchSn(merchSn);
  1337. String merchShortName = "";
  1338. if (merchEntity != null) {
  1339. merchShortName = merchEntity.getMerchShortName();
  1340. }
  1341. String orderSn = merchShortName + Dict.orderBizType.item_10.getItem() + CommonUtil.generateOrderNumber();
  1342. orderInfo.setOrderSn(orderSn);
  1343. orderInfo.setMerchSn(merchSn);
  1344. orderInfo.setUserId(userId);
  1345. orderInfo.setFreightPrice(freightPrice.intValue());
  1346. orderInfo.setOrderBizType(Dict.orderBizType.item_10.getItem());
  1347. /*orderInfo.setCoupon_id(userCouponId);
  1348. orderInfo.setCoupon_name(couponName);*/
  1349. // orderInfo.setFullCutPrice(fullCutCouponDec);//使用的优惠券
  1350. orderInfo.setCouponPrice(couponPrice);
  1351. orderInfo.setPostscript("");//留言
  1352. orderInfo.setAddTime(new Date());
  1353. orderInfo.setGoodsPrice(goodsTotalPrice);
  1354. orderInfo.setOrderPrice(orderTotalPrice);
  1355. orderInfo.setActualPrice(actualPrice);
  1356. orderInfo.setOrderType("1");
  1357. orderInfo.setOrderStatus(0);// 待付款
  1358. orderInfo.setShippingStatus(0);
  1359. orderInfo.setPayStatus(0);
  1360. orderInfo.setShippingId(0L);
  1361. orderInfo.setShippingFee(Constant.ZERO);
  1362. orderInfo.setIntegral(0);
  1363. orderInfo.setIntegralMoney(Constant.ZERO);
  1364. orderInfo.setCreateTime(new Date());
  1365. orderInfo.setModTime(new Date());
  1366. orderInfo.setIsOnfflineOrder(Dict.isOnfflineOrder.item_1.getItem());//线下购买
  1367. // orderInfo.setIsScan("0");//默认未扫描
  1368. /*//标记该订单已使用优惠券
  1369. if(couponVo != null){
  1370. couponVo.setUsed_time(new Date());
  1371. couponVo.setIsUsed(Dict.isUsed.item_1.getItem());
  1372. apiUserCouponMapper.update(couponVo);
  1373. }*/
  1374. return orderInfo;
  1375. }
  1376. public OrderGoodsEntity setOrderGoodsVo(OrderEntity orderInfo, OfflineCartEntity goodsItem) {
  1377. GoodsEntity goodsVo = goodsDao.queryObject(goodsItem.getGoodsId());
  1378. OrderGoodsEntity orderGoodsVo = new OrderGoodsEntity();
  1379. orderGoodsVo.setOrderId(Integer.parseInt(orderInfo.getId() + ""));
  1380. orderGoodsVo.setGoodsId(goodsItem.getGoodsId());
  1381. orderGoodsVo.setGoodsSn(goodsItem.getGoodsSn());
  1382. orderGoodsVo.setProductId(goodsItem.getProductId());
  1383. orderGoodsVo.setGoodsName(goodsItem.getGoodsName());
  1384. orderGoodsVo.setListPicUrl(goodsItem.getListPicUrl());
  1385. orderGoodsVo.setMarketPrice(goodsItem.getMarketPrice());
  1386. orderGoodsVo.setRetailPrice(goodsItem.getRetailPrice());
  1387. orderGoodsVo.setNumber(goodsItem.getNumber());
  1388. orderGoodsVo.setOrderBizType(Dict.orderBizType.item_11.getItem());
  1389. orderGoodsVo.setCreateTime(new Date());
  1390. orderGoodsVo.setModTime(new Date());
  1391. orderGoodsVo.setGoodsRate(goodsVo.getGoodsRate());
  1392. orderGoodsVo.setSku(goodsVo.getSku());
  1393. return orderGoodsVo;
  1394. }
  1395. // public OrderGoodsEntity setOrderGoods(OrderEntity orderInfo, LinkedHashMap goods) {
  1396. // GoodsEntity goodsVo = goodsDao.queryObject(goods.get("goodsId"));
  1397. // ProductEntity productEntity = productDao.queryObjectByGoodsIdAndStoreId(goodsVo.getId() + "", null);
  1398. // OrderGoodsEntity orderGoodsVo = new OrderGoodsEntity();
  1399. // orderGoodsVo.setOrderId(Integer.parseInt(orderInfo.getId() + ""));
  1400. // orderGoodsVo.setGoodsId(goodsVo.getId().intValue());
  1401. // orderGoodsVo.setGoodsSn(goodsVo.getGoodsSn());
  1402. // orderGoodsVo.setProductId(productEntity.getId().intValue());
  1403. // orderGoodsVo.setGoodsName(goodsVo.getName());
  1404. // orderGoodsVo.setListPicUrl(goodsVo.getListPicUrl());
  1405. //
  1406. //
  1407. // orderGoodsVo.setMarketPrice((BigDecimal) goods.get("storeMarketPrice"));
  1408. // orderGoodsVo.setRetailPrice((BigDecimal) goods.get("storeRetailPrice"));
  1409. // orderGoodsVo.setNumber((Integer) goods.get("sellVolume"));
  1410. // orderGoodsVo.setOrderBizType(Dict.orderBizType.item_10.getItem());
  1411. // orderGoodsVo.setCreateTime(new Date());
  1412. // orderGoodsVo.setModTime(new Date());
  1413. // orderGoodsVo.setGoodsRate(goodsVo.getGoodsRate());
  1414. // orderGoodsVo.setSku(goodsVo.getSku());
  1415. //
  1416. //
  1417. // BigDecimal number = new BigDecimal(Long.valueOf(goodsItem.getNumber()));
  1418. // BigDecimal goodsTotal = goodsItem.getRetail_price().multiply(number);//单商品总价
  1419. // BigDecimal rate = goodsTotal.divide(orderInfo.getGoods_price(),2, BigDecimal.ROUND_HALF_UP);//当前商品总价/订单总价(不含运费、不含优惠券)
  1420. // BigDecimal freightPrice = BigDecimal.valueOf(orderInfo.getFreight_price());
  1421. // BigDecimal settlePrice = Constant.ZERO;
  1422. // if(orderInfo.getFreight_price() != 0 && !"0".equalsIgnoreCase(orderInfo.getCoupon_price()+"")){
  1423. // //运费-优惠券
  1424. // BigDecimal rateTotal = freightPrice.subtract(orderInfo.getCoupon_price());
  1425. // //商品结算平摊价格(含优惠券、运费金额) = 单商品总价 + 当前商品总价/订单总价(不含运费、不含优惠券) * 运费与优惠券合计税率
  1426. // settlePrice = goodsTotal.add(rate.multiply(rateTotal));
  1427. // }else{
  1428. // if(orderInfo.getFreight_price()!=0){
  1429. // //运费税率 = 单商品总价/订单总价(不含运费)* 运费金额
  1430. // BigDecimal freightRate = rate.multiply(freightPrice);
  1431. // //商品结算平摊价格(含运费金额) = 单商品总价+运费税率
  1432. // settlePrice = goodsTotal.add(freightRate);
  1433. // }
  1434. // if(!"0".equalsIgnoreCase(orderInfo.getCoupon_price()+"")){
  1435. // //优惠券税率 = 单商品总价/订单总价(不含优惠券)* 优惠券金额
  1436. // BigDecimal couponRate = rate.multiply(orderInfo.getCoupon_price());
  1437. // //商品结算平摊价格(含优惠券金额) = 单商品总价-优惠券税率
  1438. // settlePrice = goodsTotal.subtract(couponRate);
  1439. // }
  1440. // }
  1441. // if(settlePrice.compareTo(BigDecimal.valueOf(0)) == 0){
  1442. // orderGoodsVo.setSettlePrice(goodsTotal);//商品结算平摊价格
  1443. // }else{
  1444. // orderGoodsVo.setSettlePrice(settlePrice);//商品结算平摊价格
  1445. // }
  1446. //
  1447. // return orderGoodsVo;
  1448. // }
  1449. @Override
  1450. public OrderEntity queryObjectBySysUser(Long id) {
  1451. OrderEntity orderEntity = orderDao.queryObjectBySysUser(id);
  1452. Map<String, Object> map = new HashMap<String, Object>();
  1453. map.put("orderId", id);
  1454. List<OrderGoodsEntity> orderGoodsEntityList = orderGoodsDao.queryList(map);
  1455. orderEntity.setOrderGoodsEntityList(orderGoodsEntityList);
  1456. return orderEntity;
  1457. }
  1458. @Override
  1459. public int confirmPay(Long id, String payFlag, String orderSnWx) {
  1460. SysUserEntity user = ShiroUtils.getUserEntity();
  1461. if (user == null) {
  1462. throw new RRException("用户登录超时,请重新登录");
  1463. }
  1464. if (!user.getRoleType().equalsIgnoreCase("2")) {
  1465. throw new RRException("该操作只允许店员账户操作");
  1466. }
  1467. OrderEntity orderEntity = queryObject(id);
  1468. if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())) {
  1469. throw new RRException("此订单已付款!");
  1470. }
  1471. if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_301.getItem())) {
  1472. throw new RRException("此订单已完成!");
  1473. }
  1474. if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_101.getItem())) {
  1475. throw new RRException("此订单已取消!");
  1476. }
  1477. if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_102.getItem())) {
  1478. throw new RRException("此订单已删除!");
  1479. }
  1480. orderEntity.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_201.getItem()));
  1481. orderEntity.setPayStatus(Integer.parseInt(Dict.payStatus.item_2.getItem()));
  1482. orderEntity.setPayFlag(payFlag);
  1483. orderEntity.setPayTime(new Date());
  1484. if (Dict.payFlag.item_alipay.getItem().equalsIgnoreCase(payFlag)) {
  1485. orderEntity.setAliTradeNo(orderSnWx);
  1486. } else {
  1487. if (orderSnWx != null) {
  1488. orderEntity.setOrderSnWx(orderSnWx);
  1489. }
  1490. }
  1491. // Date now = new Date();
  1492. // Integer storeId = orderEntity.getStoreId();
  1493. // Map queryParams = new HashMap();
  1494. // queryParams.put("orderId", orderEntity.getId());
  1495. // List<OrderGoodsEntity> orderGoodsList = orderGoodsDao.queryList(queryParams);
  1496. // // 遍历订单下的详情商品,修改商品的最后销售时间
  1497. // if (orderGoodsList!=null && orderGoodsList.size()>0){
  1498. // orderGoodsList.forEach(orderGoods ->{
  1499. // Integer goodsId = orderGoods.getGoodsId();
  1500. // GoodsEntity goodsEntity = goodsDao.queryObject(goodsId);
  1501. // if (Objects.nonNull(goodsEntity)){
  1502. // goodsEntity.setLastSaleTime(now);
  1503. // goodsDao.update(goodsEntity);
  1504. // }
  1505. // if (Objects.nonNull(storeId)){
  1506. // ProductStoreRelaEntity productStoreRelaEntity = productStoreRelaDao.queryByGoodsIdAndStoreId(Long.valueOf(storeId), Long.valueOf(goodsId));
  1507. // if (Objects.nonNull(productStoreRelaEntity)){
  1508. // productStoreRelaEntity.setLastSaleTime(now);
  1509. // productStoreRelaDao.update(productStoreRelaEntity);
  1510. // }
  1511. // }
  1512. // });
  1513. // }
  1514. orderDao.update(orderEntity);
  1515. return 0;
  1516. }
  1517. @Override
  1518. public List<OrderEntity> queryExportList(Map<String, Object> map) {
  1519. List<OrderEntity> list = orderDao.queryExportList(map);
  1520. for (OrderEntity order : list) {
  1521. OrderProcessRecordEntity orderProcessRecord = orderProcessRecordDao.queryObjectByOrderSn(order.getOrderSn());
  1522. order.setOrderProcessRecord(orderProcessRecord);
  1523. // 查询活动价
  1524. BigDecimal topicPrice = orderDao.queryTopicPriceByOrderSnAndSku(order.getOrderSn(), order.getSku());
  1525. order.setTopicPrice(topicPrice);
  1526. }
  1527. return list;
  1528. }
  1529. @Override
  1530. public List<OrderEntity> queryOffilineOrderList(Map<String, Object> map) {
  1531. return orderDao.queryOffilineOrderList(map);
  1532. }
  1533. /**
  1534. * 还原查验单库存方法
  1535. *
  1536. * @param orderSns 查验单订单编号
  1537. * @return 是否还原成功, true: 成功,false: 失败
  1538. */
  1539. @Override
  1540. @Transactional(rollbackFor = Exception.class)
  1541. public Boolean restore(String orderSns) {
  1542. if (org.springframework.util.StringUtils.isEmpty(orderSns)) {
  1543. LOGGER.error("还原查验单库存,订单编号为空!");
  1544. return false;
  1545. }
  1546. List<String> orderIdStrList = new ArrayList<>();
  1547. if (orderSns.contains(",")) {
  1548. String[] split = orderSns.split(",");
  1549. orderIdStrList.addAll(Arrays.asList(split));
  1550. } else {
  1551. orderIdStrList.add(orderSns);
  1552. }
  1553. List<Integer> orderIdList = orderIdStrList.parallelStream().map(Integer::valueOf).collect(Collectors.toList());
  1554. // 查询订单详细信息
  1555. List<OrderGoodsRestoreVo> orderGoodsRestoreVos = orderGoodsService.queryListByOrderIds(orderIdList);
  1556. List<String> orderSnList = orderGoodsRestoreVos.stream().map(OrderGoodsRestoreVo::getOrderSn).collect(Collectors.toList());
  1557. // 查询记录表, 不能还原多次
  1558. List<String> snList = newRetailOrderRestoreStockRecordService.queryListByOrderSnList(orderSnList);
  1559. // 不为空则说明有订单已经被还原过, 返回失败
  1560. if (!CollectionUtils.isEmpty(snList)) {
  1561. LOGGER.error(String.format("订单【%s】已经还原过库存,不可继续还原!", snList));
  1562. throw new RRException(String.format("订单【%s】已经还原过库存,不可继续还原!", snList));
  1563. }
  1564. // 需要更新门店商品库存(mall_product_store_rela)和园区库存(mall_goods)
  1565. // 园区库存, 无门店概念
  1566. List<GoodsEntity> goodsEntities = new ArrayList<>();
  1567. // 门店商品库存
  1568. List<ProductStoreRelaEntity> productStoreRelaEntities = new ArrayList<>();
  1569. // 组装数据
  1570. orderGoodsRestoreVos.forEach(orderGoodsRestoreVo -> {
  1571. goodsEntities.add(wrapGoods(orderGoodsRestoreVo));
  1572. productStoreRelaEntities.add(wrapProductStoreRela(orderGoodsRestoreVo));
  1573. });
  1574. // 还原园区库存
  1575. goodsService.restoreBatch(goodsEntities);
  1576. // 还原门店库存
  1577. productStoreRelaService.restoreBatch(productStoreRelaEntities);
  1578. LOGGER.info("还原【{}】查验订单库存成功!", orderSnList);
  1579. // 查验完成的单已经转成保税备货,800放行后不会通知到kmall,所以需要将状态修改为已发货
  1580. orderDao.updateOrderStatusByOrderSnList(orderSnList);
  1581. LOGGER.info("更新【{}】查验订单状态为已发货成功!", orderSnList);
  1582. // 添加还原记录
  1583. List<NewRetailOrderRestoreStockRecordEntity> stockRecordEntityList = orderGoodsRestoreVos.stream().map(this::wrapRestoreRecord).collect(Collectors.toList());
  1584. newRetailOrderRestoreStockRecordService.saveBatch(stockRecordEntityList);
  1585. LOGGER.info("新增【{}】查验订单还原记录成功!", orderSnList);
  1586. return true;
  1587. }
  1588. /**
  1589. * 组装查验单库存还原记录实体
  1590. * @param orderGoodsRestoreVo 实体
  1591. * @return 查验单库存还原记录
  1592. */
  1593. private NewRetailOrderRestoreStockRecordEntity wrapRestoreRecord(OrderGoodsRestoreVo orderGoodsRestoreVo){
  1594. NewRetailOrderRestoreStockRecordEntity entity = new NewRetailOrderRestoreStockRecordEntity();
  1595. SysUserEntity user = ShiroUtils.getUserEntity();
  1596. entity.setOrderId(orderGoodsRestoreVo.getOrderId());
  1597. entity.setOrderSn(orderGoodsRestoreVo.getOrderSn());
  1598. entity.setRestoreNum(orderGoodsRestoreVo.getNumber());
  1599. entity.setStoreId(orderGoodsRestoreVo.getStoreId());
  1600. entity.setShopName(orderGoodsRestoreVo.getShopName());
  1601. entity.setSku(orderGoodsRestoreVo.getSku());
  1602. entity.setCreateSn(String.valueOf(user.getUserId()));
  1603. entity.setCreateTime(new Date());
  1604. entity.setUpdateSn(String.valueOf(user.getUserId()));
  1605. entity.setUpdateTime(new Date());
  1606. entity.setStatus(Dict.stockRestoreEnum.SUCCESS.getCode());
  1607. return entity;
  1608. }
  1609. /**
  1610. * 组装成ProductStoreRelaEntity, 还原操作
  1611. * @param orderGoodsRestoreVo 订单详细数据
  1612. * @return 门店库存
  1613. */
  1614. private ProductStoreRelaEntity wrapProductStoreRela(OrderGoodsRestoreVo orderGoodsRestoreVo) {
  1615. ProductStoreRelaEntity productStoreRelaEntity = new ProductStoreRelaEntity();
  1616. productStoreRelaEntity.setStoreId(orderGoodsRestoreVo.getStoreId().longValue());
  1617. productStoreRelaEntity.setSku(orderGoodsRestoreVo.getSku());
  1618. productStoreRelaEntity.setStockNum(orderGoodsRestoreVo.getNumber());
  1619. return productStoreRelaEntity;
  1620. }
  1621. /**
  1622. * 组装成GoodsEntity, 还原操作
  1623. * @param orderGoodsRestoreVo 订单详细数据
  1624. * @return 库存
  1625. */
  1626. private GoodsEntity wrapGoods(OrderGoodsRestoreVo orderGoodsRestoreVo) {
  1627. GoodsEntity goodsEntity = new GoodsEntity();
  1628. goodsEntity.setGoodsNumber(orderGoodsRestoreVo.getNumber());
  1629. goodsEntity.setSku(orderGoodsRestoreVo.getSku());
  1630. return goodsEntity;
  1631. }
  1632. @Override
  1633. public List<OrderEntity> queryPickUpCodeList(Map<String, Object> map) {
  1634. return orderDao.queryPickUpCodeList(map);
  1635. }
  1636. @Override
  1637. public int uploadExcel(List<OrderExpressDto> orderExpressDtoList) {
  1638. SysUserEntity user = ShiroUtils.getUserEntity();
  1639. boolean isFail = false;
  1640. List<String> failShippingNameList = new ArrayList<>();
  1641. List<String> failOrderSnList = new ArrayList<>();
  1642. List<String> failShippingCodeList = new ArrayList<>();
  1643. List<String> failCodeSnList = new ArrayList<>();
  1644. List<String> failNameSnList = new ArrayList<>();
  1645. List<String> failStatusOrderSnList = new ArrayList<>();
  1646. if (orderExpressDtoList != null && orderExpressDtoList.size() > 0) {
  1647. for (int i = 0; i < orderExpressDtoList.size(); i++) {
  1648. OrderExpressDto orderExpressDto = orderExpressDtoList.get(i);
  1649. OrderEntity orderEntity = new OrderEntity();
  1650. Map<String, Object> valideDate = MapBeanUtil.fromObject(orderExpressDto);
  1651. ImmutableBiMap.Builder builder = new ImmutableBiMap.Builder();
  1652. builder.put("orderSn", "订单编号");
  1653. builder.put("shippingNo", "快递单号");
  1654. builder.put("shippingName", "快递公司");
  1655. builder.put("shippingCode", "快递简写");
  1656. R r = ValidatorUtil.isEmpty(builder.build(), valideDate);
  1657. if (Integer.valueOf(r.get("code").toString()) != 0) {
  1658. throw new RRException(r.get("msg").toString());
  1659. } else {
  1660. r = ValidatorUtil.isEmpty(builder.build(), valideDate);
  1661. if (Integer.valueOf(r.get("code").toString()) != 0) {
  1662. throw new RRException(r.get("msg").toString());
  1663. }
  1664. }
  1665. OrderEntity order = orderDao.queryObjectByOrderSn(orderExpressDto.getOrderSn());
  1666. if (order == null) {
  1667. isFail = true;
  1668. failOrderSnList.add(orderExpressDto.getOrderSn());
  1669. } else {
  1670. if (!(order.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())
  1671. && order.getPayStatus() == Integer.parseInt(Dict.payStatus.item_2.getItem()))) {
  1672. isFail = true;
  1673. failStatusOrderSnList.add(orderExpressDto.getOrderSn());
  1674. }
  1675. }
  1676. ShippingEntity shippingEntity = shippingDao.queryObjectByCode(orderExpressDto.getShippingCode());
  1677. if (shippingEntity == null) {
  1678. isFail = true;
  1679. failShippingCodeList.add(orderExpressDto.getShippingCode());
  1680. failCodeSnList.add(orderExpressDto.getOrderSn());
  1681. } else {
  1682. if (!orderExpressDto.getShippingName().equalsIgnoreCase(shippingEntity.getName())) {
  1683. isFail = true;
  1684. failShippingNameList.add(orderExpressDto.getShippingName());
  1685. failNameSnList.add(orderExpressDto.getOrderSn());
  1686. }
  1687. }
  1688. if (!isFail) {//false则有错误的数据
  1689. if (order != null) {// 修改商品
  1690. // orderEntity.setOrderSn(orderExpressDto.getOrderSn());
  1691. orderEntity.setShippingNo(orderExpressDto.getShippingNo());
  1692. orderEntity.setShippingCode(orderExpressDto.getShippingCode());
  1693. orderEntity.setShippingName(orderExpressDto.getShippingName());
  1694. orderEntity.setShippingStatus(Integer.parseInt(Dict.shippingStatus.item_1.getItem()));
  1695. orderEntity.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_300.getItem()));
  1696. orderEntity.setModerSn(user.getUsername());
  1697. orderEntity.setCreateTime(new Date());
  1698. orderEntity.setModTime(new Date());
  1699. orderEntity.setId(order.getId());
  1700. orderDao.update(orderEntity);
  1701. }
  1702. }
  1703. }
  1704. if (failOrderSnList != null && failOrderSnList.size() > 0) {
  1705. throw new RRException("导入数据异常,订单编号不存在,不存在的订单编号【" + failOrderSnList + "】,请删除掉再继续操作");
  1706. }
  1707. if (failStatusOrderSnList != null && failStatusOrderSnList.size() > 0) {
  1708. throw new RRException("导入数据异常,修改订单快递功能只支持已付款未发货的订单,以下订单编号无效【" + failStatusOrderSnList + "】,请删除掉再继续操作");
  1709. }
  1710. if (failShippingCodeList != null && failShippingCodeList.size() > 0) {
  1711. throw new RRException("导入数据异常,快递简写不在可支持的范围中,简写错误的订单编号【" + failCodeSnList + "】,错误的快递简写【" + failShippingCodeList + "】," +
  1712. "正确数据可下载订单页面的快递公司简写Excel中查看");
  1713. }
  1714. if (failShippingNameList != null && failShippingNameList.size() > 0) {
  1715. throw new RRException("导入数据异常,快递简写对应的快递公司不一致,快递公司错误的订单编号【" + failNameSnList + "】,请修改Excel数据中订单编号对应的快递公司错误信息," +
  1716. "正确数据可下载订单页面的快递公司简写Excel中查看");
  1717. }
  1718. // if(failFreightGoodsSnList != null && failFreightGoodsSnList.size() > 0){
  1719. // exportExceptionDataEntity.setExportExceptionData("运费信息请在商城配置》运费模板中维护,运费与商户信息对应,请检查该商品商户信息下的运费是否维护,不存在的商品编码【"+failFreightGoodsSnList+"】,运费【"+failFreightList+"】");
  1720. // exportExceptionDataDao.save(exportExceptionDataEntity);
  1721. // throw new RRException("导入数据异常,异常信息请在商品管理》》商品导入异常数据中查看检查");
  1722. // }
  1723. } else {
  1724. throw new RRException("导入数据为空,或者检查商品编码数据是否为空");
  1725. }
  1726. return 1;
  1727. }
  1728. @Override
  1729. public List<OrderEntity> promOrderList(Map<String, Object> map) {
  1730. Integer[] statusList = {201};
  1731. List<OrderEntity> list = orderDao.promOrderList(map);
  1732. for (OrderEntity orderEntity : list) {
  1733. Map<String, Object> queryMap = new HashMap<>();
  1734. queryMap.put("goodsId", orderEntity.getGoodsId());
  1735. queryMap.put("statusList", statusList);
  1736. queryMap.put("orderId", orderEntity.getId());
  1737. Double promActualPrice = orderDao.getActualPriceByOutProm(queryMap);
  1738. if (promActualPrice == null) {
  1739. promActualPrice = 0d;
  1740. }
  1741. orderEntity.setPromActualPrice(BigDecimal.valueOf(promActualPrice));
  1742. }
  1743. return list;
  1744. }
  1745. @Override
  1746. public int queryPromOrderTotal(Map<String, Object> map) {
  1747. return orderDao.queryPromOrderTotal(map);
  1748. }
  1749. @Override
  1750. public List<OrderEntity> promOrderListExport(Map<String, Object> map) {
  1751. Integer[] statusList = {201};
  1752. List<OrderEntity> list = orderDao.promOrderListExport(map);
  1753. for (OrderEntity orderEntity : list) {
  1754. Map<String, Object> queryMap = new HashMap<>();
  1755. queryMap.put("goodsId", orderEntity.getGoodsId());
  1756. queryMap.put("orderId", orderEntity.getId());
  1757. queryMap.put("statusList", statusList);
  1758. Double promActualPrice = orderDao.getActualPriceByOutProm(queryMap);
  1759. if (promActualPrice == null) {
  1760. promActualPrice = 0d;
  1761. }
  1762. orderEntity.setPromActualPrice(BigDecimal.valueOf(promActualPrice));
  1763. }
  1764. return list;
  1765. }
  1766. @Override
  1767. public List<OrderEntity> storeTopicOrderList(Map<String, Object> map) {
  1768. List<OrderEntity> list = orderDao.storeTopicOrderList(map);
  1769. return list;
  1770. }
  1771. @Override
  1772. public int queryStoreTopicOrderTotal(Map<String, Object> map) {
  1773. return orderDao.queryStoreTopicOrderTotal(map);
  1774. }
  1775. @Override
  1776. public List<WxOrderEntity> wxOrderResendQueryAllList(Map<String, Object> map) {
  1777. // String requestData = JacksonUtil.toJson(map);
  1778. String url = OmsMerchPropertiesBuilder.instance().getWxOrderResendUrl();
  1779. // 同步访问,返回结果字符串
  1780. String response = OkHttpUtils.post(map, url, "SSL");
  1781. ResponseData responseData = JacksonUtils.fromStringJson(response, ResponseData.class);
  1782. if (responseData.getCode().equalsIgnoreCase("0")) {
  1783. List<WxOrderEntity> list = responseData.getData().getRows();
  1784. return list;
  1785. }
  1786. return null;
  1787. }
  1788. @Override
  1789. public List<OrderRecognitionDto> queryOrderListByRecognition(Map<String, Object> map) {
  1790. String value = sysConfigDao.queryByKey("FACE_COLLECT_FREQUENCY_TIME");
  1791. if (value == null) {
  1792. throw new RRException("请联系管理员配系统参数置FACE_COLLECT_FREQUENCY_TIME信息!");
  1793. }
  1794. List<OrderRecognitionDto> list = orderDao.queryOrderListByRecognition(map);
  1795. for (OrderRecognitionDto orderRecognitionDto : list) {
  1796. Integer frequencySecondTime = Integer.parseInt(value);
  1797. String lastFaceTime = orderRecognitionDto.getLastFaceTime();
  1798. if (StringUtils.isNotEmpty(lastFaceTime)) {
  1799. Date lastFaceDate = DateUtils.convertStringToDate(lastFaceTime, DateUtils.DATE_TIME_PATTERN);
  1800. Calendar calendar = Calendar.getInstance();
  1801. calendar.setTime(lastFaceDate);
  1802. calendar.add(Calendar.SECOND, frequencySecondTime);
  1803. Date addSecondTime = calendar.getTime();
  1804. Date nowDate = new Date();
  1805. if (addSecondTime.getTime() > nowDate.getTime()) {
  1806. orderRecognitionDto.setAddSecondTime(DateUtils.format(addSecondTime, DateUtils.DATE_TIME_PATTERN));
  1807. orderRecognitionDto.setIsDateLast("false");
  1808. } else {
  1809. //可调用身份验证范围内
  1810. orderRecognitionDto.setIsDateLast("true");
  1811. }
  1812. } else {//可调用身份验证范围内
  1813. orderRecognitionDto.setIsDateLast("true");
  1814. }
  1815. }
  1816. return list;
  1817. }
  1818. @Override
  1819. public int queryOrderListByRecognitionTotal(Map<String, Object> map) {
  1820. return orderDao.queryOrderListByRecognitionTotal(map);
  1821. }
  1822. /**
  1823. * 海控,提交订单并付款
  1824. * @param param 收银端提交的参数
  1825. * @param user 当前收银端用户
  1826. * @return 结果
  1827. */
  1828. @Override
  1829. @Transactional
  1830. public synchronized Map offlineRetailSubmitHaiKong(Map param, SysUserEntity user) {
  1831. // 解析订单数据 List
  1832. List<LinkedHashMap> goodsList = (List<LinkedHashMap>) param.get("goodsList");
  1833. // 解析用户信息 LinkedHashMap
  1834. Map userInfo = (Map) param.get("userInfo");
  1835. // 解析支付码 String
  1836. String parCode = (String) param.get("payCode");
  1837. // 解析sessionId(WebSocket) String
  1838. String sessionId = (String) param.get("sessionId");
  1839. // machineCode
  1840. String machineCode = (String) param.get("machineCode");
  1841. //选择的方式 1柜取 0邮寄
  1842. int status = Integer.parseInt(param.get("status").toString());
  1843. // 会员码
  1844. String couponBarCode = param.get("couponBarCode").toString();
  1845. Map<String, String> mapAddr = new HashMap<>();
  1846. if (status == 0) {
  1847. //省
  1848. String cmbProvince = (String) param.get("cmbProvince");
  1849. //市
  1850. String cmbCity = (String) param.get("cmbCity");
  1851. //区
  1852. String cmbArea = (String) param.get("cmbArea");
  1853. //详细地址
  1854. String addrUser = (String) param.get("addrUser");
  1855. mapAddr.put("cmbProvince", cmbProvince);
  1856. mapAddr.put("cmbCity", cmbCity);
  1857. mapAddr.put("cmbArea", cmbArea);
  1858. mapAddr.put("addrUser", addrUser);
  1859. }
  1860. try {
  1861. machineCode = URLDecoder.decode(machineCode, "UTF-8");
  1862. } catch (Exception e) {
  1863. LOGGER.error("机器码:", e);
  1864. }
  1865. Map resultObj = Maps.newHashMap();
  1866. if (user == null) {
  1867. resultObj.put("errno", 400);
  1868. resultObj.put("errmsg", "用户登录超时,请重新登录");
  1869. return resultObj;
  1870. }
  1871. if (!user.getRoleType().equalsIgnoreCase("2")) {
  1872. resultObj.put("errno", 400);
  1873. resultObj.put("errmsg", "该操作只允许店员账户操作");
  1874. return resultObj;
  1875. }
  1876. if (org.apache.commons.lang3.StringUtils.isEmpty(user.getMerchSn())) {
  1877. resultObj.put("errno", 400);
  1878. resultObj.put("errmsg", "操作用户的商户编号为空,请先维护用户商户编号信息再来操作");
  1879. return resultObj;
  1880. }
  1881. Long userId = user.getUserId();
  1882. Integer storeId = user.getStoreId();
  1883. // TODO 海控需求,下单流程修改,收银端接收会员码,付款码,用户信息,订单数据
  1884. // 1. 校验库存:保税仓库存 + 展销店库存 - 出区数 >= 购买数
  1885. // 获取保税仓库存
  1886. String queryWarehouseStockResponse = haiKongWarehouseTemplate.queryWarehouseStock(null);
  1887. if (org.springframework.util.StringUtils.isEmpty(queryWarehouseStockResponse)) {
  1888. LOGGER.error("调用库存系统接口出现错误!返回结果为空!");
  1889. throw new ServiceException("调用库存系统接口出现错误!");
  1890. }
  1891. WareQueryStockResponseDTO wareQueryStockResponseDTO = JacksonUtil.fromStringJson(queryWarehouseStockResponse, WareQueryStockResponseDTO.class);
  1892. if (Objects.isNull(wareQueryStockResponseDTO)) {
  1893. throw new ServiceException("解析一步达库存系统响应数据出现错误!");
  1894. }
  1895. List<WareQueryStockResponseDTO.WareQueryStockResponseItemDTO> items = wareQueryStockResponseDTO.getItems();
  1896. // 解析xml,组装成map key=>sku value=>库存
  1897. Map<String, Integer> stockMap = new HashMap<>(16);
  1898. items.forEach(item -> {
  1899. String itemCode = item.getItemCode();
  1900. Integer quantity = item.getQuantity();
  1901. if (stockMap.containsKey(itemCode)) {
  1902. // 避免出现sku相同情况
  1903. stockMap.put(itemCode, stockMap.get(itemCode) + quantity);
  1904. } else {
  1905. stockMap.put(itemCode, quantity);
  1906. }
  1907. });
  1908. // 订单总价格(含税价)
  1909. BigDecimal orderPrice = BigDecimal.ZERO;
  1910. // 商品总价格(不含税)
  1911. BigDecimal goodsPrice = BigDecimal.ZERO;
  1912. // 订单所占用的税
  1913. BigDecimal totalTax = BigDecimal.ZERO;
  1914. List<OrderGoodsEntity> orderGoodsEntities = new ArrayList<>();
  1915. List<GoodsEntity> goodsEntities = new ArrayList<>();
  1916. // TODO 根据商品条码、sku、门店id查询相对应的商品信息,并组装成对象
  1917. List<QueryGoodsVo> queryGoodsVoList = new ArrayList<>();
  1918. goodsList.forEach(map -> {
  1919. QueryGoodsVo queryGoodsVo = new QueryGoodsVo();
  1920. queryGoodsVo.setProdBarcode((String) map.get("prodBarcode"));
  1921. queryGoodsVo.setSku((String) map.get("goodsSn"));
  1922. queryGoodsVo.setStoreId(storeId);
  1923. queryGoodsVo.setSellVolume((Integer) map.get("sellVolume"));
  1924. queryGoodsVo.setRetailPrice(new BigDecimal(String.valueOf(map.get("retailPrice"))));
  1925. queryGoodsVo.setGoodsTaxes(new BigDecimal(String.valueOf(map.get("goodstaxes"))));
  1926. queryGoodsVo.setDisCountedPrice(new BigDecimal(String.valueOf(map.get("disCountedPrice"))));
  1927. queryGoodsVoList.add(queryGoodsVo);
  1928. });
  1929. // 将在循环中查询数据库改为一次性查询
  1930. List<GoodsEntity> goodsEntityList = goodsService.queryGoodsStockByQueryGoodsVoList(queryGoodsVoList);
  1931. // 复制集合数据
  1932. ListUtils listUtils = BeanUtils.instantiate(ListUtils.class);
  1933. listUtils.copyList(goodsEntityList, queryGoodsVoList);
  1934. // 用来存储是否达到满赠条件的map
  1935. Map<String, BigDecimal> categoryConditionMap = new HashMap<>();
  1936. Map<String, BigDecimal> brandConditionMap = new HashMap<>();
  1937. for (QueryGoodsVo goodsEntity : queryGoodsVoList) {
  1938. OrderGoodsEntity orderGoodsEntity = new OrderGoodsEntity();
  1939. // 要购买的数量
  1940. Integer sellVolume = goodsEntity.getSellVolume();
  1941. // 条码
  1942. String prodBarcode = goodsEntity.getProdBarcode();
  1943. // 当前sku
  1944. String sku = goodsEntity.getSku();
  1945. // 订单金额(含税价),订单总金额,用户支付的金额
  1946. BigDecimal retailPrice = goodsEntity.getRetailPrice();
  1947. // 商品预估税率
  1948. BigDecimal goodsTaxes = goodsEntity.getGoodsTaxes();
  1949. // 商品优惠金额
  1950. BigDecimal disCountedPrice = goodsEntity.getDisCountedPrice();
  1951. // 商品金额(不包含税的价格),推送海关电子订单需要
  1952. goodsPrice = goodsPrice.add(retailPrice.subtract(goodsTaxes));
  1953. // 累加订单价格(含税价)
  1954. orderPrice = orderPrice.add(retailPrice);
  1955. // 总税款
  1956. totalTax = totalTax.add(goodsTaxes);
  1957. // 当前sku
  1958. String currentSku = goodsEntity.getSku();
  1959. // 仓库库存
  1960. Integer warehouseStock = stockMap.get(currentSku);
  1961. // 门店库存
  1962. Integer stockNum = goodsEntity.getStockNum();
  1963. // 判断库存。。
  1964. if (!stockMap.containsKey(currentSku)) {
  1965. LOGGER.error("库存系统中不包含此sku:【{}】,校验库存出错!下单失败!", currentSku);
  1966. throw new ServiceException(String.format("不包含此sku:【%s】", currentSku));
  1967. } else {
  1968. // 保税仓库存 + 展销店库存 - 出区数 >= 购买数
  1969. // 当前出区数
  1970. Integer exitRegionNumber = goodsEntity.getExitRegionNumber();
  1971. // 保税仓库存 + 门店库存 - 出区数 >= 购买数
  1972. if (!((warehouseStock + stockNum) - exitRegionNumber >= sellVolume)) {
  1973. // 库存不足
  1974. LOGGER.error("sku【{}】库存不足!商品条码:【{}】,门店库存:【{}】,保税仓库存:【{}】,当前出区数:【{}】", currentSku, prodBarcode, stockNum, warehouseStock, exitRegionNumber);
  1975. throw new ServiceException(String.format("sku【%s】库存不足!商品条码:【%s】,门店库存:【%s】,保税仓库存:【%s】,当前出区数:【%s】", currentSku, prodBarcode, stockNum, warehouseStock, exitRegionNumber));
  1976. }
  1977. }
  1978. // 设置订单详情信息
  1979. GoodsEntity entity = new GoodsEntity(goodsEntity);
  1980. wrapOrderGoods(orderGoodsEntity, entity);
  1981. orderGoodsEntities.add(orderGoodsEntity);
  1982. // 设置条件信息,暂不支持门店满赠活动
  1983. String categoryId = String.valueOf(entity.getCategoryId());
  1984. String brandId = String.valueOf(entity.getBrandId());
  1985. if (!categoryConditionMap.containsKey(categoryId)) {
  1986. categoryConditionMap.put(categoryId, retailPrice);
  1987. } else {
  1988. categoryConditionMap.put(categoryId, categoryConditionMap.get(categoryId).add(retailPrice));
  1989. }
  1990. // if (!brandConditionMap.containsKey(brandId)) {
  1991. // brandConditionMap.put(brandId, retailPrice);
  1992. // } else {
  1993. // brandConditionMap.put(brandId, brandConditionMap.get(brandId).add(retailPrice));
  1994. // }
  1995. }
  1996. // 2. 判断购买的商品是否能参与满减活动
  1997. // 2.1 查询当前门店是否有满赠的活动
  1998. List<MkActivitiesEntity> activitiesEntities = mkActivitiesService.queryByNowByMz(String.valueOf(storeId), DateUtils.format(new Date(), "yyyy-MM-dd"));
  1999. if (CollectionUtils.isEmpty(activitiesEntities)) {
  2000. LOGGER.error("----- 该门店【{}】暂无满赠活动! -----", storeId);
  2001. } else {
  2002. // 当前门店的活动编号
  2003. List<Long> activitiesSnList = activitiesEntities.stream().map(MkActivitiesEntity::getMkaId).collect(Collectors.toList());
  2004. // 活动
  2005. List<MkActivitiesFullGiftEntity> mkActivitiesFullGiftEntities = mkActivitiesFullGiftService.queryByMkaIdList(activitiesSnList);
  2006. if (CollectionUtils.isEmpty(mkActivitiesFullGiftEntities)) {
  2007. LOGGER.error("----- 该门店【{}】暂无满赠活动! -----", storeId);
  2008. } else {
  2009. mkActivitiesFullGiftEntities.forEach(mkActivitiesFullGiftEntity -> {
  2010. // 存在品牌满赠活动,暂不支持品牌满赠活动
  2011. // String brandId = String.valueOf(mkActivitiesFullGiftEntity.getBrandId());
  2012. // if (brandConditionMap.containsKey(brandId)) {
  2013. // if (brandConditionMap.get(brandId).compareTo(mkActivitiesFullGiftEntity.getQualifiedAmount()) > 0) {
  2014. // // 该品牌满足满赠条件
  2015. //
  2016. // }
  2017. // }
  2018. // 存在分类满赠活动
  2019. String categoryId = String.valueOf(mkActivitiesFullGiftEntity.getCategoryId());
  2020. if (!CollectionUtils.isEmpty(categoryConditionMap) && categoryConditionMap.containsKey(categoryId)) {
  2021. if (categoryConditionMap.get(categoryId).compareTo(mkActivitiesFullGiftEntity.getQualifiedAmount()) > 0) {
  2022. // 该分类满足满赠条件
  2023. String giftBarcode = mkActivitiesFullGiftEntity.getGiftBarcode();
  2024. String giftGoodsSn = mkActivitiesFullGiftEntity.getGiftGoodsSn();
  2025. String shopSn = mkActivitiesFullGiftEntity.getShopSn();
  2026. GoodsEntity goodsEntity = goodsService.queryGoodsStockByBarcodeAndStoreIdAndSku(giftBarcode, Integer.parseInt(shopSn), giftGoodsSn);
  2027. // 存储赠送数
  2028. goodsEntity.setGoodsNumber(mkActivitiesFullGiftEntity.getGiftNumber());
  2029. OrderGoodsEntity orderGoodsEntity = new OrderGoodsEntity();
  2030. wrapOrderGoods(orderGoodsEntity, goodsEntity);
  2031. orderGoodsEntity.setRetailPrice(BigDecimal.ZERO);
  2032. orderGoodsEntity.setDiscountedPrice(BigDecimal.ZERO);
  2033. orderGoodsEntity.setActualPaymentAmount(BigDecimal.ZERO);
  2034. orderGoodsEntities.add(orderGoodsEntity);
  2035. }
  2036. }
  2037. });
  2038. }
  2039. }
  2040. // 3. 校验是否是会员,调用会员系统查询会员信息,查询接口:
  2041. // 优惠后价格
  2042. BigDecimal afterDiscountPrice;
  2043. if (org.springframework.util.StringUtils.isEmpty(couponBarCode)) {
  2044. // 不是会员,不享受积分抵扣,只能使用门店的优惠券
  2045. afterDiscountPrice = calculatePreferentialPrice(orderPrice, 0, goodsList, storeId, userInfo);
  2046. } else {
  2047. // 会员,计算优惠价
  2048. String queryMemberInfoResponse;
  2049. try {
  2050. // 查询会员信息
  2051. queryMemberInfoResponse = haiKongMemberTemplate.getMemberInfoByCode("{\"code\":\"" + couponBarCode + "\"}");
  2052. Response<MemberInfoDTO> response = JacksonUtil.fromListJson(queryMemberInfoResponse, new TypeReference<Response<MemberInfoDTO>>() {
  2053. });
  2054. if (Objects.nonNull(response) && response.getSuccess()) {
  2055. MemberInfoDTO memberInfoDTO = response.getData();
  2056. Integer score = memberInfoDTO.getScore();
  2057. if (Objects.nonNull(score) && score > 0) {
  2058. // 有积分
  2059. afterDiscountPrice = calculatePreferentialPrice(orderPrice, score, goodsList, storeId, userInfo);
  2060. } else {
  2061. // 无积分
  2062. afterDiscountPrice = calculatePreferentialPrice(orderPrice, 0, goodsList, storeId, userInfo);
  2063. }
  2064. } else {
  2065. LOGGER.error("查询会员信息失败!响应结果:{}", queryMemberInfoResponse);
  2066. throw new ServiceException("查询会员信息失败!请重新下单!");
  2067. }
  2068. } catch (Exception e) {
  2069. LOGGER.error("查询会员信息失败!请重新下单!");
  2070. throw new ServiceException("查询会员信息失败!请重新下单!");
  2071. }
  2072. }
  2073. // 4. 调用付款接口
  2074. // 判断是微信的支付码还是支付宝的支付码
  2075. if (parCode.startsWith("28")) {
  2076. // 支付宝支付
  2077. try {
  2078. // AliPay(user, parCode, order, processRecordEntity, orderWXPayRecordCurrent, store);
  2079. } catch (Exception e) {
  2080. e.printStackTrace();
  2081. throw e;
  2082. }
  2083. } else {
  2084. // 微信支付
  2085. try {
  2086. // wxPay(user, parCode, resultObj, order, processRecordEntity, orderWXPayRecordCurrent, store);
  2087. } catch (Exception e) {
  2088. e.printStackTrace();
  2089. throw e;
  2090. }
  2091. }
  2092. // 5. 扣减库存
  2093. // 6. 订单入库
  2094. return resultObj;
  2095. }
  2096. /**
  2097. * 设置订单商品详情数据
  2098. * @param orderGoodsEntity 订单商品详情
  2099. * @param goodsEntity 商品信息
  2100. * @return 订单商品详情
  2101. */
  2102. private OrderGoodsEntity wrapOrderGoods(OrderGoodsEntity orderGoodsEntity, GoodsEntity goodsEntity) {
  2103. // 设置商品信息
  2104. BeanUtils.copyProperties(goodsEntity, orderGoodsEntity);
  2105. // 设置订单信息
  2106. // 销售数
  2107. orderGoodsEntity.setNumber(goodsEntity.getGoodsNumber());
  2108. // TODO other...
  2109. return orderGoodsEntity;
  2110. }
  2111. /**
  2112. * 计算优惠后的价格
  2113. * 1、优惠券优先于积分抵扣
  2114. * 2、限时特价与积分不互斥,虽然海控没说哪个优先,但我觉得应该是限时特价优先于积分
  2115. * 3、优惠券之间互斥
  2116. * 4、活动和优惠券互斥
  2117. * @param orderPrice 订单总价
  2118. * @param score 会员积分
  2119. * @param goodsEntities 订单商品明细
  2120. * @param storeId 门店id
  2121. * @param userInfo 用户信息
  2122. * @return 优惠后的价格
  2123. */
  2124. private BigDecimal calculatePreferentialPrice (BigDecimal orderPrice, Integer score, List<LinkedHashMap> goodsEntities, Integer storeId, Map userInfo) {
  2125. // 优惠后的价格
  2126. BigDecimal preferentialPrice = BigDecimal.ZERO;
  2127. // 1. 判断是否有积分,是否需要计算积分抵扣后的价格
  2128. AtomicBoolean isCalculateScorePrice = new AtomicBoolean(false);
  2129. if (Objects.nonNull(score) && score > 0) {
  2130. isCalculateScorePrice.set(true);
  2131. }
  2132. // 2. 查询订单商品是否有优惠券和参加活动
  2133. goodsEntities.forEach(map -> {
  2134. // 2-1. 判断活动和优惠券之间的互斥关系
  2135. // 2-2. 计算优惠、活动后的总价格
  2136. });
  2137. // 3. 计算积分抵扣后的总价格
  2138. if (isCalculateScorePrice.get()) {
  2139. // 3-1. 计算总价的50%
  2140. BigDecimal halfPrice = preferentialPrice.multiply(new BigDecimal("0.5")).setScale(2, BigDecimal.ROUND_HALF_UP);
  2141. Integer scoreLimit = haiKongProperties.getScoreLimit();
  2142. if (score < scoreLimit) {
  2143. LOGGER.warn("用户【{}】的积分数量为:{},最低需要30积分才能抵扣!", userInfo.get("customName"), score);
  2144. return preferentialPrice;
  2145. } else {
  2146. // 3-2. 计算出积分能抵扣的价格
  2147. int scoreMayDeductionPrice = score % scoreLimit == 0 ? score / scoreLimit : (int) (score / scoreLimit);
  2148. // 3-3. 计算积分抵扣后的价格
  2149. BigDecimal scoreMayDeductionPriceDecimal = new BigDecimal(scoreMayDeductionPrice);
  2150. if (halfPrice.compareTo(scoreMayDeductionPriceDecimal) > 0) {
  2151. preferentialPrice = preferentialPrice.subtract(scoreMayDeductionPriceDecimal);
  2152. } else {
  2153. // 积分能抵扣的金额如果比总价的50%还要多,只能抵扣50%
  2154. // 总价50%的值
  2155. int halfPriceInt = halfPrice.setScale(0, BigDecimal.ROUND_FLOOR).intValue();
  2156. int i = scoreMayDeductionPrice - halfPriceInt;
  2157. preferentialPrice = preferentialPrice.subtract(new BigDecimal(halfPriceInt));
  2158. }
  2159. }
  2160. }
  2161. return preferentialPrice;
  2162. }
  2163. /**
  2164. * 提交订单并付款
  2165. *
  2166. * @param param 提交的订单数据、包括用户信息、支付码、会话id、机器码(收银台)、取货方式、收货地址信息、会员码
  2167. * @param user
  2168. * @return
  2169. */
  2170. @Override
  2171. @Transactional
  2172. public synchronized Map offlineRetailSubmit(Map param, SysUserEntity user) {
  2173. // 解析订单数据 List
  2174. List<LinkedHashMap> goodsList = (List<LinkedHashMap>) param.get("goodsList");
  2175. // 解析用户信息 LinkedHashMap
  2176. Map userInfo = (Map) param.get("userInfo");
  2177. // 解析支付码 String
  2178. String parCode = (String) param.get("payCode");
  2179. // 解析sessionId(WebSocket) String
  2180. String sessionId = (String) param.get("sessionId");
  2181. // machineCode
  2182. String machineCode = (String) param.get("machineCode");
  2183. //选择的方式 1柜取 0邮寄
  2184. int status = Integer.parseInt(param.get("status").toString());
  2185. Map<String, String> mapAddr = new HashMap<>();
  2186. if (status == 0) {
  2187. //省
  2188. String cmbProvince = (String) param.get("cmbProvince");
  2189. //市
  2190. String cmbCity = (String) param.get("cmbCity");
  2191. //区
  2192. String cmbArea = (String) param.get("cmbArea");
  2193. //详细地址
  2194. String addrUser = (String) param.get("addrUser");
  2195. mapAddr.put("cmbProvince", cmbProvince);
  2196. mapAddr.put("cmbCity", cmbCity);
  2197. mapAddr.put("cmbArea", cmbArea);
  2198. mapAddr.put("addrUser", addrUser);
  2199. }
  2200. try {
  2201. machineCode = URLDecoder.decode(machineCode, "UTF-8");
  2202. } catch (Exception e) {
  2203. // e.printStackTrace();
  2204. }
  2205. Map resultObj = Maps.newHashMap();
  2206. try {
  2207. if (user == null) {
  2208. resultObj.put("errno", 400);
  2209. resultObj.put("errmsg", "用户登录超时,请重新登录");
  2210. return resultObj;
  2211. }
  2212. if (!user.getRoleType().equalsIgnoreCase("2")) {
  2213. resultObj.put("errno", 400);
  2214. resultObj.put("errmsg", "该操作只允许店员账户操作");
  2215. return resultObj;
  2216. }
  2217. if (org.apache.commons.lang3.StringUtils.isEmpty(user.getMerchSn())) {
  2218. resultObj.put("errno", 400);
  2219. resultObj.put("errmsg", "操作用户的商户编号为空,请先维护用户商户编号信息再来操作");
  2220. return resultObj;
  2221. }
  2222. Long userId = user.getUserId();
  2223. Integer storeId = user.getStoreId();
  2224. List<GoodsEntity> goodsEntities = new ArrayList<>();
  2225. BigDecimal totalTax = new BigDecimal(0);
  2226. // 检查库存和更新库存
  2227. for (LinkedHashMap goodsDto : goodsList) {
  2228. // 要购买的数量
  2229. Integer sellVolume = (Integer) goodsDto.get("sellVolume");
  2230. Integer goodsSellNumber = (Integer) goodsDto.get("sellVolume");
  2231. String prodBarcode = (String) goodsDto.get("prodBarcode");
  2232. String sku = (String) goodsDto.get("goodsSn");
  2233. Map<GoodsEntity, Integer> numberMap = new HashMap<>();
  2234. // 根据商品条码,门店id,sku查找库存
  2235. List<GoodsEntity> queryGoodsList = goodsDao.queryListByBarcode(prodBarcode, storeId,sku);
  2236. if (queryGoodsList != null && queryGoodsList.size() != 0) {
  2237. for (GoodsEntity goodsEntity : queryGoodsList) {
  2238. // 如果当前还有需要购买的
  2239. if (sellVolume > 0) {
  2240. // 当前商品剩余的数量, 门店库存
  2241. Integer remainAmount = Integer.parseInt(goodsEntity.getStockNum());
  2242. if (sellVolume >= remainAmount) {
  2243. // 证明该sku库存不足,需要继续向下个sku消费
  2244. sellVolume -= remainAmount;
  2245. // 记录该商品用了多少个数量
  2246. numberMap.put(goodsEntity, remainAmount);
  2247. } else {
  2248. // 记录该商品用了多少个数量
  2249. numberMap.put(goodsEntity, sellVolume);
  2250. sellVolume = 0;
  2251. }
  2252. }
  2253. }
  2254. }
  2255. // 园区库存是有问题的, 这里去掉校验极端情况下可能会导致园区库存为负数
  2256. // if (sellVolume > 0) {
  2257. // resultObj.put("errno", 400);
  2258. // resultObj.put("errmsg", "订单提交失败:条形码:" + prodBarcode + ",电商门店库存不足");
  2259. // return resultObj;
  2260. // }
  2261. Iterator<GoodsEntity> goodsIterator = numberMap.keySet().iterator();
  2262. // 循环购买的商品map,重新计算数量跟价格
  2263. while (goodsIterator.hasNext()) {
  2264. GoodsEntity goodsEntity = goodsIterator.next();
  2265. // 该商品购买数量
  2266. Integer num = numberMap.get(goodsEntity);
  2267. // 取得规格的信息,判断规格库存,门店库存
  2268. ProductStoreRelaEntity productInfo = productStoreRelaDao
  2269. .queryByGoodsIdAndStoreId(Long.valueOf(storeId), Long.valueOf(goodsEntity.getId()));
  2270. // 判断园区库存
  2271. synchronized (productInfo) {
  2272. // if (null == productInfo || null == productInfo.getStockNum() ||
  2273. // productInfo.getStockNum() < (num)) {
  2274. // resultObj.put("errno", 400);
  2275. // resultObj.put("errmsg", "条形码:" + prodBarcode + ",电商门店库存不足,仅剩余" + productInfo.getStockNum());
  2276. // return resultObj;
  2277. // } else {
  2278. // 判断销售价是否低于底线价
  2279. // if(productInfo.getBottomLinePrice() != null){
  2280. // BigDecimal bottomLinePrice = new BigDecimal(productInfo.getBottomLinePrice());
  2281. // if (goodsEntity.getStoreRetailPrice().compareTo(bottomLinePrice) <= -1) {
  2282. // LOGGER.error("销售价格小于底线价格");
  2283. //
  2284. // // 记录该信息,到价格过低日志表中,这里没有活动id
  2285. // Mall2LowPriceWarningEntity lowPriceWarningEntity = new Mall2LowPriceWarningEntity();
  2286. // lowPriceWarningEntity.setSalePrice(goodsEntity.getStoreRetailPrice());
  2287. // lowPriceWarningEntity.setWarningPrice(bottomLinePrice);
  2288. // lowPriceWarningEntity.setSku(goodsEntity.getGoodsSn());
  2289. // lowPriceWarningEntity.setWarningType("00");
  2290. // lowPriceWarningEntity.setStoreId(storeId+"");
  2291. // lowPriceWarningEntity.setCreateTime(new Date());
  2292. //
  2293. // lowPriceWarningDao.save(lowPriceWarningEntity);
  2294. // resultObj.put("errno", 400);
  2295. // resultObj.put("errmsg", "商品"+goodsEntity.getName()+"的销售价格小于底线价格");
  2296. // return resultObj;
  2297. // }
  2298. // }
  2299. // 门店库存变化记录
  2300. StoreMngChangeEntity storeMngChangeEntity = new StoreMngChangeEntity();
  2301. storeMngChangeEntity.setChangeType(Dict.changeType.item_1.getItem());
  2302. storeMngChangeEntity.setChangeReason("商品销售扣减");
  2303. storeMngChangeEntity.setGoodsId(Integer.parseInt(String.valueOf(productInfo.getGoodsId())));
  2304. storeMngChangeEntity.setStoreId(Integer.parseInt(String.valueOf(productInfo.getStoreId())));
  2305. storeMngChangeEntity.setMerchSn(productInfo.getMerchSn());
  2306. storeMngChangeEntity.setStoreChangeNum(num);
  2307. storeMngChangeEntity.setStoreOriginalNum(productInfo.getStockNum());
  2308. storeMngChangeEntity.setStoreValidNum(productInfo.getStockNum() - num);
  2309. storeMngChangeEntity.setCreateTime(new Date());
  2310. storeMngChangeEntity.setModTime(new Date());
  2311. storeMngChangeEntity.setCreaterSn(user.getUsername());
  2312. storeMngChangeEntity.setModerSn(user.getUsername());
  2313. storeMngChangeEntity.setIsValid(0);
  2314. storeMngChangeDao.save(storeMngChangeEntity);
  2315. int validNum = productInfo.getStockNum() - num;
  2316. if (goodsEntity != null) {
  2317. MngChangeEntity mngChangeEntity = new MngChangeEntity();
  2318. mngChangeEntity.setThirdPartyMerchCode(goodsEntity.getThirdPartyMerchCode());
  2319. mngChangeEntity.setChangeReason("商品销售扣减");
  2320. mngChangeEntity.setCreateTime(new Date());
  2321. mngChangeEntity.setModTime(new Date());
  2322. mngChangeEntity.setCreaterSn(user.getUsername());
  2323. mngChangeEntity.setModerSn(user.getUsername());
  2324. mngChangeEntity.setIsValid(0);
  2325. mngChangeEntity.setMerchSn(goodsEntity.getMerchSn());
  2326. mngChangeEntity.setOriginalNum(goodsEntity.getGoodsNumber());//原库存数
  2327. mngChangeEntity.setValidNum(goodsEntity.getGoodsNumber() - num);//可用数
  2328. mngChangeEntity.setChangeNum(num);//变化数
  2329. mngChangeEntity.setChangeType(Dict.changeType.item_1.getItem());
  2330. mngChangeEntity.setGoodsId(Integer.parseInt(String.valueOf(goodsEntity.getId())));
  2331. mngChangeDao.save(mngChangeEntity);
  2332. // 如果园区库存数量小于等于0, 则不更新园区库存, 园区库存只做参考
  2333. int diff = Math.max(goodsEntity.getGoodsNumber() - num, 0);
  2334. goodsEntity.setGoodsNumber(diff);
  2335. goodsEntity.setLastSaleTime(new Date());
  2336. goodsDao.update(goodsEntity);
  2337. }
  2338. // 门店库存
  2339. productInfo.setStockNum(validNum);
  2340. productInfo.setStoreId(Long.valueOf(storeId));
  2341. productInfo.setSellVolume(productInfo.getSellVolume() + num);
  2342. productInfo.setLastSaleTime(new Date());
  2343. productStoreRelaDao.updateStockNum(productInfo);//修改普通商品库存
  2344. }
  2345. BigDecimal retailPrice = new BigDecimal(0);
  2346. BigDecimal storeRetailPrice = new BigDecimal(0);
  2347. if (goodsDto.get("retailPrice") instanceof Double) {
  2348. retailPrice = new BigDecimal((Double) goodsDto.get("retailPrice")); // 单价
  2349. storeRetailPrice = new BigDecimal((Double) goodsDto.get("retailPrice")); // 单价
  2350. } else if (goodsDto.get("retailPrice") instanceof Integer) {
  2351. retailPrice = new BigDecimal((Integer) goodsDto.get("retailPrice"));
  2352. storeRetailPrice = new BigDecimal((Integer) goodsDto.get("retailPrice"));
  2353. } else if (goodsDto.get("retailPrice") instanceof Float) {
  2354. retailPrice = new BigDecimal((Float) goodsDto.get("retailPrice"));
  2355. storeRetailPrice = new BigDecimal((Float) goodsDto.get("retailPrice"));
  2356. }
  2357. // 优惠价
  2358. BigDecimal disCountedPrice = new BigDecimal(0);
  2359. // 实际支付价
  2360. BigDecimal actualPaymentAmount = new BigDecimal(0);
  2361. if (goodsDto.get("discountedPrice") instanceof Double) {
  2362. disCountedPrice = new BigDecimal((Double) goodsDto.get("discountedPrice")); // 优惠金额
  2363. } else if (goodsDto.get("discountedPrice") instanceof Integer) {
  2364. disCountedPrice = new BigDecimal((Integer) goodsDto.get("discountedPrice"));
  2365. } else if (goodsDto.get("discountedPrice") instanceof Float) {
  2366. disCountedPrice = new BigDecimal((Float) goodsDto.get("discountedPrice"));
  2367. }
  2368. if (goodsDto.get("actualPaymentAmount") instanceof Double) {
  2369. actualPaymentAmount = new BigDecimal((Double) goodsDto.get("actualPaymentAmount")); // 实际支付价格
  2370. } else if (goodsDto.get("actualPaymentAmount") instanceof Integer) {
  2371. actualPaymentAmount = new BigDecimal((Integer) goodsDto.get("actualPaymentAmount"));
  2372. } else if (goodsDto.get("actualPaymentAmount") instanceof Float) {
  2373. actualPaymentAmount = new BigDecimal((Float) goodsDto.get("actualPaymentAmount"));
  2374. }
  2375. disCountedPrice = disCountedPrice
  2376. .divide(new BigDecimal(goodsSellNumber), 3, RoundingMode.HALF_UP)
  2377. .multiply(new BigDecimal(num))
  2378. .setScale(2, RoundingMode.HALF_UP);
  2379. actualPaymentAmount = actualPaymentAmount
  2380. .divide(new BigDecimal(goodsSellNumber), 3, RoundingMode.HALF_UP)
  2381. .multiply(new BigDecimal(num))
  2382. .setScale(2, RoundingMode.HALF_UP);
  2383. goodsEntity.setRetailPrice(retailPrice);
  2384. goodsEntity.setStoreRetailPrice(storeRetailPrice);
  2385. goodsEntity.setDiscountedPrice(disCountedPrice);
  2386. goodsEntity.setActualPaymentAmount(actualPaymentAmount);
  2387. // 借用这个字段来存储购买数
  2388. goodsEntity.setGoodsNumber(num);
  2389. goodsEntity.setActivity((String) goodsDto.get("activity"));
  2390. goodsEntities.add(goodsEntity);
  2391. }
  2392. // 计算该购物车所需要的所有税费
  2393. Object taxObject = goodsDto.get("goodstaxes");
  2394. BigDecimal tax = new BigDecimal(0);
  2395. if (taxObject instanceof Double) {
  2396. tax = new BigDecimal((Double) taxObject);
  2397. } else if (taxObject instanceof Integer) {
  2398. tax = new BigDecimal((Integer) taxObject);
  2399. } else if (taxObject instanceof Float) {
  2400. tax = new BigDecimal((Float) taxObject);
  2401. } else if (taxObject instanceof String) {
  2402. tax = new BigDecimal((String) taxObject);
  2403. }
  2404. totalTax = totalTax.add(tax).setScale(2, BigDecimal.ROUND_HALF_DOWN); // 计算总的税额
  2405. }
  2406. UserEntity userEntity = userDao.queryByMobile((String) userInfo.get("customPhone"));
  2407. if (userEntity == null) {
  2408. // 保存用户信息
  2409. userEntity = new UserEntity();
  2410. userEntity.setUsername((String) userInfo.get("customName"));
  2411. userEntity.setPassword("");
  2412. userEntity.setIdNo((String) userInfo.get("customIDCard"));
  2413. userEntity.setMobile((String) userInfo.get("customPhone"));
  2414. userEntity.setGender(1);
  2415. userEntity.setRegisterTime(new Date());
  2416. userEntity.setLastLoginTime(new Date());
  2417. userEntity.setIdNo((String) userInfo.get("customIDCard"));
  2418. userDao.save(userEntity);
  2419. MerchUserEntity merchUserEntity = new MerchUserEntity();
  2420. merchUserEntity.setMerchSn(user.getMerchSn());
  2421. merchUserEntity.setStoreId(storeId);
  2422. merchUserEntity.setUserId(userEntity.getId());
  2423. merchUserEntity.setCreateTime(new Date());
  2424. merchUserEntity.setIsLoadGoods("0");
  2425. merchUserDao.save(merchUserEntity);
  2426. } else {
  2427. userEntity.setUsername((String) userInfo.get("customName"));
  2428. userEntity.setIdNo((String) userInfo.get("customIDCard"));
  2429. userEntity.setMobile((String) userInfo.get("customPhone"));
  2430. userDao.update(userEntity);
  2431. }
  2432. // TODO 查询使用的优惠券,并减扣金额
  2433. String couponSn = (String) userInfo.get("couponSn");
  2434. // 获取当前时间
  2435. String currentTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
  2436. MkActivitiesCouponEntity couponEntity = mkActivitiesCouponService.queryByCouponSn(couponSn, currentTime);
  2437. // // 优惠金额
  2438. BigDecimal disCountAmount = new BigDecimal(0);
  2439. if (couponEntity != null) {
  2440. disCountAmount = couponEntity.getCouponPrice();
  2441. }
  2442. // 判断该用户是否是生日
  2443. Boolean isBirth = false;
  2444. String birthday = "";
  2445. if (userEntity.getIdNo().length() == 15) {
  2446. birthday = userEntity.getIdNo().substring(8, 10) + "-" + userEntity.getIdNo().substring(10, 12);
  2447. } else if (userEntity.getIdNo().length() == 18) {
  2448. birthday = userEntity.getIdNo().substring(10, 12) + "-" + userEntity.getIdNo().substring(12, 14);
  2449. }
  2450. SimpleDateFormat format = new SimpleDateFormat("MM-dd");
  2451. String today = format.format(new Date());
  2452. if (birthday.equalsIgnoreCase(today)) {
  2453. isBirth = true;
  2454. }
  2455. // 生成订单
  2456. String merchOrderSn = "EMATO" + CommonUtil.generateOrderNumber();
  2457. OrderVo order = setOrderVo(goodsEntities, userEntity, storeId.longValue(), user.getMerchSn(), disCountAmount, totalTax, status, mapAddr);
  2458. order.setStore_id(storeId.longValue());
  2459. // if(storeTopic != null){
  2460. // order.setActivity_id(storeTopic.getId().longValue());
  2461. // }
  2462. order.setMerchOrderSn(merchOrderSn);
  2463. order.setCoupon_name(couponSn); // 借用这个字段来记录是否使用优惠券
  2464. //插入订单信息和订单商品
  2465. orderDao.saveOrderVo(order);
  2466. // TODO req_2021-07-19 电商端下单时间 req_20210826_001
  2467. customsClearanceTimeliness.send(Arrays.asList(order.getOrder_sn()), "customerOrder");
  2468. // TODO 订单流转表
  2469. OrderProcessRecordEntity processRecordEntity = new OrderProcessRecordEntity();
  2470. processRecordEntity.setOrderSn(order.getOrder_sn());
  2471. processRecordEntity.setUserId(Integer.valueOf(userEntity.getId() + ""));
  2472. processRecordEntity.setAddOrderStartTime(order.getCreateTime());
  2473. processRecordEntity.setIsAddOrderSend(Dict.isSend.item_1.getItem());
  2474. processRecordEntity.setOrderBizType(Dict.orderBizType.item_10.getItem());
  2475. if (null == order.getId()) {
  2476. resultObj.put("errno", 400);
  2477. resultObj.put("errmsg", "订单提交失败");
  2478. return resultObj;
  2479. }
  2480. List<OrderGoodsVo> orderGoodsVoList = new ArrayList<>();
  2481. for (GoodsEntity goodsDto : goodsEntities) {
  2482. OrderGoodsVo orderGoodsVo = setOrderGoodsVo(order, goodsDto);
  2483. //新增订单详情
  2484. orderGoodsDao.saveOrderGoodsVo(orderGoodsVo);
  2485. orderGoodsVoList.add(orderGoodsVo);
  2486. }
  2487. //清空预订单商品临时表
  2488. Map orderInfoMap = Maps.newHashMap();
  2489. orderInfoMap.put("orderInfo", order);
  2490. resultObj.put("errno", 0);
  2491. resultObj.put("errmsg", "订单提交成功");
  2492. resultObj.put("data", orderInfoMap);
  2493. //判断支付类型,并支付订单
  2494. R r = null;
  2495. //保存支付记录
  2496. OrderWXPayRecordEntity orderWXPayRecordCurrent = orderWXPayRecordService.saveRecordVo(order);
  2497. StoreEntity store = storeService.queryObject(order.getStore_id().intValue());
  2498. // 设置支付单开始时间
  2499. // TODO req_2021-07-19 顾客付款时间 req_20210826_001
  2500. customsClearanceTimeliness.send(Arrays.asList(order.getOrder_sn()), "customerPay");
  2501. processRecordEntity.setPaymentStartTime(new Date());
  2502. // 判断是微信的支付码还是支付宝的支付码
  2503. // if (parCode.startsWith("28")) {
  2504. // // 支付宝支付
  2505. // try {
  2506. // AliPay(user, parCode, order, processRecordEntity, orderWXPayRecordCurrent, store);
  2507. // } catch (Exception e) {
  2508. // e.printStackTrace();
  2509. // throw e;
  2510. // }
  2511. // } else {
  2512. // // 微信支付
  2513. // try {
  2514. // wxPay(user, parCode, resultObj, order, processRecordEntity, orderWXPayRecordCurrent, store);
  2515. // } catch (Exception e) {
  2516. // e.printStackTrace();
  2517. // throw e;
  2518. // }
  2519. // }
  2520. // TODO req_2021-07-19 客户付款完成时间 req_20210826_001
  2521. customsClearanceTimeliness.send(Arrays.asList(order.getOrder_sn()), "customerPayFinished");
  2522. processRecordEntity.setPaymentStartTime(new Date());
  2523. // TODO 到时候要注释掉,测试用而已
  2524. OrderEntity orderEntity = queryObject(order.getId());
  2525. orderEntity.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_201.getItem()));
  2526. orderEntity.setPayStatus(Integer.parseInt(Dict.payStatus.item_2.getItem()));
  2527. orderEntity.setPayTime(new Date());
  2528. orderDao.update(orderEntity);
  2529. resultObj.put("shopName", store.getStoreName()); // 根据门店编号查询
  2530. resultObj.put("userName", user.getUsername());
  2531. // 保存订单流转表
  2532. // 设置下单完成时间
  2533. processRecordEntity.setAddOrderSuccTime(order.getPay_time());
  2534. orderProcessRecordDao.save(processRecordEntity);
  2535. // 生成销售记录
  2536. SaleRecordEntity saleRecordEntity = new SaleRecordEntity();
  2537. // 根据收银机机器码,查询收银机
  2538. CashierEntity cashierEntity = cashierDao.queryByMachineCode(machineCode, storeId + "");
  2539. if (cashierEntity != null) {
  2540. saleRecordEntity.setCashierSn(cashierEntity.getCashierSn());
  2541. saleRecordEntity.setOrderSn(order.getOrder_sn());
  2542. saleRecordEntity.setSallerId(userId + "");
  2543. saleRecordEntity.setSalesTime(new Date());
  2544. // saleRecordEntity.setDiscountId(topicId + "");
  2545. saleRecordEntity.setCreateTime(new Date());
  2546. saleRecordDao.save(saleRecordEntity);
  2547. }
  2548. // 查询积分规则 ,默认先按消费金额1:1积分
  2549. Mall2PointsRulesEntity pointsRules = null;
  2550. // 增加该会员的积分
  2551. Mall2MemberPointsEntity memberPointsEntity = memberPointsDao.queryByUserId(userEntity.getId());
  2552. if (memberPointsEntity == null) {
  2553. memberPointsEntity = new Mall2MemberPointsEntity();
  2554. memberPointsEntity.setUserId(userEntity.getId() + "");
  2555. memberPointsEntity.setPoints(order.getActual_price().intValue());
  2556. memberPointsEntity.setCreaterSn(userId + "");
  2557. memberPointsEntity.setCreateTime(new Date());
  2558. memberPointsDao.save(memberPointsEntity);
  2559. } else {
  2560. memberPointsEntity.setPoints(order.getActual_price().add(new BigDecimal(memberPointsEntity.getPoints())).intValue());
  2561. memberPointsEntity.setModerSn(userId + "");
  2562. memberPointsEntity.setModTime(new Date());
  2563. memberPointsDao.update(memberPointsEntity);
  2564. }
  2565. // 增加该会员的消费记录
  2566. Mall2MemberConsumptionRecordsEntity consumptionRecords = new Mall2MemberConsumptionRecordsEntity();
  2567. consumptionRecords.setUserId(userEntity.getId() + "");
  2568. consumptionRecords.setOrderSn(order.getOrder_sn());
  2569. consumptionRecords.setConsumptionTime(new Date());
  2570. consumptionRecords.setShopSn(storeId + "");
  2571. // TODO 判断是否有使用生日优惠
  2572. if (isBirth) {
  2573. consumptionRecords.setIsUseBirthdayOffer("0"); // 使用生日优惠
  2574. } else {
  2575. consumptionRecords.setIsUseBirthdayOffer("1"); // 没使用生日优惠
  2576. }
  2577. consumptionRecords.setCreaterSn(userId + "");
  2578. consumptionRecords.setCreateTime(new Date());
  2579. memberConsumptionRecordsDao.save(consumptionRecords);
  2580. // 生成取票码
  2581. PickUpCodeEntity pickUpCodeEntity = new PickUpCodeEntity();
  2582. pickUpCodeEntity.setOrderSn(order.getOrder_sn());
  2583. pickUpCodeEntity.setPickUpCodeSn(cashierEntity.getCashierSn());//小票码前段
  2584. pickUpCodeService.save(pickUpCodeEntity);
  2585. resultObj.put("code", pickUpCodeEntity.getPickUpCodeSn()); // 系统中累加
  2586. resultObj.put("time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
  2587. resultObj.put("orderNo", order.getOrder_sn()); //
  2588. resultObj.put("phone", (String) userInfo.get("customPhone"));
  2589. // 通知WebSocket
  2590. WebSocketServer.sendMessage(sessionId, order.getOrder_sn(), order.getStore_id()
  2591. + "");
  2592. // TODO 下单流程完成了,现在将下单的库存明细存入表中,准备发送到中控
  2593. // List<KtoEccsEntity> ktoEccsEntities = new LinkedList<>();
  2594. //// orderGoodsVoList
  2595. // for (OrderGoodsVo orderGoodsVo : orderGoodsVoList) {
  2596. // KtoEccsEntity ktoEccsEntity = new KtoEccsEntity();
  2597. // ktoEccsEntity.setRequestData(JSON.toJSONString(orderGoodsVo));
  2598. // ktoEccsEntity.setRequestType("03");
  2599. // ktoEccsEntity.setSendStatus("00");
  2600. // ktoEccsEntity.setCreaterSn(user.getUserId()+"");
  2601. // ktoEccsEntity.setCreateTime(new Date());
  2602. // ktoEccsEntities.add(ktoEccsEntity);
  2603. // }
  2604. //
  2605. //
  2606. // if(ktoEccsEntities.size() > 0){
  2607. // if(ktoEccsEntities.size() > 50){
  2608. // List<List<KtoEccsEntity>> partition = Lists.partition(ktoEccsEntities, 50);
  2609. // for (List<KtoEccsEntity> ktoEccs : partition) {
  2610. // ktoEccsService.saveBatch(ktoEccs);
  2611. // }
  2612. // }else{
  2613. // ktoEccsService.saveBatch(ktoEccsEntities);
  2614. // }
  2615. // }
  2616. return resultObj;
  2617. } catch (Exception e) {
  2618. e.printStackTrace();
  2619. resultObj.put("errno", 400);
  2620. resultObj.put("errmsg", "订单异常------" + e.getMessage());
  2621. throw new RuntimeException(e);
  2622. }
  2623. }
  2624. // private BigDecimal getDisCountAmout(List<GoodsEntity> goodsEntities) {
  2625. // BigDecimal disCountAmount;
  2626. // // TODO 生成订单之前,先查询是否有优惠券或者满减
  2627. // // TODO 20200610 要修改成全部商品
  2628. // // 优惠券的集合
  2629. // List<MkStoreTicketDiscountEntity> mkStoreTicketDiscountEntities = new ArrayList<>();
  2630. // // 满减的集合
  2631. // List<MkStoreCampMinusLevelEntity> mkStoreCampMinusEntities = new ArrayList<>();
  2632. // // 存商品跟金额的关系
  2633. // Map<Long,BigDecimal> moneyMap = new HashMap<>();
  2634. // // 商品总价
  2635. // BigDecimal totalPrice = new BigDecimal(0);
  2636. //
  2637. // for(GoodsEntity goodsEntity : goodsEntities){
  2638. // Long goodsId = goodsEntity.getId();
  2639. // // 计算该商品的价格
  2640. // BigDecimal goodsPrice = goodsEntity.getStoreRetailPrice().multiply(new BigDecimal(goodsEntity.getGoodsNumber())).setScale(2, RoundingMode.HALF_UP);
  2641. // moneyMap.put(goodsId,goodsPrice);
  2642. // totalPrice = totalPrice.add(goodsPrice);
  2643. // // 查询该商品id是否有优惠券
  2644. // List<MkStoreTicketDiscountEntity> mkStoreTicketDiscountEntity = mkStoreTicketDiscountService.queryByGoodsId(goodsId);
  2645. // if(mkStoreTicketDiscountEntity != null) {
  2646. // mkStoreTicketDiscountEntities.addAll(mkStoreTicketDiscountEntity);
  2647. // }
  2648. // // 查询该商品id是否有满减
  2649. // List<MkStoreCampMinusLevelEntity> mkStoreCampMinusEntity = mkStoreCampMinusService.queryByGoodsId(goodsId);
  2650. // if(mkStoreCampMinusEntity != null) {
  2651. // mkStoreCampMinusEntities.addAll(mkStoreCampMinusEntity);
  2652. // }
  2653. // }
  2654. //
  2655. // // 满减优惠的金额
  2656. // BigDecimal campDisCountAmount = new BigDecimal(0);
  2657. // if(mkStoreCampMinusEntities.size() > 0){
  2658. // // 上一次所需金额,用于取最大的优惠力度
  2659. // BigDecimal lastAmount = new BigDecimal(0);
  2660. // for (int i = 0 ; i < mkStoreCampMinusEntities.size() ; i++){
  2661. // MkStoreCampMinusLevelEntity mkStoreCampMinusLevelEntity = mkStoreCampMinusEntities.get(i);
  2662. // // TODO 20200610还有满多少件,跟满多少元打折的,逻辑复杂,下次开发
  2663. // BigDecimal discCond = mkStoreCampMinusLevelEntity.getYuanMinusCond();
  2664. // // 判断这次金额是否大于上次金额,如果不大于,直接continue
  2665. // if(discCond.compareTo(lastAmount) > 0){
  2666. // // 如果总金额大于所需金额,则可以使用该优惠券,记录该优惠券的角标,金额跟优惠的钱
  2667. // if(totalPrice.compareTo(discCond) > 0){
  2668. // // 记录上一次金额
  2669. // lastAmount = discCond;
  2670. // campDisCountAmount = mkStoreCampMinusLevelEntity.getYuanMinusPref();
  2671. // }
  2672. // }
  2673. // }
  2674. // }
  2675. //
  2676. // // 优惠券优惠的金额
  2677. // BigDecimal ticketDisCountAmount = new BigDecimal(0);
  2678. // if(mkStoreTicketDiscountEntities.size() > 0){
  2679. // // 上一次所需金额,用于取最大的优惠力度
  2680. // BigDecimal lastAmount = new BigDecimal(0);
  2681. // BigDecimal lastRadio = new BigDecimal(0);
  2682. // for (int i = 0 ; i < mkStoreTicketDiscountEntities.size() ; i++){
  2683. // MkStoreTicketDiscountEntity mkStoreTicketDiscountEntity = mkStoreTicketDiscountEntities.get(i);
  2684. // // 代金券所需金额
  2685. // // TODO 20200610还有折扣券的,逻辑较为复杂,下次在开发
  2686. //
  2687. // if("00".equals(mkStoreTicketDiscountEntity.getApplyType())){
  2688. // BigDecimal discCond = mkStoreTicketDiscountEntity.getVoucherCond();
  2689. // // 判断这次金额是否大于上次金额,如果不大于,直接continue
  2690. // if(discCond.compareTo(lastAmount) > 0){
  2691. // // 如果总金额大于所需金额,则可以使用该优惠券,记录该优惠券的角标,金额跟优惠的钱
  2692. // if(totalPrice.compareTo(discCond) > 0){
  2693. // // 记录上一次金额
  2694. // lastAmount = discCond;
  2695. // ticketDisCountAmount = mkStoreTicketDiscountEntity.getVoucherMoney();
  2696. // }
  2697. // }
  2698. // }else if("01".equals(mkStoreTicketDiscountEntity.getApplyType())){
  2699. // BigDecimal discCond = mkStoreTicketDiscountEntity.getDiscCond();
  2700. // if(totalPrice.compareTo(discCond) > 0){
  2701. // // 打的折扣
  2702. // lastRadio = mkStoreTicketDiscountEntity.getDiscRatio();
  2703. // }
  2704. //
  2705. //
  2706. // }
  2707. //
  2708. //
  2709. // }
  2710. // }
  2711. //
  2712. //
  2713. // disCountAmount = ticketDisCountAmount.compareTo(campDisCountAmount) > 0 ? ticketDisCountAmount : campDisCountAmount;
  2714. // return disCountAmount;
  2715. // }
  2716. private void AliPay(SysUserEntity user, String parCode, OrderVo order, OrderProcessRecordEntity processRecordEntity, OrderWXPayRecordEntity orderWXPayRecordCurrent, StoreEntity store) throws Exception {
  2717. AliPayRequestParams params = new AliPayRequestParams();
  2718. String orderBizTypeZn = "普通货物";
  2719. if ("00".equals(order.getOrderBizType())) {
  2720. orderBizTypeZn = "保税备货";
  2721. } else if ("02".equals(order.getOrderBizType())) {
  2722. orderBizTypeZn = "保税展示补货";
  2723. } else if ("10".equals(order.getOrderBizType())) {
  2724. orderBizTypeZn = "保税展示跨境";
  2725. }
  2726. params.setAuthCode(parCode);
  2727. params.setBody(order.getApprovalRemark());
  2728. params.setOutTradeNo(order.getOrder_sn());
  2729. params.setSubject(store.getMerchName() + "-" + store.getStoreName() + "-" + orderBizTypeZn);
  2730. params.setStoreId(store.getId() + "");
  2731. params.setTotalAmount(order.getActual_price().setScale(2, BigDecimal.ROUND_HALF_UP) + "");
  2732. LOGGER.info("调用阿里支付接口的请求参数:" + JacksonUtils.toJson(params));
  2733. AliPayMicropayApiResult aliPayMicropayApiResult = AliPayUtil.aliTradePay(params);
  2734. orderWXPayRecordService.updateRecordByAli(orderWXPayRecordCurrent.getId(), aliPayMicropayApiResult);
  2735. LOGGER.info("调用阿里支付接口的同步返回结果:" + JacksonUtils.toJson(aliPayMicropayApiResult));
  2736. // 修改订单状态
  2737. //当支付成功时,修改订单,并把其他支付记录撤销
  2738. if (AliPayUtil.AliPayTradeState.SUCC.getCode().equals(aliPayMicropayApiResult.getCode())) {
  2739. // //查询当前订单所有的支付记录
  2740. // List<OrderWXPayRecordEntity> orderWXPayRecordEntitys =
  2741. // orderWXPayRecordService.getRecordsByOutTradeNo(order.getOrder_sn());
  2742. this.confirmPay(order.getId(), Dict.payFlag.item_alipay.getItem(), aliPayMicropayApiResult.getTradeNo());
  2743. // 设置支付单完成时间
  2744. processRecordEntity.setPaymentSuccTime(aliPayMicropayApiResult.getGmtPayment());
  2745. processRecordEntity.setPayTransactionId(aliPayMicropayApiResult.getTradeNo());
  2746. // 系统繁忙
  2747. } else if (AliPayUtil.AliPayTradeState.SERVER_FAIL.getCode().equals(aliPayMicropayApiResult.getCode())) {
  2748. LOGGER.info(aliPayMicropayApiResult.getSubMsg());
  2749. throw new RuntimeException(aliPayMicropayApiResult.getSubMsg() + ",请稍后再试");
  2750. // 支付失败
  2751. } else if (AliPayUtil.AliPayTradeState.BUSINESS_FAIL.getCode().equals(aliPayMicropayApiResult.getCode())) {
  2752. // 系统异常
  2753. if (AliPayUtil.BusinessFailState.SYSTEM_ERROR.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())) {
  2754. LOGGER.info(aliPayMicropayApiResult.getSubMsg());
  2755. throw new RuntimeException(aliPayMicropayApiResult.getSubMsg() + ",请稍后再试");
  2756. // 订单总额超过限额
  2757. } else if (AliPayUtil.BusinessFailState.TOTAL_FEE_EXCEED.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())) {
  2758. LOGGER.info(aliPayMicropayApiResult.getSubMsg());
  2759. throw new RuntimeException(aliPayMicropayApiResult.getSubMsg() + ",请告知顾客");
  2760. // 授权码无效
  2761. } else if (AliPayUtil.BusinessFailState.PAYMENT_AUTH_CODE_INVALID.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())) {
  2762. LOGGER.info(aliPayMicropayApiResult.getSubMsg());
  2763. throw new RuntimeException(aliPayMicropayApiResult.getSubMsg() + ",请顾客刷新条码后,重新支付");
  2764. // 交易信息被篡改
  2765. } else if (AliPayUtil.BusinessFailState.CONTEXT_INCONSISTENT.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())) {
  2766. LOGGER.info(aliPayMicropayApiResult.getSubMsg());
  2767. throw new RuntimeException(aliPayMicropayApiResult.getSubMsg() + ",请重试");
  2768. // 余额支付功能关闭
  2769. } else if (AliPayUtil.BusinessFailState.ERROR_BALANCE_PAYMENT_DISABLE.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())) {
  2770. LOGGER.info(aliPayMicropayApiResult.getSubMsg());
  2771. throw new RuntimeException(aliPayMicropayApiResult.getSubMsg() + ",请用户打开余额支付");
  2772. // 交易买家不匹配
  2773. } else if (AliPayUtil.BusinessFailState.TRADE_BUYER_NOT_MATCH.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())) {
  2774. LOGGER.info(aliPayMicropayApiResult.getSubMsg());
  2775. throw new RuntimeException(aliPayMicropayApiResult.getSubMsg() + ",请重试");
  2776. // 买家状态非法
  2777. } else if (AliPayUtil.BusinessFailState.BUYER_ENABLE_STATUS_FORBID.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())) {
  2778. LOGGER.info(aliPayMicropayApiResult.getSubMsg());
  2779. throw new RuntimeException(aliPayMicropayApiResult.getSubMsg() + ",请买家联系支付宝小二,确认为什么非法");
  2780. // 唤起移动收银台失败
  2781. } else if (AliPayUtil.BusinessFailState.PULL_MOBILE_CASHIER_FAIL.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())) {
  2782. LOGGER.info(aliPayMicropayApiResult.getSubMsg());
  2783. throw new RuntimeException(aliPayMicropayApiResult.getSubMsg() + ",请用户刷新条码后,重新支付");
  2784. // 用户的无限支付开关关闭
  2785. } else if (AliPayUtil.BusinessFailState.MOBILE_PAYMENT_SWITCH_OFF.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())) {
  2786. LOGGER.info(aliPayMicropayApiResult.getSubMsg());
  2787. throw new RuntimeException(aliPayMicropayApiResult.getSubMsg() + ",请用户在PC上打开无线支付开关后,在发起支付");
  2788. // 支付失败
  2789. } else if (AliPayUtil.BusinessFailState.PAYMENT_FAIL.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())) {
  2790. LOGGER.info(aliPayMicropayApiResult.getSubMsg());
  2791. throw new RuntimeException(aliPayMicropayApiResult.getSubMsg() + ",请重试");
  2792. // 商户账号被冻结
  2793. } else if (AliPayUtil.BusinessFailState.SELLER_BEEN_BLOCKED.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())) {
  2794. LOGGER.info(aliPayMicropayApiResult.getSubMsg());
  2795. throw new RuntimeException(aliPayMicropayApiResult.getSubMsg() + ",请联系支付宝小二解冻");
  2796. // 买家未通过人行认证
  2797. } else if (AliPayUtil.BusinessFailState.ERROR_BUYER_CERTIFY_LEVEL_LIMIT.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())) {
  2798. LOGGER.info(aliPayMicropayApiResult.getSubMsg());
  2799. throw new RuntimeException(aliPayMicropayApiResult.getSubMsg() + ",请买家联系支付宝小二");
  2800. // 用户当面付付款开关管壁
  2801. } else if (AliPayUtil.BusinessFailState.USER_FACE_PAYMENT_SWITCH_OFF.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())) {
  2802. LOGGER.info(aliPayMicropayApiResult.getSubMsg());
  2803. throw new RuntimeException(aliPayMicropayApiResult.getSubMsg() + ",请买家打开当面付付款开关");
  2804. } else {
  2805. LOGGER.info(aliPayMicropayApiResult.getSubMsg());
  2806. throw new RuntimeException(aliPayMicropayApiResult.getSubMsg());
  2807. }
  2808. // 其他支付异常状态
  2809. } else {
  2810. LOGGER.info(aliPayMicropayApiResult.getSubMsg());
  2811. throw new RuntimeException(aliPayMicropayApiResult.getSubMsg() + "...........请联系管理员");
  2812. }
  2813. }
  2814. private void wxPay(SysUserEntity user, String parCode, Map resultObj, OrderVo order, OrderProcessRecordEntity processRecordEntity, OrderWXPayRecordEntity orderWXPayRecordCurrent, StoreEntity store) throws ParseException {
  2815. R r;
  2816. String ip = "127.0.0.1";
  2817. try {
  2818. InetAddress ia = InetAddress.getLocalHost();
  2819. // String localname=ia.getHostName();
  2820. ip = ia.getHostAddress();
  2821. } catch (Exception e) {
  2822. e.printStackTrace();
  2823. }
  2824. WechatMicropayApiResult wechatMicropayApiResult = WechatUtil
  2825. .wxMicropay(store.getMerchName() + "-" + store.getStoreName(), order.getOrderBizType(), null,
  2826. orderWXPayRecordCurrent.getOutTradeNoWX(), order.getActual_price().doubleValue(),
  2827. ip, parCode);
  2828. orderWXPayRecordService.updateRecord(orderWXPayRecordCurrent.getId(), wechatMicropayApiResult);
  2829. resultObj.put("shopName", store.getStoreName()); // 根据门店编号查询
  2830. resultObj.put("userName", user.getUsername());
  2831. // 修改订单状态
  2832. //当支付成功时,修改订单,并把其他支付记录撤销
  2833. if (WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatMicropayApiResult.getTrade_state())) {
  2834. //查询当前订单所有的支付记录
  2835. List<OrderWXPayRecordEntity> orderWXPayRecordEntitys =
  2836. orderWXPayRecordService.getRecordsByOutTradeNo(order.getOrder_sn());
  2837. LOGGER.info("wechatMicropayApiResult.getTransaction_id()" + wechatMicropayApiResult.getTransaction_id());
  2838. Map orderRaram = Maps.newHashMap();
  2839. orderRaram.put("payTransactionId", wechatMicropayApiResult.getTransaction_id());
  2840. orderRaram.put("orderId", order.getId());
  2841. orderDao.updateOrderInfo(orderRaram);
  2842. this.confirmPay(order.getId(), Dict.payFlag.item_weixin.getItem(), orderWXPayRecordCurrent.getOutTradeNoWX());
  2843. // 设置支付单完成时间
  2844. processRecordEntity.setPaymentSuccTimeStr(wechatMicropayApiResult.getTime_end());
  2845. processRecordEntity.setPaymentSuccTime(
  2846. new SimpleDateFormat("yyyyMMddHHmmss").parse(wechatMicropayApiResult.getTime_end()));
  2847. processRecordEntity.setPayTransactionId(wechatMicropayApiResult.getTransaction_id());
  2848. //用户支付中
  2849. } else if (WechatUtil.WXTradeState.USERPAYING.getCode().equals(wechatMicropayApiResult.getTrade_state())) {
  2850. r = R.error(WechatUtil.WXTradeState.USERPAYING.getCodeZn() + ",稍等片刻后请刷新页面重新查看订单状态");
  2851. int times = 0;
  2852. // 查询是否支付了
  2853. while (true) {
  2854. boolean flag = orderQuery(order, processRecordEntity);
  2855. if (flag) {
  2856. break;
  2857. }
  2858. try {
  2859. Thread.currentThread().sleep(1000);
  2860. } catch (InterruptedException e) {
  2861. e.printStackTrace();
  2862. }
  2863. if (times >= 60) {
  2864. throw new RuntimeException("超过60s未支付,订单下单失败");
  2865. }
  2866. times++;
  2867. }
  2868. //用户支付失败
  2869. } else if (WechatUtil.WXTradeState.PAYERROR.getCode().equals(wechatMicropayApiResult.getTrade_state())) {
  2870. WechatReverseApiResult wechatReverseApiResult =
  2871. WechatUtil.wxReverse(orderWXPayRecordCurrent.getOutTradeNoWX());
  2872. //撤销订单成功
  2873. if (WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatReverseApiResult.getReturn_code()) &&
  2874. WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatReverseApiResult.getResult_code())) {
  2875. //调用订单查询接口
  2876. WechatRefundApiResult wechatRefundApiResult =
  2877. WechatUtil.wxOrderQuery(orderWXPayRecordCurrent.getOutTradeNoWX());
  2878. if (WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatRefundApiResult.getReturn_code()) &&
  2879. WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatRefundApiResult.getResult_code())) {
  2880. // 修改订单支付记录
  2881. orderWXPayRecordService
  2882. .updateWXPayRecordTradeState(orderWXPayRecordCurrent.getId(), wechatRefundApiResult);
  2883. }
  2884. r = R.error(orderWXPayRecordCurrent.getErrCodeDes());
  2885. } else {
  2886. r = R.error(wechatReverseApiResult.getErr_code_des());
  2887. }
  2888. throw new RuntimeException("订单支付失败");
  2889. } else {
  2890. throw new RuntimeException("未支付或支付失败,请联系管理员");
  2891. }
  2892. }
  2893. private boolean orderQuery(OrderVo order, OrderProcessRecordEntity processRecordEntity) {
  2894. LOGGER.info(">>>>>>>>>>>>>>>>>>>>wxOrderQuery 微信查询接口调用");
  2895. String merchOrderSn = order.getMerchOrderSn();
  2896. String orderId = order.getId() + "";
  2897. String orderSn = order.getOrder_sn();
  2898. WechatRefundApiResult result = WechatUtil.wxOrderQuery(orderSn);
  2899. if (result.getReturn_code().equalsIgnoreCase(WechatUtil.WXTradeState.SUCCESS.getCode())) {
  2900. if (result.getResult_code().equalsIgnoreCase(WechatUtil.WXTradeState.SUCCESS.getCode())) {
  2901. if (result.getTrade_state().equalsIgnoreCase(Dict.tradeState.item_SUCCESS.getItem())) {
  2902. Date successTime = DateUtils.convertStringToDate(result.getTime_end(),
  2903. DateUtils.DATE_TIME_PATTERN_YYYY_MM_DD_HH_MM_SS);
  2904. Map orderRaram = Maps.newHashMap();
  2905. orderRaram.put("payStatus", Dict.payStatus.item_2.getItem());//已支付
  2906. orderRaram.put("orderStatus", Dict.orderStatus.item_201.getItem());//已支付
  2907. orderRaram.put("payTransactionId", result.getTransaction_id());
  2908. orderRaram.put("payTime", successTime);
  2909. orderRaram.put("orderId", orderId);
  2910. orderRaram.put("payFlag", Dict.payFlag.item_weixin.getItem());
  2911. orderDao.updateOrderInfo(orderRaram);
  2912. Map processParam = Maps.newHashMap();
  2913. processParam.put("payTime", successTime);
  2914. processParam.put("orderSn", orderSn);
  2915. orderDao.updateOrderProcessRecord(processParam);
  2916. // orderWXPayRecordService
  2917. // .updateWXPayRecordTradeState(orderWXPayRecordTemp.getId(), wechatRefundApiResult);
  2918. // 设置支付单完成时间
  2919. processRecordEntity.setPaymentSuccTimeStr(result.getTime_end());
  2920. processRecordEntity.setPaymentSuccTime(successTime);
  2921. processRecordEntity.setPayTransactionId(result.getTransaction_id());
  2922. return true;
  2923. } else if (result.getTrade_state().equalsIgnoreCase(Dict.tradeState.item_NOTPAY.getItem())) {//订单未支付
  2924. Map orderRaram = Maps.newHashMap();
  2925. orderRaram.put("payStatus", Dict.payStatus.item_0.getItem());//支付状态未支付
  2926. orderRaram.put("orderStatus", Dict.orderStatus.item_0.getItem());//订单状态未支付
  2927. orderRaram.put("orderId", orderId);
  2928. orderDao.updateOrderInfo(orderRaram);
  2929. } else if (result.getTrade_state().equalsIgnoreCase(Dict.tradeState.item_CLOSED.getItem())) {
  2930. Map orderRaram = Maps.newHashMap();
  2931. orderRaram.put("payStatus", Dict.payStatus.item_7.getItem());
  2932. orderRaram.put("orderStatus", Dict.orderStatus.item_500.getItem());
  2933. orderRaram.put("orderId", orderId);
  2934. orderDao.updateOrderInfo(orderRaram);
  2935. LOGGER.info(">>>>>>>>>>>>>>>>>>>>wxOrderByTransactionIdQueryUpdFail 根据支付单查询微信接口返回信息:state 【" + result.getTrade_state() +
  2936. "】,des【" + result.getTrade_state_desc() + "】");
  2937. return false;
  2938. } else if (result.getTrade_state().equalsIgnoreCase(Dict.tradeState.item_PAYERROR.getItem())) {
  2939. Map orderRaram = Maps.newHashMap();
  2940. orderRaram.put("payStatus", Dict.payStatus.item_8.getItem());
  2941. orderRaram.put("orderStatus", Dict.orderStatus.item_501.getItem());
  2942. orderRaram.put("orderId", orderId);
  2943. orderDao.updateOrderInfo(orderRaram);
  2944. LOGGER.info(">>>>>>>>>>>>>>>>>>>>wxOrderByTransactionIdQueryUpdFail 根据支付单查询微信接口返回信息:state 【" + result.getTrade_state() +
  2945. "】,des【" + result.getTrade_state_desc() + "】");
  2946. return false;
  2947. } else if (result.getTrade_state().equalsIgnoreCase(Dict.tradeState.item_USERPAYING.getItem())) {
  2948. Map orderRaram = Maps.newHashMap();
  2949. orderRaram.put("payStatus", Dict.payStatus.item_1.getItem());
  2950. orderRaram.put("orderStatus", Dict.orderStatus.item_100.getItem());
  2951. orderRaram.put("orderId", orderId);
  2952. orderDao.updateOrderInfo(orderRaram);
  2953. LOGGER.info(">>>>>>>>>>>>>>>>>>>>wxOrderByTransactionIdQueryUpdFail 根据支付单查询微信接口返回信息:state 【" + result.getTrade_state() +
  2954. "】,des【" + result.getTrade_state_desc() + "】");
  2955. } else if (result.getTrade_state().equalsIgnoreCase(Dict.tradeState.item_REVOKED.getItem())) {
  2956. LOGGER.info(">>>>>>>>>>>>>>>>>>>>wxOrderByTransactionIdQueryUpdFail 根据支付单查询微信接口返回信息:state 【" + result.getTrade_state() +
  2957. "】,des【" + result.getTrade_state_desc() + "】");
  2958. return false;
  2959. }
  2960. } else {
  2961. LOGGER.info(">>>>>>>>>>>>>>>>>>>>wxOrderQuery 微信查询接口返回失败信息:code 【" + result.getErr_code() +
  2962. "】,des【" + result.getErr_code_des() + "】");
  2963. }
  2964. return false;
  2965. } else {
  2966. LOGGER.info(">>>>>>>>>>>>>>>>>>>>wxOrderQuery 微信查询接口调用失败: " + result.getReturn_msg());
  2967. return false;
  2968. }
  2969. }
  2970. @Override
  2971. public OrderEntity queryObjectByOrderSn(String orderSn) {
  2972. return orderDao.queryObjectByOrderSn(orderSn);
  2973. }
  2974. ExecutorService service = Executors.newSingleThreadExecutor();
  2975. // 收银端退款的代码
  2976. @Override
  2977. @Transactional
  2978. public synchronized R orderRefund(OrderEntity order, String sessionId, SysUserEntity user) throws Exception {
  2979. OrderEntity orderInfo = order;
  2980. if (null == orderInfo) {
  2981. return R.error("订单不存在");
  2982. }
  2983. if (orderInfo.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_401.getItem()) ||
  2984. orderInfo.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_402.getItem())) {
  2985. return R.error("订单已退款");
  2986. }
  2987. if (orderInfo.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_0.getItem())) {
  2988. return R.error("订单正在准备,请稍等!");
  2989. }
  2990. if (orderInfo.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_100.getItem())) {
  2991. return R.error("订单尚未支付完成,无法进行退款!");
  2992. }
  2993. if (orderInfo.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_101.getItem())) {
  2994. return R.error("订单尚未支付完成,无法进行退款!");
  2995. }
  2996. if (orderInfo.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_102.getItem())) {
  2997. return R.error("订单尚未支付完成,无法进行退款!");
  2998. }
  2999. String payFlag = order.getPayFlag();
  3000. String key = "kmall_order_refund_" + order.getOrderSn();
  3001. if (JedisUtil.exists(key)) {
  3002. return R.error("订单退款操作过快,请等待!");
  3003. }
  3004. JedisUtil.set(key, System.currentTimeMillis() + "", 3);
  3005. if (orderInfo.getPayStatus() == Integer.parseInt(Dict.payStatus.item_3.getItem())) {
  3006. return R.error("订单正在退款中,请勿重复退款");
  3007. }
  3008. CountDownLatch cdl = new CountDownLatch(1);
  3009. service.submit(()-> {
  3010. try {
  3011. orderDao.updateOrderRefunding(order.getId());
  3012. } finally {
  3013. cdl.countDown();
  3014. }
  3015. });
  3016. cdl.await();
  3017. if (Dict.payFlag.item_weixin.getItem().equals(payFlag)) {
  3018. Double totalActualPrice = orderDao.getTotalActualPrice(orderInfo.getMerchOrderSn());
  3019. if (totalActualPrice == null) {
  3020. totalActualPrice = 0d;
  3021. }
  3022. String refundResult = "";
  3023. if (orderInfo.getOrderStatus() != Integer.parseInt(Dict.orderStatus.item_0.getItem())) {
  3024. LOGGER.info("微信退款开始");
  3025. WechatRefundApiResult result = WechatUtil.wxRefund(orderInfo.getOrderSn().toString(), totalActualPrice,
  3026. orderInfo.getActualPrice().doubleValue());
  3027. OrderRefundEntity orderRefund = new OrderRefundEntity();
  3028. orderRefund.setRefundId(result.getRefund_id());
  3029. orderRefund.setOutRefundNo(result.getOut_trade_no());
  3030. orderRefund.setRefundMoney(BigDecimal.valueOf(Long.valueOf(result.getRefund_fee())).divide(Constant.ONE_HUNDRED));
  3031. orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_2.getItem()));//退款处理中
  3032. orderRefund.setModTime(new Date());
  3033. orderRefund.setRefundTime(new Date());
  3034. orderRefund.setOrderId(Integer.parseInt(order.getId() + ""));
  3035. orderRefund.setUserId(user.getUserId().intValue());
  3036. orderRefund.setRefundId(order.getUserId() + "");
  3037. orderRefund.setCreateTime(new Date());
  3038. List<OrderEntity> list = orderDao.queryObjectByMerchOrderSn(order.getMerchOrderSn());
  3039. if (list.size() > 1) {//多条订单
  3040. orderRefund.setRefundType(Integer.parseInt(Dict.RefundType.item_2.getItem()));//部分退款
  3041. } else {
  3042. orderRefund.setRefundType(Integer.parseInt(Dict.RefundType.item_1.getItem()));//用户全额退款
  3043. }
  3044. order.setPayStatus(Integer.parseInt(Dict.payStatus.item_5.getItem()));
  3045. order.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_401.getItem()));
  3046. LOGGER.info("微信退款");
  3047. orderDao.update(order);//修改为退款成功
  3048. // 修改小票码
  3049. PickUpCodeEntity pickUpCodeEntity = pickUpCodeService.queryObject(order.getOrderSn());
  3050. pickUpCodeEntity.setPickUpCodeStatus("3");
  3051. pickUpCodeService.update(pickUpCodeEntity);
  3052. //调用免税mall接口退款
  3053. //HttpUtil.doPostJson()
  3054. restoreInventoryMsMall(order);
  3055. orderRefund.setRestore(1);
  3056. orderRefundDao.save(orderRefund);//退款记录
  3057. }
  3058. // 支付宝的退款代码
  3059. } else if (Dict.payFlag.item_alipay.getItem().equals(payFlag)) {
  3060. AliPayMicropayApiResult userRefund = AliPayUtil.aliTradeRefund(order.getOrderSn(), order.getActualPrice().toString(),
  3061. "用户退款", order.getStoreId() + "");
  3062. // 是否已退款校验
  3063. try {
  3064. String fundChange = userRefund.getFundChange();
  3065. if ("N".equals(fundChange)) {
  3066. return R.error("资金已退回,请勿重复退款!");
  3067. }
  3068. } catch (Exception e) {
  3069. LOGGER.error("[支付宝退款校验出错]",e.getMessage());
  3070. }
  3071. LOGGER.info(userRefund.getSubMsg());
  3072. OrderRefundEntity orderRefund = new OrderRefundEntity();
  3073. orderRefund.setRefundId(userRefund.getTradeNo());
  3074. orderRefund.setOutRefundNo(userRefund.getOutTradeNo());
  3075. orderRefund.setRefundMoney(new BigDecimal(userRefund.getRefundFee()));
  3076. orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_2.getItem()));//退款成功
  3077. orderRefund.setModTime(new Date());
  3078. orderRefund.setRefundTime(new Date());
  3079. orderRefund.setOrderId(Integer.parseInt(order.getId() + ""));
  3080. orderRefund.setUserId(user.getUserId().intValue());
  3081. orderRefund.setRefundId(order.getUserId() + "");
  3082. orderRefund.setCreateTime(new Date());
  3083. List<OrderEntity> list = orderDao.queryObjectByMerchOrderSn(order.getMerchOrderSn());
  3084. if (list.size() > 1) {//多条订单
  3085. orderRefund.setRefundType(Integer.parseInt(Dict.RefundType.item_2.getItem()));//部分退款
  3086. } else {
  3087. orderRefund.setRefundType(Integer.parseInt(Dict.RefundType.item_1.getItem()));//用户全额退款
  3088. }
  3089. order.setPayStatus(Integer.parseInt(Dict.payStatus.item_5.getItem()));
  3090. order.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_401.getItem()));
  3091. orderDao.update(order);//修改为退款成功
  3092. // 修改小票码
  3093. PickUpCodeEntity pickUpCodeEntity = pickUpCodeService.queryObject(order.getOrderSn());
  3094. pickUpCodeEntity.setPickUpCodeStatus("3");
  3095. pickUpCodeService.update(pickUpCodeEntity);
  3096. //调用免税mall接口退款
  3097. restoreInventoryMsMall(order);
  3098. orderRefund.setRestore(1);
  3099. orderRefundDao.save(orderRefund);//退款记录
  3100. }
  3101. return R.ok("退款成功");
  3102. }
  3103. /**
  3104. * 海控订单退款
  3105. * @param order
  3106. */
  3107. private void restoreInventoryMsMall(OrderEntity order) {
  3108. //调用CCNET接口
  3109. String msg = OkHttpUtils.post(JSON.toJSONString(order),OmsMerchPropertiesBuilder.instance().getWxOrderResendUrl() + "/refundOrder",JSON.toJSONString(order),"SSL");
  3110. ResponseData responseData = JacksonUtils.fromStringJson(msg, ResponseData.class);
  3111. if(responseData.getCode().equalsIgnoreCase("0")) {
  3112. Map<String, Object> map = new HashMap();
  3113. SysUserEntity user = ShiroUtils.getUserEntity();
  3114. map.put("orderId", order.getId());
  3115. List<OrderGoodsEntity> orderGoodsVoList = orderGoodsDao.queryList(map);
  3116. for (OrderGoodsEntity orderGoodsEntity : orderGoodsVoList) {
  3117. ProductStoreRelaEntity storeRelaEntity = productStoreRelaDao
  3118. .queryByGoodsIdAndStoreId(order.getStoreId().longValue(), orderGoodsEntity.getGoodsId().longValue());
  3119. if (null == storeRelaEntity || null == storeRelaEntity.getSellVolume()) {
  3120. storeRelaEntity.setSellVolume(0);
  3121. }
  3122. BigDecimal sellVolume = new BigDecimal(storeRelaEntity.getSellVolume() - orderGoodsEntity.getNumber());//销售量
  3123. if (sellVolume.compareTo(Constant.ZERO) < 0) {
  3124. sellVolume = Constant.ZERO;
  3125. }
  3126. //还原门店库存
  3127. if (null != storeRelaEntity.getStockNum()) {
  3128. Integer stockNum = storeRelaEntity.getStockNum();
  3129. resetStoreGoodsStock(stockNum, storeRelaEntity, orderGoodsEntity, sellVolume, responseData.getCode(), user);
  3130. }
  3131. }
  3132. }else{
  3133. LOGGER.error(order.getOrderSn()+"[该订单退款失败]"+JSON.toJSONString(order));
  3134. }
  3135. }
  3136. @Transactional
  3137. public void toBeRestoreInventory(OrderEntity order) {
  3138. Map<String, Object> map = new HashMap();
  3139. SysUserEntity user = ShiroUtils.getUserEntity();
  3140. map.put("orderId", order.getId());
  3141. List<OrderGoodsEntity> orderGoodsVoList = orderGoodsDao.queryList(map);
  3142. for (OrderGoodsEntity orderGoodsEntity : orderGoodsVoList) {
  3143. // 当前订单商品数量
  3144. Integer restoreNumber = orderGoodsEntity.getNumber();
  3145. ProductStoreRelaEntity storeRelaEntity = productStoreRelaDao
  3146. .queryByGoodsIdAndStoreId(order.getStoreId().longValue(), orderGoodsEntity.getGoodsId().longValue());
  3147. Integer toBeRestored = storeRelaEntity.getToBeRestored();
  3148. if (toBeRestored == null) {
  3149. toBeRestored = 0;
  3150. }
  3151. // 修改门店商品待退款的数量 = 当前订单商品数量 + 门店待退款数量
  3152. storeRelaEntity.setToBeRestored(toBeRestored + restoreNumber);
  3153. GoodsEntity goodsEntity = goodsDao.queryObject(orderGoodsEntity.getGoodsId());
  3154. toBeRestored = goodsEntity.getToBeRestored();
  3155. if (toBeRestored == null) {
  3156. toBeRestored = 0;
  3157. }
  3158. goodsEntity.setToBeRestored(toBeRestored + restoreNumber);
  3159. productStoreRelaDao.update(storeRelaEntity);
  3160. goodsDao.update(goodsEntity);
  3161. }
  3162. }
  3163. /**
  3164. * 查询oms系统是否有该订单
  3165. *
  3166. * @param orderSn
  3167. * @return
  3168. */
  3169. private boolean arrivedOms(String orderSn) {
  3170. Map<String, String> sParaTemp = new TreeMap<String, String>();
  3171. // sParaTemp.put("data","ZWCW2020122749351849");
  3172. sParaTemp.put("data", orderSn);
  3173. sParaTemp.put("merchId", omsMerchProperties.getMerchSn());
  3174. String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
  3175. sParaTemp.put("timestamp", timestamp);
  3176. //生成要请求给oms秘钥
  3177. // String sign = OmsSign.sign(sParaTemp,cus.getWaybill().get("secret-key"));
  3178. LOGGER.info("md5混淆码参数:" + omsMerchProperties.getMd5Salt());
  3179. String sign = OmsSign.sign(sParaTemp, omsMerchProperties.getMd5Salt());
  3180. sParaTemp.put("sign", sign);
  3181. //构建Request
  3182. String url = omsMerchProperties.getQueryInveResponseUrl();
  3183. Request request = com.kmall.admin.utils.oms.OkHttpUtils.buildRequest(url, JSON.toJSONString(sParaTemp));
  3184. LOGGER.info("oms的请求报文:" + request);
  3185. // 同步访问,返回结果字符串
  3186. String responseString = null;
  3187. try {
  3188. responseString = com.kmall.admin.utils.oms.OkHttpUtils.post(request);
  3189. } catch (Exception e) {
  3190. e.printStackTrace();
  3191. }
  3192. LOGGER.info("oms的响应报文" + responseString);
  3193. //解析响应数据
  3194. Gson gson = new Gson();
  3195. ResponseMessage result = gson.fromJson(responseString, ResponseMessage.class);
  3196. if (result == null) {
  3197. String info = "解析响应数据Result失败";
  3198. LOGGER.error("--- {}", info);
  3199. throw new RuntimeException(info);
  3200. }
  3201. if ("oms无该订单".equals(result.getMsg())) {
  3202. return false;
  3203. }
  3204. return true;
  3205. }
  3206. private String wxRefund(OrderEntity orderInfo, Double totalActualPrice) {
  3207. WechatRefundApiResult result = WechatUtil.wxRefund(orderInfo.getOrderSn().toString(), totalActualPrice,
  3208. orderInfo.getActualPrice().doubleValue());
  3209. if (result.getResult_code().equals(WechatUtil.WXTradeState.SUCCESS.getCode())) {
  3210. refund(orderInfo, result);
  3211. } else {
  3212. OrderRefundEntity mallOrderRefund = orderRefundService.queryObjectByOrderId(orderInfo.getId());
  3213. OrderRefundEntity orderRefund = new OrderRefundEntity();
  3214. orderRefund.setRefundType(Integer.parseInt(Dict.RefundType.item_1.getItem()));
  3215. orderRefund.setRefundMoney(BigDecimal.valueOf(orderInfo.getActualPrice().doubleValue()));
  3216. orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_4.getItem()));
  3217. SysUserEntity user = ShiroUtils.getUserEntity();
  3218. orderRefund.setModerSn(user.getUsername());
  3219. orderRefund.setModTime(new Date());
  3220. // orderRefund.setOutRefundNo(result.getOut_refund_no());
  3221. if (mallOrderRefund != null) {
  3222. orderRefund.setId(mallOrderRefund.getId());
  3223. orderRefundService.update(orderRefund);//退款记录
  3224. }
  3225. OrderExceptionRecordEntity mallOrderExceptionRecord = new OrderExceptionRecordEntity();
  3226. mallOrderExceptionRecord.setOrderSn(orderInfo.getOrderSn());
  3227. mallOrderExceptionRecord.setUserId(Integer.parseInt(orderInfo.getUserId() + ""));
  3228. mallOrderExceptionRecord.setExceptionStatus(Dict.exceptionStatus.item_03.getItem());
  3229. mallOrderExceptionRecord.setExceptionContent("退款失败" + result.getErr_code_des());
  3230. mallOrderExceptionRecord.setCreateTime(new Date());
  3231. orderExceptionRecordService.save(mallOrderExceptionRecord);
  3232. return result.getErr_code_des();
  3233. }
  3234. return "";
  3235. }
  3236. @Override
  3237. public int queryOffilineOrderTotal(Query query) {
  3238. return orderDao.queryOffilineOrderTotal(query);
  3239. }
  3240. @Override
  3241. public List<PurchaseSalesInStockDetail> purchaseSalesInStockDetailList(Query query) {
  3242. return orderDao.purchaseSalesInStockDetailList(query);
  3243. }
  3244. @Override
  3245. public int purchaseSalesInStockDetailTotal(Query query) {
  3246. return orderDao.purchaseSalesInStockDetailTotal(query);
  3247. }
  3248. @Override
  3249. public List<OrderEntity> queryExportOffilineOrderList(Map<String, Object> params) {
  3250. List<OrderEntity> orderEntityList = orderDao.queryExportOffilineOrderList(params);
  3251. // if (orderEntityList!=null && orderEntityList.size()>0){
  3252. // for (OrderEntity orderEntity : orderEntityList) {
  3253. // // 查询活动价
  3254. // BigDecimal topicPrice = orderDao.queryTopicPriceByOrderSnAndSku(orderEntity.getOrderSn(),orderEntity.getSku());
  3255. // orderEntity.setTopicPrice(topicPrice);
  3256. // }
  3257. // }
  3258. return orderEntityList;
  3259. }
  3260. @Override
  3261. public List<OrderEntity> queryMasterExportOffilineOrderList(Map<String, Object> params) {
  3262. return orderDao.queryMasterExportOffilineOrderList(params);
  3263. }
  3264. @Override
  3265. public List<OrderEntity> queryMasterExportList(Map<String, Object> params) {
  3266. return orderDao.queryMasterExportList(params);
  3267. }
  3268. @Override
  3269. public List<SystemFormatDto> queryExportSystemFormatList(Map<String, Object> params) {
  3270. List<SystemFormatDto> systemFormatList = orderDao.queryExportSystemFormatList(params);
  3271. return systemFormatList;
  3272. }
  3273. @Override
  3274. public List<OrderEntity> queryLastDayOrder(String comparedDate) {
  3275. Map<String, Object> map = new HashMap<>();
  3276. //
  3277. // DateFormat dateFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//格式化一下时间
  3278. //
  3279. // Date dNow = new Date(); //当前时间
  3280. //
  3281. // Date dBefore = new Date();
  3282. //
  3283. // Calendar calendar = Calendar.getInstance(); //得到日历
  3284. //
  3285. // calendar.setTime(dNow);//把当前时间赋给日历
  3286. //
  3287. // calendar.add(Calendar.DAY_OF_MONTH, -1); //设置为前一天
  3288. //
  3289. // dBefore = calendar.getTime(); //得到前一天的时间
  3290. String defaultStartDate = comparedDate + " 00:00:00";
  3291. String defaultEndDate = comparedDate + " 23:59:59";
  3292. map.put("startTime", defaultStartDate);
  3293. map.put("endTime", defaultEndDate);
  3294. return orderDao.queryOffilineOrderList(map);
  3295. }
  3296. /**
  3297. * 查询CW保税+新零售销售报表第一个sheet
  3298. *
  3299. * @param billDate
  3300. * @param storeId
  3301. * @return
  3302. */
  3303. @Override
  3304. public ExportExcelDto querySumAmount(String billDate, String storeId) {
  3305. ExportExcelDto exportExcelDto = new ExportExcelDto();
  3306. ExportExcelDto totalAmount = orderDao.totalAmount(billDate, storeId);
  3307. ExportExcelDto refundCurrentAmount = orderDao.refundCurrentAmount(billDate, storeId);
  3308. ExportExcelDto refundPreviousAmount = orderDao.refundPreviousAmount(billDate, storeId);
  3309. ExportExcelDto currentTax = orderDao.currentTax(billDate, storeId);
  3310. ExportExcelDto refundPreviousTax = orderDao.refundPreviousTax(billDate, storeId);
  3311. // 以下是直接从数据库中查出来的
  3312. exportExcelDto.setTotalAmount(totalAmount.getTotalAmount()); // 总销售额
  3313. exportExcelDto.setTotalCount(totalAmount.getTotalCount()); // 总销售数
  3314. exportExcelDto.setRefundCurrentAmount(refundCurrentAmount.getRefundCurrentAmount()); // 当期退款额
  3315. exportExcelDto.setRefundCurrentCount(refundCurrentAmount.getRefundCurrentCount()); // 当期退款数
  3316. exportExcelDto.setRefundPreviousAmount(refundPreviousAmount.getRefundPreviousAmount()); // 退前期销售额
  3317. exportExcelDto.setRefundPreviousCount(refundPreviousAmount.getRefundPreviousCount()); // 退前期销售数
  3318. exportExcelDto.setCurrentTax(currentTax.getCurrentTax()); // 当前税额
  3319. exportExcelDto.setPreviousTax(refundPreviousTax.getPreviousTax()); // 前期税额
  3320. // 以下是通过计算的出来的
  3321. // 销售净额
  3322. exportExcelDto.setNetAmount(new BigDecimal(exportExcelDto.getTotalAmount()).subtract(new BigDecimal(exportExcelDto.getRefundPreviousAmount())).setScale(2, RoundingMode.HALF_UP).toString());
  3323. // 总税额
  3324. exportExcelDto.setTotalTax(new BigDecimal(exportExcelDto.getCurrentTax()).add(new BigDecimal(exportExcelDto.getPreviousTax())).setScale(2, RoundingMode.HALF_UP).toString());
  3325. // 税前总额
  3326. exportExcelDto.setPreTaxTotalAmount(new BigDecimal(exportExcelDto.getNetAmount()).subtract(new BigDecimal(exportExcelDto.getTotalTax())).setScale(2, RoundingMode.HALF_UP).toString());
  3327. // 成功单数
  3328. exportExcelDto.setSuccessNumber(new BigDecimal(exportExcelDto.getTotalCount()).subtract(new BigDecimal(exportExcelDto.getRefundPreviousCount())).setScale(2, RoundingMode.HALF_UP).toString());
  3329. // 退款总额
  3330. exportExcelDto.setRefundAmount(new BigDecimal(exportExcelDto.getRefundCurrentAmount()).add(new BigDecimal(exportExcelDto.getRefundPreviousAmount())).setScale(2, RoundingMode.HALF_UP).toString());
  3331. // 退单单数
  3332. exportExcelDto.setRefundCount(new BigDecimal(exportExcelDto.getRefundCurrentCount()).add(new BigDecimal(exportExcelDto.getRefundPreviousCount())).setScale(2, RoundingMode.HALF_UP).toString());
  3333. return exportExcelDto;
  3334. }
  3335. @Override
  3336. public Map<String, List<OrderEntity>> querySaleOrderList(String billDate, String storeId) {
  3337. Map<String, List<OrderEntity>> result = new HashMap<>();
  3338. // 查询当天所有订单
  3339. List<OrderEntity> orderEntityList = orderDao.queryCurrentPreviousOrderList(billDate, storeId);
  3340. result.put("current", orderEntityList);
  3341. // 查询当天退前期订单
  3342. List<OrderEntity> refundPreviousOrderList = orderDao.queryRefundPreviousOrderList(billDate, storeId);
  3343. result.put("previous", refundPreviousOrderList);
  3344. return result;
  3345. }
  3346. @Override
  3347. public Map<String, List<TaxDetailDto>> queryTaxDetailList(String billDate, String storeId) {
  3348. Map<String, List<TaxDetailDto>> result = new HashMap<>();
  3349. // 查询当天所有订单税单
  3350. List<TaxDetailDto> taxDetailList = orderDao.queryCurrentTaxDetailList(billDate, storeId);
  3351. // 计算税前价,增值税,消费税
  3352. BigDecimal discountRate = new BigDecimal(0.7);
  3353. if (taxDetailList != null && taxDetailList.size() != 0) {
  3354. for (TaxDetailDto taxDetailDto : taxDetailList) {
  3355. // 获取实际支付价格
  3356. String postTaxPrice = taxDetailDto.getPostTaxPrice();
  3357. // 获取总税额
  3358. String taxStr = taxDetailDto.getTax();
  3359. // 税前金额
  3360. BigDecimal tax = new BigDecimal(taxStr);
  3361. BigDecimal pretaxPrice = new BigDecimal(postTaxPrice).subtract(tax).setScale(2, RoundingMode.HALF_UP);
  3362. // 计算综合税率
  3363. BigDecimal taxRate = tax.divide(pretaxPrice, 4, RoundingMode.HALF_UP);
  3364. // 消费税率
  3365. BigDecimal saleTaxRate = new BigDecimal(taxDetailDto.getSaleTaxRate()).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
  3366. // 综合税率
  3367. BigDecimal vatRate = new BigDecimal(taxDetailDto.getVatRate()).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
  3368. // 消费税 = (明细商品总价 / (1-消费税税率)) * 消费税税率
  3369. // 增值税 = (明细商品总价 + 消费税) * 增值税税率
  3370. // 订单该商品总税费 = (商品消费税 + 商品增值税)* 0.7
  3371. // 如果大于,要算消费税
  3372. BigDecimal saleTax = new BigDecimal(0);
  3373. BigDecimal vat = new BigDecimal(0);
  3374. if (taxRate.compareTo(new BigDecimal("0.23")) > 0) {
  3375. saleTax = pretaxPrice.divide(new BigDecimal(1).subtract(saleTaxRate), 2, RoundingMode.HALF_UP).multiply(saleTaxRate).
  3376. setScale(2, RoundingMode.HALF_UP);
  3377. vat = pretaxPrice.add(saleTax).multiply(vatRate).
  3378. multiply(discountRate).setScale(2, RoundingMode.HALF_UP);
  3379. saleTax = saleTax.multiply(discountRate).setScale(2, RoundingMode.HALF_UP);
  3380. } else {
  3381. // 不需要算消费税,增值税计算
  3382. vat = pretaxPrice.multiply(vatRate).multiply(discountRate).setScale(2, RoundingMode.HALF_UP);
  3383. }
  3384. taxDetailDto.setSaleTax(saleTax.toString());
  3385. taxDetailDto.setVat(vat.toString());
  3386. }
  3387. }
  3388. result.put("current", taxDetailList);
  3389. // 查询当天退前期订单税单
  3390. List<TaxDetailDto> refundPrevioustaxDetailList = orderDao.queryRefundPreviousTaxDetailList(billDate, storeId);
  3391. // 计算税前价,增值税,消费税
  3392. if (refundPrevioustaxDetailList != null && refundPrevioustaxDetailList.size() != 0) {
  3393. for (TaxDetailDto taxDetailDto : refundPrevioustaxDetailList) {
  3394. // 获取实际支付价格
  3395. String postTaxPrice = taxDetailDto.getPostTaxPrice();
  3396. // 获取总税额
  3397. String taxStr = taxDetailDto.getPreTax();
  3398. // 税前金额
  3399. BigDecimal tax = new BigDecimal(taxStr);
  3400. BigDecimal pretaxPrice = new BigDecimal(postTaxPrice).subtract(tax).setScale(2, RoundingMode.HALF_UP);
  3401. // 计算综合税率
  3402. BigDecimal taxRate = tax.divide(pretaxPrice, 4, RoundingMode.HALF_UP);
  3403. // 消费税率
  3404. BigDecimal saleTaxRate = new BigDecimal(taxDetailDto.getPreSaleTax()).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
  3405. // 综合税率
  3406. BigDecimal vatRate = new BigDecimal(taxDetailDto.getPreVat()).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
  3407. // 消费税 = (明细商品总价 / (1-消费税税率)) * 消费税税率
  3408. // 增值税 = (明细商品总价 + 消费税) * 增值税税率
  3409. // 订单该商品总税费 = (商品消费税 + 商品增值税)* 0.7
  3410. // 如果大于,要算消费税
  3411. BigDecimal saleTax = new BigDecimal(0);
  3412. BigDecimal vat = new BigDecimal(0);
  3413. if (taxRate.compareTo(new BigDecimal("0.23")) > 0) {
  3414. saleTax = pretaxPrice.divide(new BigDecimal(1).subtract(saleTaxRate), 2, RoundingMode.HALF_UP).multiply(saleTaxRate).
  3415. multiply(discountRate).setScale(2, RoundingMode.HALF_UP);
  3416. vat = pretaxPrice.add(saleTax).multiply(vatRate).
  3417. multiply(discountRate).setScale(2, RoundingMode.HALF_UP);
  3418. } else {
  3419. // 不需要算消费税,增值税计算
  3420. vat = pretaxPrice.multiply(vatRate).multiply(discountRate).setScale(2, RoundingMode.HALF_UP);
  3421. }
  3422. taxDetailDto.setPreSaleTax(saleTax.compareTo(BigDecimal.ZERO) == 0 ? saleTax.toString() : "-" + saleTax.toString());
  3423. taxDetailDto.setPreVat(vat.compareTo(BigDecimal.ZERO) == 0 ? vat.toString() : "-" + vat.toString());
  3424. }
  3425. }
  3426. result.put("previous", refundPrevioustaxDetailList);
  3427. return result;
  3428. }
  3429. @Override
  3430. public List<String> queryInveResponse(String orderSn) throws IOException {
  3431. Map<String, String> sParaTemp = new TreeMap<String, String>();
  3432. sParaTemp.put("data", orderSn);
  3433. sParaTemp.put("merchId", omsMerchProperties.getMerchSn());
  3434. String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
  3435. sParaTemp.put("timestamp", timestamp);
  3436. //生成要请求给oms秘钥
  3437. // String sign = OmsSign.sign(sParaTemp,cus.getWaybill().get("secret-key"));
  3438. LOGGER.info("md5混淆码参数:" + omsMerchProperties.getMd5Salt());
  3439. String sign = OmsSign.sign(sParaTemp, omsMerchProperties.getMd5Salt());
  3440. sParaTemp.put("sign", sign);
  3441. //构建Request
  3442. String url = omsMerchProperties.getQueryInveResponseUrl();
  3443. Request request = com.kmall.admin.utils.oms.OkHttpUtils.buildRequest(url, JSON.toJSONString(sParaTemp));
  3444. LOGGER.info("oms的请求报文:" + request);
  3445. // 同步访问,返回结果字符串
  3446. String responseString = null;
  3447. try {
  3448. responseString = com.kmall.admin.utils.oms.OkHttpUtils.post(request);
  3449. } catch (Exception e) {
  3450. e.printStackTrace();
  3451. throw e;
  3452. }
  3453. LOGGER.info("oms的响应报文" + responseString);
  3454. //解析响应数据
  3455. Gson gson = new Gson();
  3456. ResponseMessage result = gson.fromJson(responseString, ResponseMessage.class);
  3457. if (result == null) {
  3458. String info = "解析响应数据Result失败";
  3459. LOGGER.error("--- {}", info);
  3460. throw new RuntimeException(info);
  3461. }
  3462. ResponseMessageData data = result.getData();
  3463. List rows = data.getRows();
  3464. List<String> resultMessage = new LinkedList<>();
  3465. for (Object row : rows) {
  3466. if (row instanceof ArrayList) {
  3467. for (Object o : ((ArrayList<?>) row)) {
  3468. if (o instanceof LinkedTreeMap) {
  3469. String cusReturnInfo = (String) ((LinkedTreeMap<?, ?>) o).get("cusReturnInfo");
  3470. resultMessage.add(cusReturnInfo);
  3471. }
  3472. }
  3473. }
  3474. }
  3475. // cusReturnInfo -> [Code:2600;Desc:放行]
  3476. return resultMessage;
  3477. }
  3478. /**
  3479. * 查询所有状态为201的订单。且下单时间超过5分钟的订单
  3480. *
  3481. * @return
  3482. */
  3483. @Override
  3484. public List<OrderEntity> queryAll201Order() {
  3485. SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
  3486. String date = format.format(new Date());
  3487. return orderDao.queryAll201Order(date);
  3488. }
  3489. /**
  3490. * 恢复kmall退单冻结的库存
  3491. *
  3492. * @param orderSn
  3493. */
  3494. @Override
  3495. @Transactional
  3496. public void toBeRestored(String orderSn) {
  3497. // 查询该订单在库存是否已经释放过,避免重复恢复库存
  3498. OrderEntity orderInfo = orderDao.queryObjectByOrderSn(orderSn);
  3499. OrderRefundEntity orderRefundEntity = orderRefundService.queryObjectByOrderId(orderInfo.getId());
  3500. if (orderRefundEntity == null) {
  3501. LOGGER.error("该订单无退款记录,订单号{}", orderSn);
  3502. throw new RuntimeException("该订单无退款记录,订单号:" + orderSn);
  3503. }
  3504. Integer restore = orderRefundEntity.getRestore();
  3505. if (restore == 1) {
  3506. LOGGER.error("该订单库存记录已恢复过,订单号{}", orderSn);
  3507. throw new RuntimeException("该订单库存记录已恢复过,订单号:" + orderSn);
  3508. }
  3509. restoreInventory(orderInfo, "oms退单成功,恢复库存");
  3510. orderRefundEntity.setRestore(1);
  3511. orderRefundService.update(orderRefundEntity);
  3512. }
  3513. @Override
  3514. public Ticket printMsgEwb(long id, String sessionId) {
  3515. OrderEntity orderEntity = queryInfos(id);
  3516. List<OrderGoodsEntity> orderGoodsEntityList = orderEntity.getOrderGoodsEntityList();
  3517. // 获取门店
  3518. StoreEntity storeEntity = storeDao.queryObject(orderEntity.getStoreId());
  3519. // 获取清关信息
  3520. OrderProcessRecordEntity orderProcessRecordEntity =
  3521. orderProcessRecordDao.queryObjectByOrderSn(orderEntity.getOrderSn());
  3522. // 小票头
  3523. TicketHead head = new TicketHead();
  3524. head.setTitle(storeEntity.getStoreName());
  3525. // head.setMemberId(orderEntity.getUserName().toString());
  3526. head.setOrderId(orderEntity.getOrderSn());
  3527. head.setTradeTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss EEE").format(orderEntity.getPayTime()));
  3528. // 商品信息
  3529. Integer goodsTotal = 0; // 商品总个数
  3530. BigDecimal total = Constant.ZERO; // 商品总计
  3531. BigDecimal taxTotal = Constant.ZERO; //税费总计
  3532. List<Goods> goodsList = new ArrayList<>();
  3533. BigDecimal discountedPrice = Constant.ZERO; // 优惠金额
  3534. for (OrderGoodsEntity orderGoods : orderGoodsEntityList) {
  3535. goodsTotal += orderGoods.getNumber();
  3536. total = total.add(orderGoods.getRetailPrice().multiply(new BigDecimal(orderGoods.getNumber())))
  3537. .setScale(2, BigDecimal.ROUND_HALF_UP);
  3538. discountedPrice = discountedPrice.add(orderGoods.getDiscountedPrice());
  3539. GoodsEntity goodsEntity = goodsService.queryObject(orderGoods.getGoodsId());
  3540. BigDecimal goodsTax = CalculateTax.calculateFinalTax(goodsEntity, orderGoods.getRetailPrice(), goodsService).setScale(3, RoundingMode.HALF_UP);
  3541. goodsTax = goodsTax.multiply(new BigDecimal(orderGoods.getNumber())).setScale(2, RoundingMode.HALF_UP);
  3542. taxTotal = taxTotal.add(goodsTax).setScale(2, RoundingMode.HALF_UP);
  3543. Goods goods = new Goods(orderGoods.getGoodsName(),
  3544. orderGoods.getRetailPrice().toString(), // 含税价
  3545. // beforeTaxPrice.toString(),// 税前价
  3546. goodsTax.toString(),
  3547. orderGoods.getNumber().toString(),
  3548. new BigDecimal(orderGoods.getNumber()).multiply(orderGoods.getRetailPrice()).setScale(2, RoundingMode.HALF_UP).toString(),
  3549. orderGoods.getDiscountedPrice().toString());
  3550. goodsList.add(goods);
  3551. }
  3552. // 收银信息
  3553. CashInfo cashInfo = new CashInfo();
  3554. cashInfo.setGoodsTotal(goodsTotal.toString());
  3555. cashInfo.setTotal(total.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
  3556. cashInfo.setTaxTotal(taxTotal.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
  3557. cashInfo.setReceipts(orderEntity.getActualPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
  3558. cashInfo.setOddChange(discountedPrice.toString());
  3559. cashInfo.setCoupon(orderEntity.getCouponPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
  3560. cashInfo.setFreight(
  3561. new BigDecimal(orderEntity.getFreightPrice()).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
  3562. if ("alipay".equals(orderEntity.getPayFlag())) {
  3563. cashInfo.setPaymentMode("支付宝支付");
  3564. } else {
  3565. cashInfo.setPaymentMode("微信支付");
  3566. }
  3567. // 海关清单
  3568. CusListing cusListing = new CusListing();
  3569. cusListing.setOrderId(orderEntity.getOrderSn());
  3570. if (!orderEntity.getOrderBizType().equalsIgnoreCase(Dict.orderBizType.item_11.getItem())) {
  3571. cusListing.setWaybillId(orderProcessRecordEntity.getLogisticsNo());
  3572. cusListing.setInvtNo(orderProcessRecordEntity.getInvtNo()==null?"":orderProcessRecordEntity.getInvtNo());
  3573. cusListing.setConsignee(orderEntity.getConsignee());
  3574. // 脱敏设置
  3575. if (StringUtils.isNotEmpty(cusListing.getConsignee()) && cusListing.getConsignee().length() > 1) {
  3576. cusListing.setConsignee(new StringBuilder(cusListing.getConsignee()).replace(1, 2, "*").toString());
  3577. }
  3578. cusListing.setConsigneeTel(orderEntity.getMobile());
  3579. if (StringUtils.isNotEmpty(cusListing.getConsigneeTel())) {
  3580. cusListing.setConsigneeTel(new StringBuilder(cusListing.getConsigneeTel()).replace(3, 7, "****").toString());
  3581. }
  3582. }
  3583. cusListing.setOriginAddress(PrintTicketPropertiesBuilder.instance().getAddress());
  3584. cusListing.setDeliveryAddress(storeEntity.getStoreAddress());
  3585. // 尝试在取货码表中查询数据,如果有的话就改变状态
  3586. // String orderSn = orderEntity.getOrderSn();
  3587. // PickUpCodeEntity pickUpCodeEntity = pickUpCodeService.queryObject(orderSn);
  3588. // if (pickUpCodeEntity != null) {
  3589. // pickUpCodeEntity.setPickUpCodeStatus("0");
  3590. // pickUpCodeService.update(pickUpCodeEntity);
  3591. //
  3592. // }
  3593. TicketMailInfo mailInfo = new TicketMailInfo();
  3594. String exprNo = orderProcessRecordEntity.getLogisticsNo();
  3595. if (StringUtils.isNullOrEmpty(exprNo)) {
  3596. throw new RRException("快递面单为空,请联系客服");
  3597. }
  3598. //图片地址
  3599. mailInfo.setStoreImgUrl(storeEntity.getStoreImgUrl()==null?"/statics/img/cw_qrcode.png":storeEntity.getStoreImgUrl().trim());
  3600. mailInfo.setExprNo(exprNo);
  3601. String logoUrl = "/statics/img/yto_logo.jpg";
  3602. Map<String, String> logoMap = new HashMap<>();
  3603. logoMap.put("yto", "/statics/img/yto_logo.jpg");
  3604. logoMap.put("best", "/statics/img/bestex_logo3.png");
  3605. if (StringUtils.isNotEmpty(orderEntity.getShippingCode()) && logoMap.containsKey(orderEntity.getShippingCode())) {
  3606. logoUrl = logoMap.get(orderEntity.getShippingCode());
  3607. }
  3608. mailInfo.setExprLogoUrl(logoUrl);
  3609. byte[] barCode128 = BarcodeUtil.generateBarCode128(exprNo, 6.0D, null, true, false);
  3610. String exprNoBase64Img = new String(Base64.getEncoder().encode(barCode128));
  3611. mailInfo.setShopTel(storeEntity.getTelephoneNumber()==null?"0752-2688660":storeEntity.getTelephoneNumber().trim());
  3612. // 发货人
  3613. mailInfo.setSenderTel("0752-26886602");
  3614. mailInfo.setSenderName("CW澳洲大药房");
  3615. mailInfo.setSenderProvince("广东省");
  3616. mailInfo.setSenderCity("深圳市");
  3617. mailInfo.setSenderDistrict("南山区");
  3618. mailInfo.setSenderAddress("前海综合保税区W104");
  3619. // 收货人
  3620. mailInfo.setConsigneeMob(new StringBuilder(orderEntity.getMobile()).replace(3, 7, "****").toString());
  3621. mailInfo.setConsigneeName(new StringBuilder(orderEntity.getConsignee()).replace(1, 2, "*").toString());
  3622. mailInfo.setConsigneeProvince(orderEntity.getProvince());
  3623. mailInfo.setConsigneeCity(orderEntity.getCity());
  3624. mailInfo.setConsigneeDistrict(orderEntity.getDistrict());
  3625. mailInfo.setConsigneeAddress(orderEntity.getAddress());
  3626. mailInfo.setExprNoBase64Img(exprNoBase64Img);
  3627. return TicketPrintUtil.print(head, goodsList, cashInfo, cusListing, mailInfo);
  3628. }
  3629. /**
  3630. * 计算优惠价格,活动价格
  3631. *
  3632. * @param calculateOrderDiscountPriceVo 请求参数
  3633. * @return 商品集合
  3634. */
  3635. @Override
  3636. public List<GoodsDetailsDto> calculateOrderDiscountPrice(CalculateOrderDiscountPriceVo calculateOrderDiscountPriceVo) {
  3637. if (Objects.isNull(calculateOrderDiscountPriceVo)) {
  3638. LOGGER.error("计算活动优惠价格,请求参数为null!");
  3639. throw new ServiceException("计算活动优惠价格,请求参数为null!");
  3640. }
  3641. String storeId = calculateOrderDiscountPriceVo.getStoreId();
  3642. List<GoodsDetailsDto> goodsDetailsDtos = calculateOrderDiscountPriceVo.getGoodsList();
  3643. List<QueryGoodsVo> goodsVos = goodsDetailsDtos.stream().map(good -> {
  3644. QueryGoodsVo queryGoodsVo = new QueryGoodsVo();
  3645. BeanUtils.copyProperties(good, queryGoodsVo);
  3646. queryGoodsVo.setSku(good.getGoodsSn());
  3647. queryGoodsVo.setStoreId(Integer.parseInt(storeId));
  3648. return queryGoodsVo;
  3649. }).collect(Collectors.toList());
  3650. // 查询商品表
  3651. List<GoodsEntity> goodsEntities = goodsService.queryGoodsStockByQueryGoodsVoList(goodsVos);
  3652. /*
  3653. * 2.查询当前时间,该门店是否有活动,如果有活动,查询开启了哪些营销方式
  3654. * 参数: 当前时间 门店id
  3655. */
  3656. List<MkActivitiesEntity> mkActivitiesEntityList = mkActivitiesService.queryByNow(storeId, DateUtils.format(new Date(), "yyyy-MM-dd"));
  3657. /*
  3658. * 活动相关规则:
  3659. * 1. 优先优惠券再去计算积分
  3660. * 2. 满赠的赠品商品在推送定时时零售价为0
  3661. * 3. 任何活动都优先于积分计算
  3662. * 4. 活动之间具有互斥性
  3663. */
  3664. if (CollectionUtils.isEmpty(mkActivitiesEntityList)) {
  3665. LOGGER.info("当前时间门店【{}】,无相关活动信息!", storeId);
  3666. for (GoodsDetailsDto goodsDetailsDto : goodsDetailsDtos) {
  3667. GoodsEntity goodsEntity = new GoodsEntity();
  3668. BeanUtils.copyProperties(goodsDetailsDto, goodsEntity);
  3669. goodsEntity.setGoodsRate(new BigDecimal(goodsDetailsDto.getGoodsRate()));
  3670. // 无活动情况,实际支付价 = 零售价
  3671. BigDecimal tax = CalculateTax.calculateFinalTax(goodsEntity , goodsEntity.getRetailPrice(), goodsService).setScale(3,RoundingMode.HALF_UP);
  3672. // 预估税
  3673. goodsDetailsDto.setGoodstaxes(String.valueOf(tax));
  3674. // TODO 测试用
  3675. goodsDetailsDto.setActualPaymentAmount(BigDecimal.ZERO);
  3676. }
  3677. return goodsDetailsDtos;
  3678. }
  3679. List<Integer> brandIdList = goodsEntities.stream().map(GoodsEntity::getBrandId).collect(Collectors.toList());
  3680. List<Integer> categoryIdList = goodsEntities.stream().map(GoodsEntity::getCategoryId).collect(Collectors.toList());
  3681. AtomicBoolean activityFlag = new AtomicBoolean(false);
  3682. // 判断活动类型,并确定购物栏中商品是否满足活动条件
  3683. mkActivitiesEntityList.forEach(mkActivitiesEntity -> {
  3684. String mkaStoreId = mkActivitiesEntity.getMkaStoreId();
  3685. Long mkaId = mkActivitiesEntity.getMkaId();
  3686. String mkaTopic = mkActivitiesEntity.getMkaTopic();
  3687. Constants.ActivityTopicEnum activityTopicEnum = Constants.ActivityTopicEnum.valueOf(mkaTopic);
  3688. switch (activityTopicEnum) {
  3689. case MZ:
  3690. // 判断商品是否符合满赠活动要求
  3691. MkActivitiesFullGiftEntity mkActivitiesFullGiftEntity = mkActivitiesFullGiftService.queryObjectByMkaIdAndStoreId(mkaId.intValue(), storeId);
  3692. if (Objects.isNull(mkActivitiesFullGiftEntity)) {
  3693. LOGGER.error("查询满赠活动信息结果为空!mka_id:{}, store_id:{}", mkaId, storeId);
  3694. throw new ServiceException(String.format("查询满赠活动信息结果为空!mka_id:%s, store_id:%s", mkaId, storeId));
  3695. }
  3696. Long brandId = mkActivitiesFullGiftEntity.getBrandId();
  3697. Long categoryId = mkActivitiesFullGiftEntity.getCategoryId();
  3698. Constants.ActivityType fullGiftActivityType = Constants.ActivityType.valueOf(mkActivitiesFullGiftEntity.getFullGiftType());
  3699. switch (fullGiftActivityType) {
  3700. case BRAND:
  3701. if (brandIdList.contains(brandId.intValue())) {
  3702. // 活动包含该商品品牌,此次订单该品牌商品
  3703. List<GoodsEntity> goodsEntityList = goodsEntities.stream().filter(goodsEntity -> brandId.intValue() == goodsEntity.getBrandId()).collect(Collectors.toList());
  3704. AtomicReference<BigDecimal> brandTotalPrice = new AtomicReference<>(BigDecimal.ZERO);
  3705. goodsEntityList.forEach(goodsEntity -> {
  3706. brandTotalPrice.set(brandTotalPrice.get().add(goodsEntity.getRetailPrice()));
  3707. });
  3708. if (brandTotalPrice.get().compareTo(mkActivitiesFullGiftEntity.getQualifiedAmount()) >= 0) {
  3709. // 满足满赠条件
  3710. String giftGoodsSn = mkActivitiesFullGiftEntity.getGiftGoodsSn();
  3711. String giftBarcode = mkActivitiesFullGiftEntity.getGiftBarcode();
  3712. GoodsEntity goodsEntity = goodsService.queryGoodsStockByBarcodeAndStoreIdAndSku(giftBarcode, Integer.parseInt(mkaStoreId), giftGoodsSn);
  3713. GoodsDetailsDto goodsDetailsDto = new GoodsDetailsDto();
  3714. BeanUtils.copyProperties(goodsEntity, goodsDetailsDto);
  3715. // 除了限时促销(需要向海关备案),其它活动都拿海关备案价来算税款
  3716. BigDecimal tax = CalculateTax.calculateFinalTax(goodsEntity, goodsEntity.getRetailPrice(), goodsService).setScale(3, RoundingMode.HALF_UP);
  3717. goodsDetailsDto.setGoodstaxes(String.valueOf(tax));
  3718. goodsDetailsDto.setActualPaymentAmount(BigDecimal.ZERO);
  3719. goodsDetailsDto.setActivity("满赠商品");
  3720. goodsDetailsDto.setGiftNumber(mkActivitiesFullGiftEntity.getGiftNumber());
  3721. goodsDetailsDto.setDiscountedPrice(goodsEntity.getRetailPrice());
  3722. // 添加进商品详情列表
  3723. goodsDetailsDtos.add(goodsDetailsDto);
  3724. }
  3725. }
  3726. break;
  3727. case CATEGORY:
  3728. if (categoryIdList.contains(categoryId.intValue())) {
  3729. // 活动包含该商品分类
  3730. List<GoodsEntity> goodsEntityList = goodsEntities.stream().filter(goodsEntity -> brandId.equals(mkActivitiesFullGiftEntity.getCategoryId())).collect(Collectors.toList());
  3731. AtomicReference<BigDecimal> categoryTotalPrice = new AtomicReference<>(BigDecimal.ZERO);
  3732. goodsEntityList.forEach(goodsEntity -> {
  3733. categoryTotalPrice.set(categoryTotalPrice.get().add(goodsEntity.getRetailPrice()));
  3734. });
  3735. if (categoryTotalPrice.get().compareTo(mkActivitiesFullGiftEntity.getQualifiedAmount()) >= 0) {
  3736. // 满足满赠条件
  3737. String giftGoodsSn = mkActivitiesFullGiftEntity.getGiftGoodsSn();
  3738. String giftBarcode = mkActivitiesFullGiftEntity.getGiftBarcode();
  3739. GoodsEntity goodsEntity = goodsService.queryGoodsStockByBarcodeAndStoreIdAndSku(giftBarcode, Integer.parseInt(mkaStoreId), giftGoodsSn);
  3740. GoodsDetailsDto goodsDetailsDto = new GoodsDetailsDto();
  3741. BeanUtils.copyProperties(goodsEntity, goodsDetailsDto);
  3742. // 除了限时促销(需要向海关备案),其它活动都拿海关备案价来算税款
  3743. BigDecimal tax = CalculateTax.calculateFinalTax(goodsEntity, goodsEntity.getRetailPrice(), goodsService).setScale(3, RoundingMode.HALF_UP);
  3744. goodsDetailsDto.setGoodstaxes(String.valueOf(tax));
  3745. goodsDetailsDto.setActualPaymentAmount(BigDecimal.ZERO);
  3746. goodsDetailsDto.setActivity("满赠商品");
  3747. goodsDetailsDto.setGiftNumber(mkActivitiesFullGiftEntity.getGiftNumber());
  3748. goodsDetailsDto.setDiscountedPrice(goodsEntity.getRetailPrice());
  3749. // 添加进商品详情列表
  3750. goodsDetailsDtos.add(goodsDetailsDto);
  3751. }
  3752. }
  3753. break;
  3754. default:
  3755. LOGGER.error("未知满赠类型【{},{}】!请联系管理员!", fullGiftActivityType.getActivityType(), fullGiftActivityType.getActivityTypeCode());
  3756. throw new ServiceException(String.format("未知满赠类型【%s,%s】!请联系管理员!", fullGiftActivityType.getActivityType(), fullGiftActivityType.getActivityTypeCode()));
  3757. }
  3758. break;
  3759. case YHJ:
  3760. // 判断商品是否符合优惠券活动要求
  3761. Map<String, Object> params = new HashMap<>();
  3762. params.put("shop_sn", storeId);
  3763. params.put("mka_id", mkaId);
  3764. List<MkActivitiesCouponEntity> mkActivitiesCouponEntities = mkActivitiesCouponService.queryList(params);
  3765. if (CollectionUtils.isEmpty(mkActivitiesCouponEntities)) {
  3766. LOGGER.error("查询优惠券活动信息结果为空!mka_id:{}, store_id:{}", mkaId, storeId);
  3767. throw new ServiceException(String.format("查询优惠券活动信息结果为空!mka_id:%s, store_id:%s", mkaId, storeId));
  3768. }
  3769. MkActivitiesCouponEntity mkActivitiesCouponEntity = mkActivitiesCouponEntities.get(0);
  3770. Integer couponEntityBrandId = mkActivitiesCouponEntity.getBrandId();
  3771. Integer couponEntityCategoryId = mkActivitiesCouponEntity.getCategoryId();
  3772. Integer couponEntityStoreId = Integer.parseInt(mkActivitiesCouponEntity.getShopSn());
  3773. BigDecimal couponPrice = mkActivitiesCouponEntity.getCouponPrice();
  3774. Constants.ActivityType couponActivityType = Constants.ActivityType.valueOf(mkActivitiesCouponEntity.getActivityType());
  3775. switch (couponActivityType) {
  3776. case BRAND:
  3777. goodsEntities.forEach(goodsEntity -> {
  3778. if (couponEntityBrandId.equals(goodsEntity.getBrandId())) {
  3779. BigDecimal retailPrice = goodsEntity.getRetailPrice();
  3780. String sku = goodsEntity.getSku();
  3781. String prodBarcode = goodsEntity.getProdBarcode();
  3782. if (couponPrice.compareTo(retailPrice) <= 0) {
  3783. LOGGER.error("优惠券优惠金额【{}】大于或等于商品【条码:{},sku:{}】的零售价【{}】,请检查优惠券金额设置!", couponPrice, prodBarcode, sku, retailPrice);
  3784. throw new ServiceException(String.format("优惠券优惠金额【%s】大于或等于商品【条码:%s,sku:%s】的零售价【%s】,请检查优惠券金额设置!", couponPrice, prodBarcode, sku, retailPrice));
  3785. }
  3786. BigDecimal discountAfterPrice = retailPrice.subtract(couponPrice);
  3787. GoodsDetailsDto goodsDetailsDto = new GoodsDetailsDto();
  3788. BeanUtils.copyProperties(goodsEntity, goodsDetailsDto);
  3789. // 除了限时促销(需要向海关备案),其它活动都拿海关备案价来算税款
  3790. BigDecimal tax = CalculateTax.calculateFinalTax(goodsEntity, goodsEntity.getRetailPrice(), goodsService).setScale(3, RoundingMode.HALF_UP);
  3791. goodsDetailsDto.setActualPaymentAmount(discountAfterPrice);
  3792. goodsDetailsDto.setGoodstaxes(String.valueOf(tax));
  3793. goodsDetailsDto.setActivity("优惠券活动");
  3794. goodsDetailsDto.setDiscountedPrice(retailPrice.subtract(discountAfterPrice));
  3795. goodsDetailsDtos.add(goodsDetailsDto);
  3796. }
  3797. });
  3798. break;
  3799. case CATEGORY:
  3800. goodsEntities.forEach(goodsEntity -> {
  3801. if (couponEntityCategoryId.equals(goodsEntity.getCategoryId())) {
  3802. BigDecimal retailPrice = goodsEntity.getRetailPrice();
  3803. String sku = goodsEntity.getSku();
  3804. String prodBarcode = goodsEntity.getProdBarcode();
  3805. if (couponPrice.compareTo(retailPrice) <= 0) {
  3806. LOGGER.error("优惠券优惠金额【{}】大于或等于商品【条码:{},sku:{}】的零售价【{}】,请检查优惠券金额设置!", couponPrice, prodBarcode, sku, retailPrice);
  3807. throw new ServiceException(String.format("优惠券优惠金额【%s】大于或等于商品【条码:%s,sku:%s】的零售价【%s】,请检查优惠券金额设置!", couponPrice, prodBarcode, sku, retailPrice));
  3808. }
  3809. BigDecimal discountAfterPrice = retailPrice.subtract(couponPrice);
  3810. GoodsDetailsDto goodsDetailsDto = new GoodsDetailsDto();
  3811. BeanUtils.copyProperties(goodsEntity, goodsDetailsDto);
  3812. // 除了限时促销(需要向海关备案),其它活动都拿海关备案价来算税款
  3813. BigDecimal tax = CalculateTax.calculateFinalTax(goodsEntity, goodsEntity.getRetailPrice(), goodsService).setScale(3, RoundingMode.HALF_UP);
  3814. goodsDetailsDto.setActualPaymentAmount(discountAfterPrice);
  3815. goodsDetailsDto.setGoodstaxes(String.valueOf(tax));
  3816. goodsDetailsDto.setActivity("优惠券活动");
  3817. goodsDetailsDto.setDiscountedPrice(retailPrice.subtract(discountAfterPrice));
  3818. goodsDetailsDtos.add(goodsDetailsDto);
  3819. }
  3820. });
  3821. break;
  3822. case PRODUCT:
  3823. mkActivitiesCouponEntities.forEach(mkActivitiesCouponEntity1 -> {
  3824. // 单个商品优惠券,有多条记录
  3825. String activityProductBarcode = mkActivitiesCouponEntity1.getBarcode();
  3826. String activitySku = mkActivitiesCouponEntity1.getGoodsSn();
  3827. goodsEntities.forEach(goodsEntity -> {
  3828. String sku = goodsEntity.getSku();
  3829. String prodBarcode = goodsEntity.getProdBarcode();
  3830. // 条码、sku、门店都需一致
  3831. if (activitySku.equals(sku) && activityProductBarcode.equals(prodBarcode) && couponEntityStoreId.equals(goodsEntity.getStoreId())) {
  3832. BigDecimal retailPrice = goodsEntity.getRetailPrice();
  3833. if (couponPrice.compareTo(retailPrice) <= 0) {
  3834. LOGGER.error("优惠券优惠金额【{}】大于或等于商品【条码:{},sku:{}】的零售价【{}】,请检查优惠券金额设置!", couponPrice, prodBarcode, sku, retailPrice);
  3835. throw new ServiceException(String.format("优惠券优惠金额【%s】大于或等于商品【条码:%s,sku:%s】的零售价【%s】,请检查优惠券金额设置!", couponPrice, prodBarcode, sku, retailPrice));
  3836. }
  3837. BigDecimal discountAfterPrice = retailPrice.subtract(couponPrice);
  3838. GoodsDetailsDto goodsDetailsDto = new GoodsDetailsDto();
  3839. BeanUtils.copyProperties(goodsEntity, goodsDetailsDto);
  3840. // 除了限时促销(需要向海关备案),其它活动都拿海关备案价来算税款
  3841. BigDecimal tax = CalculateTax.calculateFinalTax(goodsEntity, goodsEntity.getRetailPrice(), goodsService).setScale(3, RoundingMode.HALF_UP);
  3842. goodsDetailsDto.setActualPaymentAmount(discountAfterPrice);
  3843. goodsDetailsDto.setGoodstaxes(String.valueOf(tax));
  3844. goodsDetailsDto.setActivity("优惠券活动");
  3845. goodsDetailsDto.setDiscountedPrice(retailPrice.subtract(discountAfterPrice));
  3846. goodsDetailsDtos.add(goodsDetailsDto);
  3847. }
  3848. });
  3849. });
  3850. break;
  3851. default:
  3852. LOGGER.error("未知的优惠券活动分类类型:【{},{}】,请联系管理员!", activityTopicEnum.getTopicCode(), activityTopicEnum.getTopicName());
  3853. throw new ServiceException(String.format("未知的优惠券活动分类类型:【%s,%s】,请联系管理员!", activityTopicEnum.getTopicCode(), activityTopicEnum.getTopicName()));
  3854. }
  3855. break;
  3856. case LSCX:
  3857. // 判断商品是否符合限时特价活动要求
  3858. List<MkActivitiesPromotionEntity> mkActivitiesPromotionEntities = mkActivitiesPromotionService.queryListByMkaIdAndStoreId(mkaId.intValue(), storeId);
  3859. if (CollectionUtils.isEmpty(mkActivitiesPromotionEntities)) {
  3860. LOGGER.error("查询临时促销活动信息结果为空!mka_id:{}, store_id:{}", mkaId, storeId);
  3861. throw new ServiceException(String.format("查询临时促销活动信息结果为空!mka_id:%s, store_id:%s", mkaId, storeId));
  3862. }
  3863. // 限时特价,直接替换实际支付价即可,并且拿特价计算税款
  3864. mkActivitiesPromotionEntities.forEach(mkActivitiesPromotionEntity -> {
  3865. String entityBarcode = mkActivitiesPromotionEntity.getBarcode();
  3866. String entityGoodsSn = mkActivitiesPromotionEntity.getGoodsSn();
  3867. BigDecimal activityPrice = mkActivitiesPromotionEntity.getActivityPrice();
  3868. String shopSn = mkActivitiesPromotionEntity.getShopSn();
  3869. goodsEntities.forEach(goodsEntity -> {
  3870. String sku = goodsEntity.getSku();
  3871. String prodBarcode = goodsEntity.getProdBarcode();
  3872. String storeId2 = String.valueOf(goodsEntity.getStoreId());
  3873. BigDecimal retailPrice = goodsEntity.getRetailPrice();
  3874. if (entityBarcode.equals(prodBarcode) && entityGoodsSn.equals(sku) && shopSn.equals(storeId2)) {
  3875. GoodsDetailsDto goodsDetailsDto = new GoodsDetailsDto();
  3876. BigDecimal tax = CalculateTax.calculateFinalTax(goodsEntity, activityPrice, goodsService).setScale(3, RoundingMode.HALF_UP);
  3877. BeanUtils.copyProperties(goodsDetailsDto, goodsEntity);
  3878. goodsDetailsDto.setActualPaymentAmount(activityPrice);
  3879. goodsDetailsDto.setGoodstaxes(String.valueOf(tax));
  3880. goodsDetailsDto.setActivity("限时促销");
  3881. goodsDetailsDto.setDiscountedPrice(retailPrice.subtract(activityPrice));
  3882. goodsDetailsDtos.add(goodsDetailsDto);
  3883. }
  3884. });
  3885. });
  3886. break;
  3887. default:
  3888. LOGGER.error("未知的满赠活动分类类型:【{},{}】,请联系管理员!", activityTopicEnum.getTopicCode(), activityTopicEnum.getTopicName());
  3889. throw new ServiceException(String.format("未知的满赠活动分类类型:【%s,%s】,请联系管理员!", activityTopicEnum.getTopicCode(), activityTopicEnum.getTopicName()));
  3890. }
  3891. });
  3892. return goodsDetailsDtos;
  3893. }
  3894. /**
  3895. * 设置订单数据
  3896. *
  3897. * @return
  3898. */
  3899. public OrderVo setOrderVo(List<GoodsEntity> goodsList, UserEntity loginUser, Long storeId, String merchSn, BigDecimal disCountAmount, BigDecimal totalTax) {
  3900. OrderVo orderInfo = new OrderVo();
  3901. BigDecimal goodsTotalPrice = new BigDecimal(0.00);
  3902. BigDecimal fullCutCouponDec = Constant.ZERO; // 非现金抵扣 = 各种优惠价格 +优惠券的价格 暂时借用这个字段去,为了不改动ccnet系统
  3903. BigDecimal couponPrice = disCountAmount;
  3904. BigDecimal freightPrice = Constant.ZERO;
  3905. BigDecimal actualPrice = Constant.ZERO;
  3906. //订单价格计算:订单的总价+运费
  3907. for (GoodsEntity goodsEntity : goodsList) {
  3908. goodsTotalPrice = goodsTotalPrice
  3909. .add(goodsEntity.getRetailPrice().multiply(new BigDecimal(goodsEntity.getGoodsNumber()))).setScale(2, RoundingMode.HALF_UP);
  3910. fullCutCouponDec = fullCutCouponDec
  3911. .add(goodsEntity.getDiscountedPrice()).setScale(2, RoundingMode.HALF_UP);
  3912. actualPrice = actualPrice
  3913. .add(goodsEntity.getActualPaymentAmount()).setScale(2, RoundingMode.HALF_UP);
  3914. }
  3915. BigDecimal orderTotalPrice = goodsTotalPrice.add(new BigDecimal(0));
  3916. fullCutCouponDec = fullCutCouponDec.add(couponPrice).setScale(2, RoundingMode.HALF_UP);
  3917. // 加上税额
  3918. goodsTotalPrice = goodsTotalPrice.subtract(totalTax).setScale(2, RoundingMode.HALF_UP);
  3919. SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
  3920. String orderSn = "ZWCW" + format.format(new Date()) + CommonUtil.generateOrderNumber();
  3921. orderInfo.setOrder_sn(orderSn);
  3922. orderInfo.setMerchSn(merchSn);
  3923. orderInfo.setUser_id(loginUser.getId().longValue());
  3924. actualPrice = actualPrice.subtract(couponPrice);
  3925. StoreEntity storeEntity = storeDao.queryObject(storeId);
  3926. //收货地址和运费
  3927. orderInfo.setConsignee(loginUser.getUsername());
  3928. orderInfo.setMobile(loginUser.getMobile());
  3929. orderInfo.setCountry("");
  3930. orderInfo.setProvince(storeEntity.getProvinceName());
  3931. orderInfo.setCity(storeEntity.getCityName());
  3932. orderInfo.setDistrict(storeEntity.getCountyName());
  3933. orderInfo.setAddress(storeEntity.getStoreAddress());
  3934. orderInfo.setAddress_id(1L);
  3935. orderInfo.setDelivery_date(new Date());
  3936. orderInfo.setDelivery_remark("无");
  3937. orderInfo.setStore_id(storeId);
  3938. orderInfo.setFreight_price(freightPrice.intValue());
  3939. orderInfo.setCoupon_id(Integer.parseInt(String.valueOf(0L)));
  3940. orderInfo.setCoupon_price(couponPrice);
  3941. orderInfo.setCoupon_name("无");
  3942. orderInfo.setActivity_id(0L);
  3943. //使用的促销费用
  3944. orderInfo.setFull_cut_price(fullCutCouponDec);
  3945. orderInfo.setCampMinusId(0);
  3946. orderInfo.setCampName("");
  3947. //留言
  3948. orderInfo.setPostscript("无");
  3949. orderInfo.setAdd_time(new Date());
  3950. orderInfo.setGoods_price(goodsTotalPrice); // 商品总价
  3951. orderInfo.setOrder_price(orderTotalPrice);
  3952. orderInfo.setActual_price(actualPrice); // 实际支付金额
  3953. orderInfo.setOrder_type("1");
  3954. orderInfo.setOrder_status(0);
  3955. orderInfo.setShipping_status(0);
  3956. orderInfo.setPay_status(0);
  3957. orderInfo.setShipping_id(0L);
  3958. orderInfo.setShipping_fee(Constant.ZERO);
  3959. orderInfo.setIntegral(0);
  3960. orderInfo.setIntegral_money(Constant.ZERO);
  3961. orderInfo.setCreateTime(new Date());
  3962. orderInfo.setModTime(new Date());
  3963. orderInfo.setPayMobile(loginUser.getMobile());
  3964. // orderInfo.setPayTransactionId(orderInfo.getOrder_sn());
  3965. orderInfo.setIsScan("0");//默认未扫描
  3966. orderInfo.setPayMobile(loginUser.getMobile());
  3967. orderInfo.setPay_name(loginUser.getUsername());
  3968. orderInfo.setIsOnfflineOrder(Dict.isOnfflineOrder.item_1.getItem());
  3969. orderInfo.setOrderBizType(Dict.orderBizType.item_10.getItem());
  3970. return orderInfo;
  3971. }
  3972. /**
  3973. * 设置订单数据
  3974. *
  3975. * @return
  3976. */
  3977. public OrderVo setOrderVo(List<GoodsEntity> goodsList, UserEntity loginUser, Long storeId, String merchSn, BigDecimal disCountAmount, BigDecimal totalTax, int status, Map mapAddr) {
  3978. OrderVo orderInfo = new OrderVo();
  3979. BigDecimal goodsTotalPrice = new BigDecimal(0.00);
  3980. BigDecimal fullCutCouponDec = Constant.ZERO; // 非现金抵扣 = 各种优惠价格 +优惠券的价格 暂时借用这个字段去,为了不改动ccnet系统
  3981. BigDecimal couponPrice = disCountAmount;
  3982. BigDecimal freightPrice = Constant.ZERO;
  3983. BigDecimal actualPrice = Constant.ZERO;
  3984. //订单价格计算:订单的总价+运费
  3985. for (GoodsEntity goodsEntity : goodsList) {
  3986. goodsTotalPrice = goodsTotalPrice
  3987. .add(goodsEntity.getRetailPrice().multiply(new BigDecimal(goodsEntity.getGoodsNumber()))).setScale(2, RoundingMode.HALF_UP);
  3988. fullCutCouponDec = fullCutCouponDec
  3989. .add(goodsEntity.getDiscountedPrice()).setScale(2, RoundingMode.HALF_UP);
  3990. actualPrice = actualPrice
  3991. .add(goodsEntity.getActualPaymentAmount()).setScale(2, RoundingMode.HALF_UP);
  3992. }
  3993. BigDecimal orderTotalPrice = goodsTotalPrice.add(new BigDecimal(0));
  3994. fullCutCouponDec = fullCutCouponDec.add(couponPrice).setScale(2, RoundingMode.HALF_UP);
  3995. // 加上税额
  3996. goodsTotalPrice = goodsTotalPrice.subtract(totalTax).setScale(2, RoundingMode.HALF_UP);
  3997. SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
  3998. String orderSn = "ZWCW" + format.format(new Date()) + CommonUtil.generateOrderNumber();
  3999. orderInfo.setOrder_sn(orderSn);
  4000. orderInfo.setMerchSn(merchSn);
  4001. orderInfo.setUser_id(loginUser.getId().longValue());
  4002. actualPrice = actualPrice.subtract(couponPrice);
  4003. StoreEntity storeEntity = storeDao.queryObject(storeId);
  4004. //收货地址和运费
  4005. orderInfo.setConsignee(loginUser.getUsername());
  4006. orderInfo.setMobile(loginUser.getMobile());
  4007. orderInfo.setCountry("");
  4008. //根据 前端的选择方式 1 是柜取 0 是 邮寄
  4009. if (status == 0) {
  4010. //省
  4011. String cmbProvince = (String) mapAddr.get("cmbProvince");
  4012. //市
  4013. String cmbCity = (String) mapAddr.get("cmbCity");
  4014. //区
  4015. String cmbArea = (String) mapAddr.get("cmbArea");
  4016. //详细地址
  4017. String addrUser = (String) mapAddr.get("addrUser");
  4018. orderInfo.setProvince(cmbProvince);
  4019. orderInfo.setCity(cmbCity);
  4020. orderInfo.setDistrict(cmbArea);
  4021. orderInfo.setAddress(addrUser);
  4022. } else {
  4023. orderInfo.setProvince(storeEntity.getProvinceName());
  4024. orderInfo.setCity(storeEntity.getCityName());
  4025. orderInfo.setDistrict(storeEntity.getCountyName());
  4026. orderInfo.setAddress(storeEntity.getStoreAddress());
  4027. }
  4028. orderInfo.setAddress_id(1L);
  4029. orderInfo.setDelivery_date(new Date());
  4030. orderInfo.setDelivery_remark("无");
  4031. orderInfo.setStore_id(storeId);
  4032. orderInfo.setFreight_price(freightPrice.intValue());
  4033. orderInfo.setCoupon_id(Integer.parseInt(String.valueOf(0L)));
  4034. orderInfo.setCoupon_price(couponPrice);
  4035. orderInfo.setCoupon_name("无");
  4036. orderInfo.setActivity_id(0L);
  4037. //使用的促销费用
  4038. orderInfo.setFull_cut_price(fullCutCouponDec);
  4039. orderInfo.setCampMinusId(0);
  4040. orderInfo.setCampName("");
  4041. //留言
  4042. orderInfo.setPostscript("无");
  4043. orderInfo.setAdd_time(new Date());
  4044. orderInfo.setGoods_price(goodsTotalPrice); // 商品总价
  4045. orderInfo.setOrder_price(orderTotalPrice);
  4046. orderInfo.setActual_price(actualPrice); // 实际支付金额
  4047. orderInfo.setOrder_type("1");
  4048. orderInfo.setOrder_status(0);
  4049. orderInfo.setShipping_status(0);
  4050. orderInfo.setPay_status(0);
  4051. orderInfo.setShipping_id(0L);
  4052. orderInfo.setShipping_fee(Constant.ZERO);
  4053. orderInfo.setIntegral(0);
  4054. orderInfo.setIntegral_money(Constant.ZERO);
  4055. orderInfo.setCreateTime(new Date());
  4056. orderInfo.setModTime(new Date());
  4057. orderInfo.setPayMobile(loginUser.getMobile());
  4058. // orderInfo.setPayTransactionId(orderInfo.getOrder_sn());
  4059. orderInfo.setIsScan("0");//默认未扫描
  4060. orderInfo.setPayMobile(loginUser.getMobile());
  4061. orderInfo.setPay_name(loginUser.getUsername());
  4062. orderInfo.setIsOnfflineOrder(Dict.isOnfflineOrder.item_1.getItem());
  4063. orderInfo.setOrderBizType(Dict.orderBizType.item_10.getItem());
  4064. // 添加快递信息
  4065. try {
  4066. StoreExprActiveDto activeExpr = addressInfoService.queryByStoreId(storeId);
  4067. if (activeExpr == null) {
  4068. throw new RRException("门店未配置快递信息");
  4069. }
  4070. orderInfo.setShipping_id(activeExpr.getExprId());
  4071. orderInfo.setShipping_code(activeExpr.getExprCode());
  4072. orderInfo.setShipping_name(activeExpr.getExprName());
  4073. } catch (Exception e) {
  4074. LOGGER.error("订单写入门店快递配置信息有误:", e);
  4075. }
  4076. return orderInfo;
  4077. }
  4078. public OrderGoodsVo setOrderGoodsVo(OrderVo orderInfo, GoodsEntity goodsDto) {
  4079. OrderGoodsVo orderGoodsVo = new OrderGoodsVo();
  4080. orderGoodsVo.setOrder_id(orderInfo.getId());
  4081. orderGoodsVo.setGoods_id(goodsDto.getId());
  4082. orderGoodsVo.setGoods_sn(goodsDto.getGoodsSn());
  4083. orderGoodsVo.setProduct_id(Long.valueOf(goodsDto.getProductId()));
  4084. orderGoodsVo.setGoods_name(goodsDto.getName());
  4085. orderGoodsVo.setList_pic_url(goodsDto.getListPicUrl());
  4086. orderGoodsVo.setMarket_price(goodsDto.getStoreRetailPrice());
  4087. orderGoodsVo.setRetail_price(goodsDto.getStoreRetailPrice());
  4088. orderGoodsVo.setDiscountedPrice(goodsDto.getDiscountedPrice());
  4089. orderGoodsVo.setActualPaymentAmount(goodsDto.getActualPaymentAmount());
  4090. orderGoodsVo.setNumber(goodsDto.getGoodsNumber());
  4091. // orderGoodsVo.setGoods_specification_name_value(goodsDto.get);
  4092. // orderGoodsVo.setGoods_specification_ids(goodsItem.getGoods_specification_ids());
  4093. orderGoodsVo.setOrderBizType(Dict.orderBizType.item_10.getItem());
  4094. orderGoodsVo.setCreateTime(new Date());
  4095. orderGoodsVo.setModTime(new Date());
  4096. orderGoodsVo.setActivity(goodsDto.getActivity());
  4097. orderGoodsVo.setGoodsRate(goodsDto.getGoodsRate());
  4098. orderGoodsVo.setSku(goodsDto.getSku());
  4099. BigDecimal number = new BigDecimal(Long.valueOf(goodsDto.getGoodsNumber()));
  4100. BigDecimal goodsTotal = goodsDto.getRetailPrice().multiply(number);//单商品总价
  4101. BigDecimal rate = goodsTotal.divide(orderInfo.getGoods_price(), 2, BigDecimal.ROUND_HALF_UP);//当前商品总价/订单总价(不含运费、不含优惠券)
  4102. BigDecimal freightPrice = BigDecimal.valueOf(orderInfo.getFreight_price());
  4103. BigDecimal settlePrice = Constant.ZERO; // ccnet 取的这个而价格
  4104. if (orderInfo.getFreight_price() != 0 && !"0".equalsIgnoreCase(orderInfo.getCoupon_price() + "")) {
  4105. //运费-优惠券
  4106. BigDecimal rateTotal = freightPrice.subtract(orderInfo.getCoupon_price());
  4107. //商品结算平摊价格(含优惠券、运费金额) = 单商品总价 + 当前商品总价/订单总价(不含运费、不含优惠券) * 运费与优惠券合计税率
  4108. settlePrice = goodsTotal.add(rate.multiply(rateTotal));
  4109. } else {
  4110. if (orderInfo.getFreight_price() != 0) {
  4111. //运费税率 = 单商品总价/订单总价(不含运费)* 运费金额
  4112. BigDecimal freightRate = rate.multiply(freightPrice);
  4113. //商品结算平摊价格(含运费金额) = 单商品总价+运费税率
  4114. settlePrice = goodsTotal.add(freightRate);
  4115. }
  4116. if (!"0".equalsIgnoreCase(orderInfo.getCoupon_price() + "")) {
  4117. //优惠券税率 = 单商品总价/订单总价(不含优惠券)* 优惠券金额
  4118. BigDecimal couponRate = rate.multiply(orderInfo.getCoupon_price());
  4119. //商品结算平摊价格(含优惠券金额) = 单商品总价-优惠券税率
  4120. settlePrice = goodsTotal.subtract(couponRate);
  4121. }
  4122. }
  4123. if (settlePrice.compareTo(BigDecimal.valueOf(0)) == 0) {
  4124. orderGoodsVo.setSettlePrice(goodsTotal);//商品结算平摊价格
  4125. } else {
  4126. orderGoodsVo.setSettlePrice(settlePrice);//商品结算平摊价格
  4127. }
  4128. // 计算税费
  4129. GoodsEntity goodsEntity = goodsService.queryObject(goodsDto.getId().intValue());
  4130. BigDecimal goodsTax = CalculateTax.calculateFinalTax(goodsEntity, goodsDto.getStoreRetailPrice(), goodsService).setScale(3, RoundingMode.HALF_UP);
  4131. goodsTax = goodsTax.multiply(number).setScale(2, RoundingMode.HALF_UP);
  4132. orderGoodsVo.setTaxPrice(goodsTax);
  4133. return orderGoodsVo;
  4134. }
  4135. }