OrderServiceImpl.java 237 KB

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