OrderServiceImpl.java 234 KB

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