OrderServiceImpl.java 247 KB

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