OrderServiceImpl.java 237 KB

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