OrderServiceImpl.java 233 KB

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