12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733 |
- package com.kmall.admin.service.impl;
- import com.alibaba.fastjson.JSON;
- import com.alibaba.fastjson.JSONObject;
- import com.fasterxml.jackson.core.type.TypeReference;
- import com.google.common.collect.ImmutableBiMap;
- import com.google.common.collect.Maps;
- import com.google.gson.Gson;
- import com.google.gson.internal.LinkedTreeMap;
- import com.kmall.admin.biz.CustomsClearanceTimeliness;
- import com.kmall.admin.dao.*;
- import com.kmall.admin.dao.alarm.Mall2LowPriceWarningDao;
- import com.kmall.admin.dao.mk.Mk2GoodsTopicPriceDao;
- import com.kmall.admin.dao.mk.Mk2MemberBirthdayDao;
- import com.kmall.admin.dao.mk.store.MkStorePromOrderRealDao;
- import com.kmall.admin.dao.mk.store.MkStorePromTypeDao;
- import com.kmall.admin.dao.mk.store.StoreTopicDao;
- import com.kmall.admin.dao.vip.Mall2MemberConsumptionRecordsDao;
- import com.kmall.admin.dao.vip.Mall2MemberPointsDao;
- import com.kmall.admin.dao.vip.Mall2PointsRulesDao;
- import com.kmall.admin.dto.*;
- import com.kmall.admin.entity.*;
- import com.kmall.admin.entity.mk.MkActivitiesEntity;
- import com.kmall.admin.entity.mk.store.MkStorePromOrderRealEntity;
- import com.kmall.admin.entity.record.NewRetailOrderRestoreStockRecordEntity;
- import com.kmall.admin.entity.vip.Mall2MemberConsumptionRecordsEntity;
- import com.kmall.admin.entity.vip.Mall2MemberPointsEntity;
- import com.kmall.admin.entity.vip.Mall2PointsRulesEntity;
- import com.kmall.admin.fromcomm.dao.SysConfigDao;
- import com.kmall.admin.fromcomm.entity.SysUserEntity;
- import com.kmall.admin.haikong.constant.Constants;
- import com.kmall.admin.haikong.constant.VmcconnectUrlEnum;
- import com.kmall.admin.haikong.dto.WareQueryStockResponseDTO;
- import com.kmall.admin.haikong.utils.ListUtils;
- import com.kmall.admin.haikong.vo.CalculateOrderDiscountPriceResponseVO;
- import com.kmall.admin.haikong.vo.QueryGoodsVO;
- import com.kmall.admin.haikong.client.HaiKongMemberTemplate;
- import com.kmall.admin.haikong.client.HaiKongWarehouseTemplate;
- import com.kmall.admin.haikong.client.VmcShopTemplate;
- import com.kmall.admin.haikong.config.HaiKongProperties;
- import com.kmall.admin.haikong.dto.MemberInfoDTO;
- import com.kmall.admin.haikong.utils.Response;
- import com.kmall.admin.service.*;
- import com.kmall.admin.service.kmall2eccs.KtoEccsService;
- import com.kmall.admin.service.mk.MkActivitiesService;
- import com.kmall.admin.service.mk.store.MkStoreCampMinusService;
- import com.kmall.admin.service.mk.store.MkStoreTicketDiscountService;
- import com.kmall.admin.service.record.NewRetailOrderRestoreStockRecordService;
- import com.kmall.admin.utils.CalculateTax;
- import com.kmall.admin.utils.ShiroUtils;
- import com.kmall.admin.utils.data.response.ResponseMessage;
- import com.kmall.admin.utils.data.response.ResponseMessageData;
- import com.kmall.admin.utils.jackson.JacksonUtil;
- import com.kmall.admin.utils.oms.OmsSign;
- import com.kmall.admin.utils.pdf.BarcodeUtil;
- import com.kmall.admin.haikong.vo.CalculateOrderDiscountPriceVO;
- import com.kmall.admin.websocket.WebSocketServer;
- import com.kmall.api.entity.OrderGoodsRestoreVo;
- import com.kmall.api.entity.OrderGoodsVo;
- import com.kmall.api.entity.OrderVo;
- import com.kmall.api.util.CommonUtil;
- import com.kmall.common.constant.Dict;
- import com.kmall.common.utils.*;
- import com.kmall.common.utils.print.ticket.item.*;
- import com.kmall.common.utils.wechat.WechatMicropayApiResult;
- import com.kmall.common.utils.wechat.WechatRefundApiResult;
- import com.kmall.common.utils.wechat.WechatReverseApiResult;
- import com.kmall.manager.manager.alipay.AliPayMicropayApiResult;
- import com.kmall.manager.manager.alipay.AliPayRequestParams;
- import com.kmall.manager.manager.alipay.AliPayUtil;
- import com.kmall.manager.manager.express.kdn.KdniaoUtil;
- import com.kmall.manager.manager.express.sf.ServiceException;
- import com.kmall.manager.manager.express.sf.entity.RouteEntity;
- import com.kmall.manager.manager.express.sf.entity.RouteResponseEntity;
- import com.kmall.manager.manager.express.sf.entity.SfRouteServiceResponseEntity;
- import com.kmall.manager.manager.express.sf.properties.SFPropertiesBuilder;
- import com.kmall.manager.manager.express.sf.properties.SFUtil;
- import com.kmall.manager.manager.merch.OmsMerchProperties;
- import com.kmall.manager.manager.merch.OmsMerchPropertiesBuilder;
- import com.kmall.manager.manager.print.ticket.PrintTicketPropertiesBuilder;
- import com.kmall.manager.manager.print.ticket.TicketPrintUtil;
- import com.kmall.manager.manager.redis.JedisUtil;
- import com.kmall.manager.manager.wechat.WechatUtil;
- import com.kmall.manager.manager.wechat.wxglobal.dto.WechatGlobalRefundApiResult;
- import okhttp3.Request;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.beans.BeanUtils;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
- import org.springframework.transaction.annotation.Transactional;
- import org.springframework.util.CollectionUtils;
- import java.io.IOException;
- import java.math.BigDecimal;
- import java.math.RoundingMode;
- import java.net.InetAddress;
- import java.net.URLDecoder;
- import java.text.ParseException;
- import java.text.SimpleDateFormat;
- import java.util.*;
- import java.util.concurrent.*;
- import java.util.concurrent.atomic.AtomicBoolean;
- import java.util.concurrent.atomic.AtomicReference;
- import java.util.stream.Collectors;
- @Service("orderService")
- public class OrderServiceImpl implements OrderService {
- private final Logger LOGGER = LoggerFactory.getLogger(OrderServiceImpl.class);
- @Autowired
- private OmsMerchProperties omsMerchProperties;
- @Autowired
- private OrderDao orderDao;
- @Autowired
- private ShippingDao shippingDao;
- @Autowired
- private OrderGoodsDao orderGoodsDao;
- @Autowired
- private OrderGoodsService orderGoodsService;
- @Autowired
- private ProductStoreRelaService productStoreRelaService;
- @Autowired
- private NewRetailOrderRestoreStockRecordService newRetailOrderRestoreStockRecordService;
- @Autowired
- private SysPrinterDao printerDao;
- @Autowired
- private UserDao userDao;
- @Autowired
- private UserCouponDao userCouponDao;
- @Autowired
- private ProductStoreRelaDao productStoreRelaDao;
- @Autowired
- private OrderProcessRecordDao orderProcessRecordDao;
- @Autowired
- private OrderRefundDao orderRefundDao;
- @Autowired
- private StoreDao storeDao;
- @Autowired
- private OfflineCartDao offlineCartDao;
- @Autowired
- private GoodsDao goodsDao;
- @Autowired
- private MerchDao merchDao;
- @Autowired
- private MngChangeDao mngChangeDao;
- @Autowired
- private StoreMngChangeDao storeMngChangeDao;
- @Autowired
- private ThirdMerchExpressDao thirdMerchExpressDao;
- @Autowired
- private MkStorePromOrderRealDao mkStorePromOrderRealDao;
- @Autowired
- private UserCampMinusDao userCampMinusDao;
- @Autowired
- private UserService userService;
- @Autowired
- private SysConfigDao sysConfigDao;
- @Autowired
- private ProductDao productDao;
- @Autowired
- private GoodsService goodsService;
- @Autowired
- private OrderWXPayRecordService orderWXPayRecordService;
- @Autowired
- private StoreService storeService;
- @Autowired
- private PickUpCodeService pickUpCodeService;
- @Autowired
- private MkStoreCampMinusService mkStoreCampMinusService;
- @Autowired
- private MkStoreTicketDiscountService mkStoreTicketDiscountService;
- @Autowired
- private CashierDao cashierDao; // 收银机查询
- @Autowired
- private CashierLoginRecordDao cashierLoginRecordDao; // 收银员登录记录
- @Autowired
- private SaleRecordDao saleRecordDao; // 销售记录
- @Autowired
- private StoreTopicDao storeTopicDao; // 查询是否有门店活动
- @Autowired
- private Mk2GoodsTopicPriceDao mk2GoodsTopicPriceDao; // 门店商品价格
- @Autowired
- private Mall2PointsRulesDao pointsRulesDao; // 积分规则
- @Autowired
- private Mall2MemberPointsDao memberPointsDao; // 用户积分
- @Autowired
- private Mall2MemberConsumptionRecordsDao memberConsumptionRecordsDao; // 会员消费记录
- @Autowired
- private MkStorePromTypeDao storePromTypeDao; // 优惠类型
- @Autowired
- private Mk2MemberBirthdayDao memberBirthdayDao; // 生日优惠
- @Autowired
- private MerchUserDao merchUserDao;
- @Autowired
- private Mall2LowPriceWarningDao lowPriceWarningDao;
- @Autowired
- private OrderRefundService orderRefundService;
- @Autowired
- private OrderExceptionRecordService orderExceptionRecordService;
- @Autowired
- private AddressInfoService addressInfoService;
- @Autowired
- private CustomsClearanceTimeliness customsClearanceTimeliness;
- @Autowired
- private HaiKongMemberTemplate haiKongMemberTemplate;
- @Autowired
- private HaiKongWarehouseTemplate haiKongWarehouseTemplate;
- @Autowired
- private HaiKongProperties haiKongProperties;
- /**
- * 免税mall接口工具类
- */
- @Autowired
- private VmcShopTemplate vmcShopTemplate;
- @Autowired
- private MkActivitiesService mkActivitiesService;
- /**
- * 满赠
- */
- @Autowired
- private MkActivitiesFullGiftService mkActivitiesFullGiftService;
- /**
- * 优惠券
- */
- @Autowired
- private MkActivitiesCouponService mkActivitiesCouponService;
- /**
- * 限时特价
- */
- @Autowired
- private MkActivitiesPromotionService mkActivitiesPromotionService;
- /**
- * 免税mall日志记录
- */
- @Autowired
- private MallVmcSendLogDao mallVmcSendLogDao;
- @Override
- public OrderEntity queryObject(Long id) {
- return orderDao.queryObject(id);
- }
- @Override
- public Double getTotalActualPrice(String merchOrderSn) {
- return orderDao.getTotalActualPrice(merchOrderSn);
- }
- @Override
- public List<OrderEntity> queryList(Map<String, Object> map) {
- return orderDao.queryList(map);
- }
- @Override
- public int queryTotal(Map<String, Object> map) {
- return orderDao.queryTotal(map);
- }
- @Override
- public int save(OrderEntity order) {
- return orderDao.save(order);
- }
- @Override
- public int update(OrderEntity order) {
- return orderDao.update(order);
- }
- /**
- * 取消订单
- *
- * @param order
- */
- @Override
- public void cancelOrder(OrderEntity order) {
- boolean needUpdateStock = true;
- if (order.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_0.getItem())) {
- order.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_101.getItem()));
- }
- orderDao.update(order);
- if (!needUpdateStock) {
- return;
- }
- // 更新库存
- updateStock(order, "管理后台取消订单");
- // 释放优惠券
- UserCouponEntity couponVo = userCouponDao.queryByOrderId(order.getId());
- if (null != couponVo) {
- userCouponDao.cancelOrder(couponVo);
- }
- //释放促销满减券
- UserCampMinusEntity userCampMinusVo = userCampMinusDao.queryUserCampByOrderId(order.getId());
- if (null != userCampMinusVo) {
- userCampMinusDao.cancelUserCampOrder(userCampMinusVo);
- }
- }
- @Override
- public int delete(Long id) {
- return orderDao.delete(id);
- }
- @Override
- public int deleteBatch(Long[] ids) {
- return orderDao.deleteBatch(ids);
- }
- @Override
- public int confirm(Long id) {
- OrderEntity orderEntity = queryObject(id);
- Integer shippingStatus = orderEntity.getShippingStatus();//发货状态
- Integer payStatus = orderEntity.getPayStatus();//付款状态
- if (2 != payStatus) {
- throw new RRException("此订单未付款,不能确认收货!");
- }
- if (4 == shippingStatus) {
- throw new RRException("此订单处于退货状态,不能确认收货!");
- }
- if (0 == shippingStatus) {
- throw new RRException("此订单未发货,不能确认收货!");
- }
- if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_301.getItem())) {
- throw new RRException("此订单已完成!");
- }
- if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_0.getItem())) {
- throw new RRException("此订单待付款!");
- }
- if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_100.getItem())) {
- throw new RRException("此订单付款中!");
- }
- if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_101.getItem())) {
- throw new RRException("此订单已取消!");
- }
- if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_102.getItem())) {
- throw new RRException("此订单已删除!");
- }
- if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())) {
- throw new RRException("此订单还未发货!");
- }
- if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_401.getItem())) {
- throw new RRException("此订单已退款!");
- }
- if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_402.getItem())) {
- throw new RRException("此订单已退款!");
- }
- orderEntity.setShippingStatus(2);
- orderEntity.setOrderStatus(301);
- orderEntity.setConfirmTime(new Date());
- orderDao.update(orderEntity);
- return 0;
- }
- @Override
- public int sendGoods(OrderEntity order) {
- Integer payStatus = order.getPayStatus();//付款状态
- if (2 != payStatus) {
- throw new RRException("此订单未付款!");
- }
- ShippingEntity shippingEntity = shippingDao.queryObject(order.getShippingId());
- if (null != shippingEntity) {
- order.setShippingName(shippingEntity.getName());
- }
- order.setOrderStatus(300);//订单已发货
- order.setShippingStatus(1);//已发货
- return orderDao.update(order);
- }
- @Override
- public Ticket printMsg(Long id) {
- OrderEntity orderEntity = queryInfos(id);
- List<OrderGoodsEntity> orderGoodsEntityList = orderEntity.getOrderGoodsEntityList();
- // 获取门店
- StoreEntity storeEntity = storeDao.queryObject(orderEntity.getStoreId());
- // 获取清关信息
- OrderProcessRecordEntity orderProcessRecordEntity =
- orderProcessRecordDao.queryObjectByOrderSn(orderEntity.getOrderSn());
- // 小票头
- TicketHead head = new TicketHead();
- head.setTitle(OmsMerchPropertiesBuilder.instance().getMerchName() + storeEntity.getStoreName());
- // head.setMemberId(orderEntity.getUserName().toString());
- head.setOrderId(orderEntity.getOrderSn());
- head.setTradeTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss EEE").format(new Date()));
- // 商品信息
- Integer goodsTotal = 0; // 商品总个数
- BigDecimal total = Constant.ZERO; // 商品总计
- BigDecimal taxTotal = Constant.ZERO; //税费总计
- List<Goods> goodsList = new ArrayList<>();
- for (OrderGoodsEntity orderGoods : orderGoodsEntityList) {
- goodsTotal += orderGoods.getNumber();
- total = total.add(orderGoods.getRetailPrice().multiply(new BigDecimal(orderGoods.getNumber())))
- .setScale(2, BigDecimal.ROUND_HALF_UP);
- BigDecimal currentTax = orderGoods.getGoodsRate().multiply(orderGoods.getRetailPrice().multiply(new BigDecimal(orderGoods.getNumber())))
- .setScale(2, BigDecimal.ROUND_HALF_UP);
- taxTotal = taxTotal.add(currentTax);
- Goods goods = new Goods(orderGoods.getGoodsName(),
- orderGoods.getRetailPrice().toString(),
- currentTax.toString(),
- orderGoods.getNumber().toString(),
- new BigDecimal(orderGoods.getNumber()).multiply(orderGoods.getRetailPrice()).setScale(2, RoundingMode.HALF_UP).toString());
- goodsList.add(goods);
- LOGGER.info(goods.toString());
- }
- // 收银信息
- CashInfo cashInfo = new CashInfo();
- cashInfo.setGoodsTotal(goodsTotal.toString());
- cashInfo.setTotal(total.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
- cashInfo.setTaxTotal(taxTotal.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
- cashInfo.setReceipts(orderEntity.getActualPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
- cashInfo.setOddChange("0.00");
- cashInfo.setCoupon(orderEntity.getCouponPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
- cashInfo.setFreight(
- new BigDecimal(orderEntity.getFreightPrice()).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
- cashInfo.setPaymentMode("微信支付");
- // 海关清单
- CusListing cusListing = new CusListing();
- cusListing.setOrderId(orderEntity.getOrderSn());
- if (!orderEntity.getOrderBizType().equalsIgnoreCase(Dict.orderBizType.item_11.getItem())) {
- cusListing.setWaybillId(orderProcessRecordEntity.getLogisticsNo());
- cusListing.setInvtNo(orderProcessRecordEntity.getInvtNo());
- cusListing.setConsignee(orderEntity.getConsignee());
- cusListing.setConsigneeTel(orderEntity.getMobile());
- }
- cusListing.setOriginAddress(PrintTicketPropertiesBuilder.instance().getAddress());
- cusListing.setDeliveryAddress(storeEntity.getStoreAddress());
- return TicketPrintUtil.print(head, goodsList, cashInfo, cusListing);
- }
- @Override
- public Ticket printMsg(Long id, String sessionId) {
- OrderEntity orderEntity = queryInfos(id);
- List<OrderGoodsEntity> orderGoodsEntityList = orderEntity.getOrderGoodsEntityList();
- // 获取门店
- StoreEntity storeEntity = storeDao.queryObject(orderEntity.getStoreId());
- // 获取清关信息
- OrderProcessRecordEntity orderProcessRecordEntity =
- orderProcessRecordDao.queryObjectByOrderSn(orderEntity.getOrderSn());
- // 小票头
- TicketHead head = new TicketHead();
- head.setTitle(storeEntity.getStoreName());
- // head.setMemberId(orderEntity.getUserName().toString());
- head.setOrderId(orderEntity.getOrderSn());
- head.setTradeTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss EEE").format(orderEntity.getPayTime()));
- // 商品信息
- Integer goodsTotal = 0; // 商品总个数
- BigDecimal total = Constant.ZERO; // 商品总计
- BigDecimal taxTotal = Constant.ZERO; //税费总计
- List<Goods> goodsList = new ArrayList<>();
- BigDecimal discountedPrice = Constant.ZERO; // 优惠金额
- for (OrderGoodsEntity orderGoods : orderGoodsEntityList) {
- goodsTotal += orderGoods.getNumber();
- total = total.add(orderGoods.getRetailPrice().multiply(new BigDecimal(orderGoods.getNumber())))
- .setScale(2, BigDecimal.ROUND_HALF_UP);
- discountedPrice = discountedPrice.add(orderGoods.getDiscountedPrice());
- // 税前价
- BigDecimal beforeTaxPrice = orderGoods.getRetailPrice().divide(new BigDecimal(1).add(orderGoods.getGoodsRate()), 2, RoundingMode.HALF_UP);
- GoodsEntity goodsEntity = goodsService.queryObject(orderGoods.getGoodsId());
- BigDecimal goodsTax = CalculateTax.calculateFinalTax(goodsEntity, orderGoods.getRetailPrice(), goodsService).setScale(3, RoundingMode.HALF_UP);
- goodsTax = goodsTax.multiply(new BigDecimal(orderGoods.getNumber())).setScale(2, RoundingMode.HALF_UP);
- taxTotal = taxTotal.add(goodsTax).setScale(2, RoundingMode.HALF_UP);
- Goods goods = new Goods(orderGoods.getGoodsName(),
- orderGoods.getRetailPrice().toString(), // 含税价
- // beforeTaxPrice.toString(),// 税前价
- goodsTax.toString(),
- orderGoods.getNumber().toString(),
- new BigDecimal(orderGoods.getNumber()).multiply(orderGoods.getRetailPrice()).setScale(2, RoundingMode.HALF_UP).toString(),
- orderGoods.getDiscountedPrice().toString());
- goodsList.add(goods);
- }
- // 收银信息
- CashInfo cashInfo = new CashInfo();
- cashInfo.setGoodsTotal(goodsTotal.toString());
- cashInfo.setTotal(total.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
- cashInfo.setTaxTotal(taxTotal.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
- cashInfo.setReceipts(orderEntity.getActualPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
- cashInfo.setOddChange(discountedPrice.toString());
- cashInfo.setCoupon(orderEntity.getCouponPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
- cashInfo.setFreight(
- new BigDecimal(orderEntity.getFreightPrice()).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
- if ("alipay".equals(orderEntity.getPayFlag())) {
- cashInfo.setPaymentMode("支付宝支付");
- } else {
- cashInfo.setPaymentMode("微信支付");
- }
- // 海关清单
- CusListing cusListing = new CusListing();
- cusListing.setOrderId(orderEntity.getOrderSn());
- if (!orderEntity.getOrderBizType().equalsIgnoreCase(Dict.orderBizType.item_11.getItem())) {
- cusListing.setWaybillId(orderProcessRecordEntity.getLogisticsNo());
- cusListing.setInvtNo(orderProcessRecordEntity.getInvtNo());
- cusListing.setConsignee(orderEntity.getConsignee());
- // 脱敏设置
- if (StringUtils.isNotEmpty(cusListing.getConsignee()) && cusListing.getConsignee().length() > 1) {
- cusListing.setConsignee(new StringBuilder(cusListing.getConsignee()).replace(1, 2, "*").toString());
- }
- cusListing.setConsigneeTel(orderEntity.getMobile());
- if (StringUtils.isNotEmpty(cusListing.getConsigneeTel())) {
- cusListing.setConsigneeTel(new StringBuilder(cusListing.getConsigneeTel()).replace(3, 7, "****").toString());
- // cusListing.setConsigneeTel(cusListing.getConsigneeTel());
- }
- }
- cusListing.setOriginAddress(PrintTicketPropertiesBuilder.instance().getAddress());
- cusListing.setDeliveryAddress(storeEntity.getStoreAddress());
- // 尝试在取货码表中查询数据,如果有的话就改变状态
- String orderSn = orderEntity.getOrderSn();
- PickUpCodeEntity pickUpCodeEntity = pickUpCodeService.queryObject(orderSn);
- if (pickUpCodeEntity != null) {
- pickUpCodeEntity.setPickUpCodeStatus("1");
- pickUpCodeService.update(pickUpCodeEntity);
- // try {
- // WebSocketServer.delete(sessionId,orderEntity.getStoreId(),pickUpCodeEntity);
- // } catch (IOException e) {
- // e.printStackTrace();
- // }
- }
- TicketMailInfo mailInfo = new TicketMailInfo();
- String exprNo = orderProcessRecordEntity.getLogisticsNo();
- if (StringUtils.isNullOrEmpty(exprNo)) {
- throw new RRException("快递面单为空,请联系客服");
- }
- //图片地址
- mailInfo.setStoreImgUrl(storeEntity.getStoreImgUrl()==null?"/statics/img/cw_qrcode.png":storeEntity.getStoreImgUrl().trim());
- mailInfo.setExprNo(exprNo);
- String logoUrl = "/statics/img/yto_logo.jpg";
- Map<String, String> logoMap = new HashMap<>();
- logoMap.put("yto", "/statics/img/yto_logo.jpg");
- logoMap.put("best", "/statics/img/bestex_logo3.png");
- if (StringUtils.isNotEmpty(orderEntity.getShippingCode()) && logoMap.containsKey(orderEntity.getShippingCode())) {
- logoUrl = logoMap.get(orderEntity.getShippingCode());
- }
- mailInfo.setExprLogoUrl(logoUrl);
- byte[] barCode128 = BarcodeUtil.generateBarCode128(exprNo, 6.0D, null, true, false);
- String exprNoBase64Img = new String(Base64.getEncoder().encode(barCode128));
- mailInfo.setShopTel(storeEntity.getTelephoneNumber()==null?"0752-2688660":storeEntity.getTelephoneNumber().trim());
- // 发货人
- mailInfo.setSenderTel("0752-2688660");
- mailInfo.setSenderName("CW澳洲大药房");
- mailInfo.setSenderProvince("广东省");
- mailInfo.setSenderCity("深圳市");
- mailInfo.setSenderDistrict("南山区");
- mailInfo.setSenderAddress("前海综合保税区W104");
- // 收货人
- mailInfo.setConsigneeMob(new StringBuilder(orderEntity.getMobile()).replace(3, 7, "****").toString());
- // mailInfo.setConsigneeMob(orderEntity.getMobile());
- mailInfo.setConsigneeName(new StringBuilder(orderEntity.getConsignee()).replace(1, 2, "*").toString());
- mailInfo.setConsigneeProvince(orderEntity.getProvince());
- mailInfo.setConsigneeCity(orderEntity.getCity());
- mailInfo.setConsigneeDistrict(orderEntity.getDistrict());
- mailInfo.setConsigneeAddress(orderEntity.getAddress());
- mailInfo.setExprNoBase64Img(exprNoBase64Img);
- return TicketPrintUtil.print(head, goodsList, cashInfo, cusListing, mailInfo);
- }
- /**
- * 退款
- */
- @Transactional
- public void refund(OrderEntity order) {
- boolean needUpdateStock = true;
- if (order.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())) {
- order.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_401.getItem()));
- }
- if (Dict.payFlag.item_cash.getItem().equals(order.getPayFlag())) {
- order.setPayStatus(Integer.parseInt(Dict.payStatus.item_4.getItem()));
- }
- orderDao.update(order);//修改为退款中
- // TODO: 2019/6/13 定时任务查询退款成功后释放库存、优惠券
- /*// 判断是否有优惠券
- UserCouponEntity couponVo = userCouponDao.queryByOrderId(order.getId());
- if (null != couponVo) {
- userCouponDao.cancelOrder(couponVo);
- }
- if (!needUpdateStock) {
- return;
- }
- // 更新库存
- updateStock(order, "管理后台订单退款");*/
- // updateStock(order, "管理后台订单退款");
- queryStorePromRealUpdateIsScan(order);
- }
- /**
- * 退款
- */
- @Transactional
- public void refund(OrderEntity order, WechatRefundApiResult result) {
- boolean needUpdateStock = true;
- if (order.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())) {
- order.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_401.getItem()));
- }
- if (Dict.payFlag.item_cash.getItem().equals(order.getPayFlag())) {
- order.setPayStatus(Integer.parseInt(Dict.payStatus.item_4.getItem()));
- } else {
- order.setPayStatus(Integer.parseInt(Dict.payStatus.item_5.getItem()));
- OrderRefundEntity mallOrderRefund = orderRefundDao.queryObjectByOrderId(order.getId());
- OrderRefundEntity orderRefund = new OrderRefundEntity();
- orderRefund.setRefundId(result.getRefund_id());
- try {
- orderRefund.setOutRefundNo(result.getOut_trade_no());
- } catch (Exception e) {
- e.printStackTrace();
- }
- orderRefund.setRefundMoney(BigDecimal.valueOf(Long.valueOf(result.getRefund_fee())).divide(Constant.ONE_HUNDRED));
- orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_5.getItem()));//退款处理中
- orderRefund.setModTime(new Date());
- if (mallOrderRefund != null) {
- orderRefund.setId(mallOrderRefund.getId());
- orderRefund.setRefundType(mallOrderRefund.getRefundType());
- orderRefundDao.update(orderRefund);
- } else {
- orderRefund.setOrderId(Integer.parseInt(order.getId() + ""));
- orderRefund.setUserId(Integer.parseInt(order.getUserId() + ""));
- orderRefund.setCreateTime(new Date());
- List<OrderEntity> list = orderDao.queryObjectByMerchOrderSn(order.getMerchOrderSn());
- if (list.size() > 1) {//多条订单
- orderRefund.setRefundType(Integer.parseInt(Dict.RefundType.item_2.getItem()));//部分退款
- } else {
- orderRefund.setRefundType(Integer.parseInt(Dict.RefundType.item_1.getItem()));//用户全额退款
- }
- orderRefundDao.save(orderRefund);//退款记录
- }
- }
- orderDao.update(order);//
- // TODO: 2019/6/13 定时任务查询退款成功后释放库存、优惠券
- /*// 判断是否有优惠券
- UserCouponEntity couponVo = userCouponDao.queryByOrderId(order.getId());
- if (null != couponVo) {
- userCouponDao.cancelOrder(couponVo);
- }
- if (!needUpdateStock) {
- return;
- }
- // 更新库存
- updateStock(order, "管理后台订单退款");*/
- // updateStock(order, "管理后台订单退款");
- queryStorePromRealUpdateIsScan(order);
- }
- @Transactional
- public void refund(OrderEntity order, AliPayMicropayApiResult result) {
- if (order.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())) {
- order.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_401.getItem()));
- }
- if (Dict.payFlag.item_cash.getItem().equals(order.getPayFlag())) {
- order.setPayStatus(Integer.parseInt(Dict.payStatus.item_4.getItem()));
- } else {
- order.setPayStatus(Integer.parseInt(Dict.payStatus.item_4.getItem()));
- OrderRefundEntity mallOrderRefund = orderRefundDao.queryObjectByOrderId(order.getId());
- OrderRefundEntity orderRefund = new OrderRefundEntity();
- orderRefund.setRefundId(result.getTradeNo());
- orderRefund.setOutRefundNo(result.getOutTradeNo());
- orderRefund
- .setRefundMoney(new BigDecimal(result.getRefundFee()).divide(Constant.ONE_HUNDRED));
- orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_2.getItem()));//退款处理中
- orderRefund.setModTime(new Date());
- if (mallOrderRefund != null) {
- orderRefund.setId(mallOrderRefund.getId());
- orderRefund.setRefundType(mallOrderRefund.getRefundType());
- orderRefundDao.update(orderRefund);
- } else {
- orderRefund.setOrderId(Integer.parseInt(order.getId() + ""));
- orderRefund.setUserId(Integer.parseInt(order.getUserId() + ""));
- orderRefund.setCreateTime(new Date());
- List<OrderEntity> list = orderDao.queryObjectByMerchOrderSn(order.getMerchOrderSn());
- if (list.size() > 1) {//多条订单
- orderRefund.setRefundType(Integer.parseInt(Dict.RefundType.item_2.getItem()));//部分退款
- } else {
- orderRefund.setRefundType(Integer.parseInt(Dict.RefundType.item_1.getItem()));//用户全额退款
- }
- orderRefundDao.save(orderRefund);//退款记录
- }
- }
- orderDao.update(order);//修改为退款中
- updateStock(order, "收银端退款");
- }
- /**
- * 平安退款逻辑处理
- *
- * @param order
- * @param result
- */
- @Transactional
- public void pinganRefund(OrderEntity order, net.sf.json.JSONObject result, String refundId) {
- boolean needUpdateStock = true;
- if (order.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())) {
- order.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_401.getItem()));
- }
- order.setPayStatus(Integer.parseInt(Dict.payStatus.item_3.getItem()));
- OrderRefundEntity orderRefund = new OrderRefundEntity();
- orderRefund.setRefundId(refundId);
- orderRefund.setOutRefundNo(result.getString("ord_no"));
- orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_5.getItem()));//退款处理中
- orderRefund.setModTime(new Date());
- orderRefund.setRefundMoney(BigDecimal.valueOf(result.getInt("trade_amount")).divide(Constant.ONE_HUNDRED));
- OrderRefundEntity mallOrderRefund = orderRefundDao.queryObjectByOrderId(order.getId());
- if (mallOrderRefund != null) {
- orderRefund.setRefundType(mallOrderRefund.getRefundType());
- orderRefund.setId(mallOrderRefund.getId());
- orderRefundDao.update(orderRefund);
- } else {//退款记录不存在
- orderRefund.setOrderId(Integer.parseInt(order.getId() + ""));
- orderRefund.setUserId(Integer.parseInt(order.getUserId() + ""));
- orderRefund.setCreateTime(new Date());
- orderRefundDao.save(orderRefund);//退款记录
- }
- orderDao.update(order);//修改为退款中
- // TODO: 2019/6/13 定时任务查询退款成功后释放库存、优惠券
- /*// 判断是否有优惠券
- UserCouponEntity couponVo = userCouponDao.queryByOrderId(order.getId());
- if (null != couponVo) {
- userCouponDao.cancelOrder(couponVo);
- }
- if (!needUpdateStock) {
- return;
- }
- // 更新库存
- updateStock(order, "管理后台平安退款订单");*/
- queryStorePromRealUpdateIsScan(order);
- }
- /**
- * 微信国际退款逻辑处理
- *
- * @param order
- * @param result
- */
- @Transactional
- public void globalRefund(OrderEntity order, WechatGlobalRefundApiResult result) {
- boolean needUpdateStock = true;
- if (order.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())) {
- order.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_401.getItem()));
- }
- order.setPayStatus(Integer.parseInt(Dict.payStatus.item_3.getItem()));
- OrderRefundEntity orderRefund = new OrderRefundEntity();
- orderRefund.setRefundId(result.getRefund_id());
- orderRefund.setOutRefundNo(result.getOut_refund_no());
- orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_5.getItem()));//退款处理中
- orderRefund.setModTime(new Date());
- orderRefund.setRefundMoney(BigDecimal.valueOf(Long.valueOf(result.getRefund_fee())).divide(Constant.ONE_HUNDRED));
- orderRefund.setRefundFeeType(result.getRefund_fee_type());
- if (org.apache.commons.lang3.StringUtils.isNotEmpty(result.getTotal_fee())) {
- orderRefund.setTotalFee(Integer.parseInt(BigDecimal.valueOf(Long.valueOf(result.getTotal_fee())).divide(Constant.ONE_HUNDRED).toString()));
- }
- orderRefund.setFeeType(result.getFee_type());
- if (org.apache.commons.lang3.StringUtils.isNotEmpty(result.getCash_fee())) {
- orderRefund.setCashFee(Integer.parseInt(BigDecimal.valueOf(Long.valueOf(result.getCash_fee())).divide(Constant.ONE_HUNDRED).toString()));
- }
- orderRefund.setCashFeeType(result.getCash_fee_type());
- if (org.apache.commons.lang3.StringUtils.isNotEmpty(result.getCash_refund_fee())) {
- orderRefund.setCashRefundFee(Integer.parseInt(BigDecimal.valueOf(Long.valueOf(result.getCash_refund_fee())).divide(Constant.ONE_HUNDRED).toString()));
- }
- orderRefund.setCashRefundFeeType(result.getCash_refund_fee_type());
- OrderRefundEntity mallOrderRefund = orderRefundDao.queryObjectByOrderId(order.getId());
- if (mallOrderRefund != null) {
- orderRefund.setRefundType(mallOrderRefund.getRefundType());
- orderRefund.setId(mallOrderRefund.getId());
- orderRefundDao.update(orderRefund);
- } else {//退款记录不存在
- orderRefund.setOrderId(Integer.parseInt(order.getId() + ""));
- orderRefund.setUserId(Integer.parseInt(order.getUserId() + ""));
- orderRefund.setCreateTime(new Date());
- orderRefundDao.save(orderRefund);//退款记录
- }
- orderDao.update(order);//修改为退款中
- // TODO: 2019/6/13 定时任务查询退款成功后释放库存、优惠券
- /*// 判断是否有优惠券
- UserCouponEntity couponVo = userCouponDao.queryByOrderId(order.getId());
- if (null != couponVo) {
- userCouponDao.cancelOrder(couponVo);
- }
- if (!needUpdateStock) {
- return;
- }
- // 更新库存
- updateStock(order, "管理后台微信国际退款订单");*/
- queryStorePromRealUpdateIsScan(order);
- }
- private synchronized void restoreInventory(OrderEntity order, String changeReason) {
- Map<String, Object> map = new HashMap();
- SysUserEntity user = ShiroUtils.getUserEntity();
- map.put("orderId", order.getId());
- List<OrderGoodsEntity> orderGoodsVoList = orderGoodsDao.queryList(map);
- for (OrderGoodsEntity orderGoodsEntity : orderGoodsVoList) {
- ProductStoreRelaEntity storeRelaEntity = productStoreRelaDao
- .queryByGoodsIdAndStoreId(order.getStoreId().longValue(), orderGoodsEntity.getGoodsId().longValue());
- if (null == storeRelaEntity || null == storeRelaEntity.getSellVolume()) {
- storeRelaEntity.setSellVolume(0);
- }
- BigDecimal sellVolume = new BigDecimal(storeRelaEntity.getSellVolume() - orderGoodsEntity.getNumber());//销售量
- if (sellVolume.compareTo(Constant.ZERO) < 0) {
- sellVolume = Constant.ZERO;
- }
- // GoodsEntity goodsEntity = goodsDao.queryObject(orderGoodsEntity.getGoodsId());
- // if (goodsEntity != null) {
- // stockNum = goodsEntity.getGoodsNumber();
- // //还原商户商品库存
- // resetGoodsStock(stockNum, storeRelaEntity, orderGoodsEntity, sellVolume, changeReason, user);
- // }
- Integer stockNum = 0;
- if (null != storeRelaEntity.getStockNum()) {
- stockNum = storeRelaEntity.getStockNum();
- resetStoreGoodsStock(stockNum, storeRelaEntity, orderGoodsEntity, sellVolume, changeReason, user);//还原门店库存
- }
- }
- }
- private synchronized void updateStock(OrderEntity order, String changeReason) {
- Map<String, Object> map = new HashMap();
- SysUserEntity user = ShiroUtils.getUserEntity();
- map.put("orderId", order.getId());
- List<OrderGoodsEntity> orderGoodsVoList = orderGoodsDao.queryList(map);
- for (OrderGoodsEntity orderGoodsEntity : orderGoodsVoList) {
- ProductStoreRelaEntity storeRelaEntity = productStoreRelaDao
- .queryByGoodsIdAndStoreId(order.getStoreId().longValue(), orderGoodsEntity.getGoodsId().longValue());
- // .queryByStoreIdProductId(Long.valueOf(order.getStoreId()),Long.valueOf(orderGoodsEntity.getProductId()));
- if (null == storeRelaEntity || null == storeRelaEntity.getSellVolume()) {
- storeRelaEntity.setSellVolume(0);
- }
- BigDecimal sellVolume = new BigDecimal(storeRelaEntity.getSellVolume() - orderGoodsEntity.getNumber());//销售量
- if (sellVolume.compareTo(Constant.ZERO) < 0) {
- sellVolume = Constant.ZERO;
- }
- Integer stockNum = 0;
- GoodsEntity goodsEntity = goodsDao.queryObject(orderGoodsEntity.getGoodsId());
- if (goodsEntity != null) {
- stockNum = goodsEntity.getGoodsNumber();
- //还原商户商品库存
- resetGoodsStock(stockNum, storeRelaEntity, orderGoodsEntity, sellVolume, changeReason, user);
- }
- if (null != storeRelaEntity.getStockNum()) {
- stockNum = storeRelaEntity.getStockNum();
- //普通商品不受共享库存影响,直接取门店配置库存
- //该商品所属第三方商户不是共享库存
- if (goodsEntity.getIsStockShare().equalsIgnoreCase(Dict.isStockShare.item_0.getItem())) {
- resetStoreGoodsStock(stockNum, storeRelaEntity, orderGoodsEntity, sellVolume, changeReason, user);//还原门店库存
- } else {
- //该商品所属第三方商户是共享库存,但商品业务类型不是00保税备货
- if (!goodsEntity.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_00.getItem())) {
- resetStoreGoodsStock(stockNum, storeRelaEntity, orderGoodsEntity, sellVolume, changeReason, user);//还原门店库存
- }
- }
- }
- //该商品所属第三方商户为共享库存,且是保税备货商品,取消订单时改变
- updateGoodsByIsShareStock(goodsEntity);
- }
- }
- /**
- * 更新商品库存数量变化后是否已共享为0“未共享”
- *
- * @param goodsInfo
- */
- private void updateGoodsByIsShareStock(GoodsEntity goodsInfo) {
- //该商品所属第三方商户为共享库存,且是保税备货商品
- if (goodsInfo.getIsStockShare().equalsIgnoreCase(Dict.isStockShare.item_1.getItem())
- && goodsInfo.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_00.getItem())) {
- GoodsEntity goodsVo = new GoodsEntity();
- goodsVo.setId(goodsInfo.getId());
- //商品库存数量变化后是否已共享,0:否,1:是(下单、退款、取消订单触发)
- goodsVo.setIsGoodsShareStock(Dict.isGoodsShareStock.item_0.getItem());
- goodsDao.update(goodsVo);
- }
- }
- /**
- * 还原商品总库存
- *
- * @param stockNum
- * @param storeRelaEntity
- * @param orderGoodsEntity
- * @param sellVolume
- * @param changeReason
- * @param user
- */
- private void resetGoodsStock(Integer stockNum, ProductStoreRelaEntity storeRelaEntity,
- OrderGoodsEntity orderGoodsEntity, BigDecimal sellVolume, String changeReason, SysUserEntity user) {
- GoodsEntity goodsEntity = goodsDao.queryObject(storeRelaEntity.getGoodsId());
- if (goodsEntity != null) {
- goodsEntity.setGoodsNumber(stockNum + orderGoodsEntity.getNumber());
- // goodsEntity.setSellVolume(Integer.parseInt(goodsSellVolume.toString()));
- if ("oms退单成功,恢复库存".equals(changeReason)) {
- goodsEntity.setToBeRestored(goodsEntity.getToBeRestored() - orderGoodsEntity.getNumber());
- }
- goodsDao.update(goodsEntity);
- String username = "system";
- if (user != null) {
- username = user.getUsername();
- }
- MngChangeEntity mngChangeEntity = new MngChangeEntity();
- mngChangeEntity.setGoodsId(Integer.parseInt(String.valueOf(goodsEntity.getId())));
- mngChangeEntity.setThirdPartyMerchCode(goodsEntity.getThirdPartyMerchCode());
- mngChangeEntity.setChangeReason(changeReason);
- mngChangeEntity.setChangeType(Dict.changeType.item_0.getItem());
- mngChangeEntity.setChangeNum(orderGoodsEntity.getNumber());//变化数
- mngChangeEntity.setOriginalNum(stockNum);//原库存数
- mngChangeEntity.setValidNum(stockNum + orderGoodsEntity.getNumber());//可用数
- mngChangeEntity.setCreateTime(new Date());
- mngChangeEntity.setModTime(new Date());
- mngChangeEntity.setCreaterSn(username);
- mngChangeEntity.setModerSn(username);
- mngChangeEntity.setIsValid(0);
- mngChangeEntity.setMerchSn(goodsEntity.getMerchSn());
- mngChangeDao.save(mngChangeEntity);
- }
- }
- /**
- * 还原门店商品库存
- *
- * @param stockNum
- * @param storeRelaEntity
- * @param orderGoodsEntity
- * @param sellVolume
- * @param changeReason
- * @param user
- */
- private void resetStoreGoodsStock(Integer stockNum, ProductStoreRelaEntity storeRelaEntity,
- OrderGoodsEntity orderGoodsEntity, BigDecimal sellVolume, String changeReason, SysUserEntity user) {
- storeRelaEntity.setSellVolume(Integer.parseInt(sellVolume.toString())); // 减退库存
- storeRelaEntity.setStockNum(stockNum + orderGoodsEntity.getNumber());//库存数量
- if ("oms退单成功,恢复库存".equals(changeReason)) {
- storeRelaEntity.setToBeRestored(storeRelaEntity.getToBeRestored() - orderGoodsEntity.getNumber());
- }
- productStoreRelaDao.update(storeRelaEntity);
- String username = "system";
- if (user != null) {
- username = user.getUsername();
- }
- StoreMngChangeEntity storeMngChangeEntity = new StoreMngChangeEntity();
- storeMngChangeEntity.setChangeType(Dict.changeType.item_0.getItem());
- storeMngChangeEntity.setChangeReason(changeReason);
- storeMngChangeEntity.setGoodsId(Integer.parseInt(String.valueOf(storeRelaEntity.getGoodsId())));
- storeMngChangeEntity.setStoreId(Integer.parseInt(String.valueOf(storeRelaEntity.getStoreId())));
- storeMngChangeEntity.setMerchSn(storeRelaEntity.getMerchSn());
- storeMngChangeEntity.setStoreChangeNum(orderGoodsEntity.getNumber());
- storeMngChangeEntity.setStoreOriginalNum(stockNum);
- storeMngChangeEntity.setStoreValidNum(stockNum + orderGoodsEntity.getNumber());
- storeMngChangeEntity.setCreateTime(new Date());
- storeMngChangeEntity.setModTime(new Date());
- storeMngChangeEntity.setCreaterSn(username);
- storeMngChangeEntity.setModerSn(username);
- storeMngChangeEntity.setIsValid(0);
- storeMngChangeDao.save(storeMngChangeEntity);
- }
- /**
- * 海控还原门店商品库存
- * @param stockNum
- * @param storeRelaEntity
- * @param orderGoodsEntity
- * @param sellVolume
- * @param user
- */
- private void resetStoreGoodsStockMall(Integer stockNum, ProductStoreRelaEntity storeRelaEntity,
- OrderGoodsEntity orderGoodsEntity, BigDecimal sellVolume,SysUserEntity user) {
- storeRelaEntity.setSellVolume(Integer.parseInt(sellVolume.toString())); // 减退库存
- //库存数量 + 商品数量
- storeRelaEntity.setStockNum(stockNum + orderGoodsEntity.getNumber());//库存数量
- //待退款数量 - 商品数量
- storeRelaEntity.setToBeRestored(storeRelaEntity.getToBeRestored() - orderGoodsEntity.getNumber());
- productStoreRelaDao.update(storeRelaEntity);
- String username = "system";
- if (user != null) {
- username = user.getUsername();
- }
- StoreMngChangeEntity storeMngChangeEntity = new StoreMngChangeEntity();
- storeMngChangeEntity.setChangeType(Dict.changeType.item_0.getItem());
- storeMngChangeEntity.setChangeReason("前端退款");
- storeMngChangeEntity.setGoodsId(storeRelaEntity.getGoodsId().intValue());
- storeMngChangeEntity.setStoreId(storeRelaEntity.getStoreId().intValue());
- storeMngChangeEntity.setMerchSn(storeRelaEntity.getMerchSn());
- storeMngChangeEntity.setStoreChangeNum(orderGoodsEntity.getNumber());
- storeMngChangeEntity.setStoreOriginalNum(stockNum);
- storeMngChangeEntity.setStoreValidNum(stockNum + orderGoodsEntity.getNumber());
- storeMngChangeEntity.setCreateTime(new Date());
- storeMngChangeEntity.setModTime(new Date());
- storeMngChangeEntity.setCreaterSn(username);
- storeMngChangeEntity.setModerSn(username);
- storeMngChangeEntity.setIsValid(0);
- storeMngChangeDao.save(storeMngChangeEntity);
- }
- /**
- * 查询该退款订单编号是否是推广渠道订单,是则修改渠道定时扫描状态
- *
- * @param orderInfo
- */
- private void queryStorePromRealUpdateIsScan(OrderEntity orderInfo) {
- Map map = new HashMap();
- map.put("orderId", orderInfo.getId());
- List<MkStorePromOrderRealEntity> list = mkStorePromOrderRealDao.queryPromRealListByMap(map);
- if (list.size() > 0) {
- for (MkStorePromOrderRealEntity mkStorePromOrderRealEntity : list) {
- mkStorePromOrderRealEntity.setIsPromStatScan(Dict.isDistSellScan.item_0.getItem());
- mkStorePromOrderRealDao.update(mkStorePromOrderRealEntity);
- }
- }
- }
- /**
- * 处理用户退款申请
- *
- * @param orderInfo
- */
- @Transactional
- public void applyRefundDeal(OrderEntity orderInfo, OrderRefundEntity refundEntity) {
- refundEntity.setApprovalTime(new Date());
- // refundEntity.setApprover(ShiroUtils.getUserId());
- // 退积分
- try {
- Integer integral = 1;
- if (orderInfo.getActualPrice().intValue() > 0) {
- integral = orderInfo.getActualPrice().intValue();
- }
- if (refundEntity.getRefundStatus() == 2) {
- orderInfo.setOrderStatus(401);
- // UserEntity entity = userDao.queryObject(orderInfo.getUserId());
- } else {
- orderInfo.setOrderStatus(201);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- orderRefundDao.update(refundEntity);
- orderDao.update(orderInfo);
- }
- @Override
- public OrderRefundEntity queryRefundObject(Long refundId) {
- return orderRefundDao.queryObject(refundId);
- }
- @Override
- public List<OrderRefundEntity> queryRefundList(Map<String, Object> map) {
- return orderRefundDao.queryList(map);
- }
- @Override
- public int queryRefundTotal(Map<String, Object> map) {
- return orderRefundDao.queryTotal(map);
- }
- @Override
- public int getUserOrderInfo(Map<String, Object> map) {
- int result = 0;
- String type = (String) map.get("type");
- if ("yfkOrderUserSum".equals(type)) {
- result = orderDao.getYfkOrderUserSum(map);
- } else if ("oderUserSum".equals(type)) {
- result = orderDao.getOderUserSum(map);
- } else if ("todayUserOrder".equals(type)) {
- result = orderDao.getTodayUserOrder(map);
- } else if ("todayUserSales".equals(type)) {
- result = orderDao.getTodayUserSales(map);
- } else if ("incomeSum".equals(type)) {
- result = orderDao.getIncomeSum(map);
- } else if ("payedOrderCount".equals(type)) {
- result = orderDao.getPayedOrderCount(map);
- }
- return result;
- }
- @Override
- public Map getLogistics(Long id) {
- OrderEntity orderEntity = queryObject(id);
- if (orderEntity == null) {
- throw new RRException("此订单不存在!");
- }
- if (orderEntity.getShippingStatus() == 0) {
- if (orderEntity.getOrderBizType().equalsIgnoreCase(Dict.orderBizType.item_00.getItem()) ||
- orderEntity.getOrderBizType().equalsIgnoreCase(Dict.orderBizType.item_02.getItem())) {
- throw new RRException("此订单还未发货!");
- } else {
- if (StringUtils.isNullOrEmpty(orderEntity.getShippingNo())) {
- throw new RRException("此订单还未发货!");
- }
- }
- }
- Map logisticsInfo = Maps.newHashMap();
- List<WuliuEntity> wuliuEntityList = new ArrayList<>();
- OrderProcessRecordEntity orderProcessRecordEntity =
- orderProcessRecordDao.queryObjectByOrderSn(orderEntity.getOrderSn());
- if (orderProcessRecordEntity != null) {
- if (orderEntity.getOrderBizType().equals(Dict.orderBizType.item_10.getItem()) ||
- orderEntity.getOrderBizType().equals(Dict.orderBizType.item_02.getItem())) {
- WuliuEntity wuliuEntity = new WuliuEntity();
- wuliuEntity.setAcceptTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
- .format(orderProcessRecordEntity.getCustomsSuccTime()));
- wuliuEntity.setAcceptStation(PrintTicketPropertiesBuilder.instance().getAddress() + "送达" +
- storeDao.queryObject(orderEntity.getStoreId()).getStoreAddress() +
- ";交易完成,用户已提走");
- wuliuEntityList.add(wuliuEntity);
- }
- if (StringUtils.isNotEmpty(orderEntity.getShippingCode()) &&
- StringUtils.isNotEmpty(orderEntity.getShippingNo()) &&
- orderProcessRecordEntity.getShipmentStartTime() != null) {
- if (orderEntity.getShippingCode().equalsIgnoreCase("SF")) {
- StoreEntity storeEntity = storeDao.queryObject(orderEntity.getStoreId());
- if (storeEntity == null) {
- throw new RRException("查询顺丰订单异常,订单的门店信息不存在");
- }
- ThirdMerchExpressEntity thirdMerchExpressEntity = thirdMerchExpressDao.getThirdMerchExpressByThirdCode(storeEntity.getThirdPartyMerchCode());
- if (thirdMerchExpressEntity == null) {
- throw new RRException("查询顺丰订单异常,缺失商户快递账号信息");
- }
- SfRouteServiceResponseEntity entity = SFUtil.routeService(orderEntity.getShippingNo(), thirdMerchExpressEntity.getExpressAccount(),
- thirdMerchExpressEntity.getExpressPwd(), SFPropertiesBuilder.instance().getUrl());
- // SfRouteServiceResponseEntity entity = SFUtil.routeService("254355029325", thirdMerchExpressEntity.getExpressAccount(),
- // thirdMerchExpressEntity.getExpressPwd(), SFPropertiesBuilder.instance().getUrl());//444072971585
- if (entity.getHead().equalsIgnoreCase("OK")) {
- if (entity.getBody() == null) {
- WuliuEntity wuliuEntity = new WuliuEntity();
- wuliuEntity.setAcceptStation("暂无物流轨迹");
- wuliuEntityList.add(wuliuEntity);
- } else {
- if (entity.getBody().getRouteResponse() == null) {
- WuliuEntity wuliuEntity = new WuliuEntity();
- wuliuEntity.setAcceptStation("暂无物流轨迹");
- wuliuEntityList.add(wuliuEntity);
- } else {
- RouteResponseEntity routeResponseEntity = entity.getBody().getRouteResponse().get(0);
- if (routeResponseEntity != null) {
- List<RouteEntity> entityList = routeResponseEntity.getRouteResponse();
- for (RouteEntity route : entityList) {
- WuliuEntity wuliuEntity = new WuliuEntity();
- wuliuEntity.setAcceptTime(route.getAccept_time());
- wuliuEntity.setAcceptStation(route.getAccept_address() + route.getRemark());
- wuliuEntityList.add(wuliuEntity);
- }
- }
- }
- }
- } else {
- throw new RRException("查询顺丰订单异常," + entity.getErrors());
- }
- } else {
- JSONObject traces =
- KdniaoUtil.getOrderTracesByJson(orderEntity.getShippingCode(), orderEntity.getShippingNo());
- List<Map> mapList = (List<Map>) traces.get("Traces");
- if (mapList != null && mapList.size() > 0) {
- for (Map map : mapList) {
- WuliuEntity wuliuEntity = new WuliuEntity();
- wuliuEntity.setAcceptTime(map.get("AcceptTime").toString());
- wuliuEntity.setAcceptStation(map.get("AcceptStation").toString());
- wuliuEntityList.add(wuliuEntity);
- }
- }
- String state = traces.get("State") + "";
- if (Dict.logisticsStatus.item_0.getItem().equals(state) && traces.getBoolean("Success")) {
- String reason = traces.get("Reason") + "";
- WuliuEntity wuliuEntity = new WuliuEntity();
- wuliuEntity.setAcceptStation(reason);
- wuliuEntityList.add(wuliuEntity);
- }
- }
- }
- if (Dict.isSend.item_1.getItem().equalsIgnoreCase(orderProcessRecordEntity.getIsCustomsSend()) &&
- orderProcessRecordEntity.getShipmentStartTime() != null) {
- WuliuEntity wuliuEntity = new WuliuEntity();
- wuliuEntity.setAcceptStation("订单已出库");
- wuliuEntity.setAcceptTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
- .format(orderProcessRecordEntity.getShipmentStartTime()));
- wuliuEntityList.add(wuliuEntity);
- }
- if (Dict.isSend.item_1.getItem().equals(orderProcessRecordEntity.getIsCustomsSend())) {
- WuliuEntity wuliuEntity = new WuliuEntity();
- wuliuEntity.setAcceptStation("订单清关完成,等待仓库发货");
- wuliuEntity.setAcceptTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
- .format(orderProcessRecordEntity.getCustomsSuccTime()));
- wuliuEntityList.add(wuliuEntity);
- }
- if (Dict.isSend.item_0.getItem().equalsIgnoreCase(orderProcessRecordEntity.getIsCustomsSend())) {
- WuliuEntity wuliuEntity = new WuliuEntity();
- wuliuEntity.setAcceptStation("订单清关失败");
- wuliuEntityList.add(wuliuEntity);
- }
- if (Dict.isSend.item_1.getItem().equalsIgnoreCase(orderProcessRecordEntity.getIsEleOrderSend()) &&
- orderProcessRecordEntity.getWaybillSuccTime() != null) {
- WuliuEntity wuliuEntity = new WuliuEntity();
- wuliuEntity.setAcceptStation("海关三单发送成功");
- wuliuEntity.setAcceptTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
- .format(orderProcessRecordEntity.getWaybillSuccTime()));
- wuliuEntityList.add(wuliuEntity);
- }
- if (Dict.isSend.item_1.getItem().equals(orderProcessRecordEntity.getIsPaymentSend())) {
- WuliuEntity wuliuEntity = new WuliuEntity();
- wuliuEntity.setAcceptStation("订单支付成功");
- wuliuEntity.setAcceptTime(
- new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(orderProcessRecordEntity.getPaySuccTime()));
- wuliuEntityList.add(wuliuEntity);
- }
- if (Dict.isSend.item_1.getItem().equalsIgnoreCase(orderProcessRecordEntity.getIsAddOrderSend())) {
- WuliuEntity wuliuEntity = new WuliuEntity();
- wuliuEntity.setAcceptStation("订单下单成功");
- wuliuEntity.setAcceptTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
- .format(orderProcessRecordEntity.getAddOrderSuccTime()));
- wuliuEntityList.add(wuliuEntity);
- }
- }
- logisticsInfo.put("tracesList", wuliuEntityList);
- logisticsInfo.put("logisticCode", orderEntity.getShippingNo());
- logisticsInfo.put("shipperCode", orderEntity.getShippingCode());
- return logisticsInfo;
- }
- @Override
- public OrderEntity queryInfos(Long id) {
- OrderEntity orderEntity = orderDao.queryObject(id);
- Map<String, Object> map = new HashMap<String, Object>();
- map.put("orderId", id);
- List<OrderGoodsEntity> orderGoodsEntityList = orderGoodsDao.queryList(map);
- orderEntity.setOrderGoodsEntityList(orderGoodsEntityList);
- return orderEntity;
- }
- /**
- * 普货商品生成线下订单
- *
- * @param offlineCartList
- * @param user
- * @return
- */
- @Transactional
- @Override
- public Map orderSubmit(List<OfflineCartEntity> offlineCartList, SysUserEntity user) {
- Map resultObj = Maps.newHashMap();
- try {
- if (user == null) {
- resultObj.put("errno", 400);
- resultObj.put("errmsg", "用户登录超时,请重新登录");
- return resultObj;
- }
- if (!user.getRoleType().equalsIgnoreCase("2")) {
- resultObj.put("errno", 400);
- resultObj.put("errmsg", "该操作只允许店员账户操作");
- return resultObj;
- }
- if (org.apache.commons.lang3.StringUtils.isEmpty(user.getMerchSn())) {
- resultObj.put("errno", 400);
- resultObj.put("errmsg", "操作用户的商户编号为空,请先维护用户商户编号信息再来操作");
- return resultObj;
- }
- Long userId = user.getUserId();
- Integer storeId = user.getStoreId();
- //获取要购买的商品
- Map param = Maps.newHashMap();
- param.put("userId", userId);
- param.put("storeId", storeId);
- if (null == offlineCartList && offlineCartList.size() == 0) {
- resultObj.put("errno", 400);
- resultObj.put("errmsg", "购买商品数据为空");
- return resultObj;
- }
- List<OfflineCartEntity> offlineCartEntityList = offlineCartDao.queryOfflineCartByBizType(param);
- if (offlineCartEntityList.size() == 0 && offlineCartList.size() > 0) {
- resultObj.put("errno", 0);
- resultObj.put("errmsg", "该单已下单成功,请重新扫描商品进行购买");
- return resultObj;
- }
- // 检查库存和更新库存
- for (OfflineCartEntity cartEntity : offlineCartEntityList) {
- GoodsEntity goodsEntity = goodsDao.queryObject(cartEntity.getGoodsId());
- if (goodsEntity == null) {
- resultObj.put("errno", 400);
- resultObj.put("errmsg", "订单提交失败:商品不存在");
- return resultObj;
- }
- //取得规格的信息,判断规格库存
- ProductStoreRelaEntity productInfo = productStoreRelaDao
- .queryByGoodsIdAndStoreId(Long.valueOf(storeId), Long.valueOf(cartEntity.getGoodsId()));
- synchronized (productInfo) {
- if (null == productInfo || null == productInfo.getStockNum() ||
- productInfo.getStockNum() < cartEntity.getNumber()) {
- resultObj.put("errno", 400);
- resultObj.put("errmsg", "库存不足,仅剩余" + productInfo.getStockNum());
- return resultObj;
- } else {
- productInfo.setStockNum(productInfo.getStockNum() - cartEntity.getNumber());
- productInfo.setStoreId(Long.valueOf(storeId));
- productInfo.addSellVolume();
- productStoreRelaDao.updateStockNum(productInfo);//修改普通商品库存
- if (goodsEntity != null) {
- goodsEntity.setGoodsNumber(goodsEntity.getGoodsNumber() - cartEntity.getNumber());
- goodsDao.update(goodsEntity);
- }
- }
- }
- }
- String merchOrderSn = "EMATO" + CommonUtil.generateOrderNumber();
- OrderEntity order = setOrderVo(user, offlineCartEntityList, user.getMerchSn());
- order.setStoreId(storeId);
- order.setMerchOrderSn(merchOrderSn);
- //开启事务,插入订单信息和订单商品
- if (order != null) {
- orderDao.save(order);
- if (null == order.getId()) {
- resultObj.put("errno", 400);
- resultObj.put("errmsg", "订单提交失败");
- return resultObj;
- }
- for (OfflineCartEntity cartEntity : offlineCartEntityList) {
- OrderGoodsEntity orderGoodsEntity = setOrderGoodsVo(order, cartEntity);
- //新增订单详情
- orderGoodsDao.save(orderGoodsEntity);
- }
- //清空预订单商品临时表
- offlineCartDao.deleteByUserId(userId);
- Map orderInfoMap = Maps.newHashMap();
- orderInfoMap.put("orderInfo", order);
- resultObj.put("errno", 0);
- resultObj.put("errmsg", "订单提交成功");
- resultObj.put("data", orderInfoMap);
- }
- } catch (Exception e) {
- e.printStackTrace();
- resultObj.put("errno", 400);
- resultObj.put("errmsg", "订单异常");
- return resultObj;
- }
- return resultObj;
- }
- /**
- * 设置订单数据
- *
- * @param loginUser
- * @return
- */
- public OrderEntity setOrderVo(SysUserEntity loginUser, List<OfflineCartEntity> offlineCartEntityList,
- String merchSn) {
- OrderEntity orderInfo = new OrderEntity();
- BigDecimal freightPrice = new BigDecimal(0.00);
- BigDecimal goodsTotalPrice = new BigDecimal(0.00);
- for (OfflineCartEntity offlineCartEntity : offlineCartEntityList) {
- goodsTotalPrice = goodsTotalPrice
- .add(offlineCartEntity.getRetailPrice().multiply(new BigDecimal(offlineCartEntity.getNumber())));
- }
- //订单价格计算:订单的总价+运费
- BigDecimal orderTotalPrice = goodsTotalPrice.add(freightPrice);
- //查询未使用的优惠券
- /*String couponName = "";
- BigDecimal fullCutCouponDec = Constant.ZERO;
- UserCouponVo couponVo = null;*/
- BigDecimal couponPrice = new BigDecimal(0.00);
- //减去其它支付的金额后,要实际支付的金额 订单的总价+运费-优惠券金额
- BigDecimal actualPrice = orderTotalPrice.subtract(couponPrice);
- //商户(拼音首字母)+业务类型+编号
- // String merchSn = OmsMerchPropertiesBuilder.instance().getMerchSn();
- // String merchShortName = OmsMerchPropertiesBuilder.instance().getMerchShortName();
- MerchEntity merchEntity = merchDao.findByMerchSn(merchSn);
- String merchShortName = "";
- if (merchEntity != null) {
- merchShortName = merchEntity.getMerchShortName();
- }
- String orderSn = merchShortName + Dict.orderBizType.item_11.getItem() + CommonUtil.generateOrderNumber();
- orderInfo.setOrderSn(orderSn);
- orderInfo.setMerchSn(merchSn);
- orderInfo.setUserId(Integer.parseInt(loginUser.getUserId() + ""));
- orderInfo.setFreightPrice(freightPrice.intValue());
- orderInfo.setOrderBizType(Dict.orderBizType.item_11.getItem());
- /*orderInfo.setCoupon_id(userCouponId);
- orderInfo.setCoupon_name(couponName);*/
- // orderInfo.setFullCutPrice(fullCutCouponDec);//使用的优惠券
- orderInfo.setCouponPrice(couponPrice);
- orderInfo.setPostscript("");//留言
- orderInfo.setAddTime(new Date());
- orderInfo.setGoodsPrice(goodsTotalPrice);
- orderInfo.setOrderPrice(orderTotalPrice);
- orderInfo.setActualPrice(actualPrice);
- orderInfo.setOrderType("1");
- orderInfo.setOrderStatus(0);// 待付款
- orderInfo.setShippingStatus(0);
- orderInfo.setPayStatus(0);
- orderInfo.setShippingId(0L);
- orderInfo.setShippingFee(Constant.ZERO);
- orderInfo.setIntegral(0);
- orderInfo.setIntegralMoney(Constant.ZERO);
- orderInfo.setCreateTime(new Date());
- orderInfo.setModTime(new Date());
- orderInfo.setIsOnfflineOrder(Dict.isOnfflineOrder.item_1.getItem());//线下购买
- /*//标记该订单已使用优惠券
- if(couponVo != null){
- couponVo.setUsed_time(new Date());
- couponVo.setIsUsed(Dict.isUsed.item_1.getItem());
- apiUserCouponMapper.update(couponVo);
- }*/
- return orderInfo;
- }
- /**
- * 设置订单数据
- *
- * @param
- * @return
- */
- public OrderEntity setOrder(Integer userId, List<LinkedHashMap> goodsList,
- String merchSn) {
- OrderEntity orderInfo = new OrderEntity();
- BigDecimal freightPrice = new BigDecimal(0.00);
- BigDecimal goodsTotalPrice = new BigDecimal(0.00);
- for (LinkedHashMap goods : goodsList) {
- goodsTotalPrice = goodsTotalPrice
- .add(new BigDecimal(goods.get("retailPrice").toString()).multiply(new BigDecimal(goods.get("sellVolume").toString())));
- }
- //订单价格计算:订单的总价+运费
- BigDecimal orderTotalPrice = goodsTotalPrice.add(freightPrice);
- //查询未使用的优惠券
- /*String couponName = "";
- BigDecimal fullCutCouponDec = Constant.ZERO;
- UserCouponVo couponVo = null;*/
- BigDecimal couponPrice = new BigDecimal(0.00);
- //减去其它支付的金额后,要实际支付的金额 订单的总价+运费-优惠券金额
- BigDecimal actualPrice = orderTotalPrice.subtract(couponPrice);
- //商户(拼音首字母)+业务类型+编号
- // String merchSn = OmsMerchPropertiesBuilder.instance().getMerchSn();
- // String merchShortName = OmsMerchPropertiesBuilder.instance().getMerchShortName();
- MerchEntity merchEntity = merchDao.findByMerchSn(merchSn);
- String merchShortName = "";
- if (merchEntity != null) {
- merchShortName = merchEntity.getMerchShortName();
- }
- String orderSn = merchShortName + Dict.orderBizType.item_10.getItem() + CommonUtil.generateOrderNumber();
- orderInfo.setOrderSn(orderSn);
- orderInfo.setMerchSn(merchSn);
- orderInfo.setUserId(userId);
- orderInfo.setFreightPrice(freightPrice.intValue());
- orderInfo.setOrderBizType(Dict.orderBizType.item_10.getItem());
- /*orderInfo.setCoupon_id(userCouponId);
- orderInfo.setCoupon_name(couponName);*/
- // orderInfo.setFullCutPrice(fullCutCouponDec);//使用的优惠券
- orderInfo.setCouponPrice(couponPrice);
- orderInfo.setPostscript("");//留言
- orderInfo.setAddTime(new Date());
- orderInfo.setGoodsPrice(goodsTotalPrice);
- orderInfo.setOrderPrice(orderTotalPrice);
- orderInfo.setActualPrice(actualPrice);
- orderInfo.setOrderType("1");
- orderInfo.setOrderStatus(0);// 待付款
- orderInfo.setShippingStatus(0);
- orderInfo.setPayStatus(0);
- orderInfo.setShippingId(0L);
- orderInfo.setShippingFee(Constant.ZERO);
- orderInfo.setIntegral(0);
- orderInfo.setIntegralMoney(Constant.ZERO);
- orderInfo.setCreateTime(new Date());
- orderInfo.setModTime(new Date());
- orderInfo.setIsOnfflineOrder(Dict.isOnfflineOrder.item_1.getItem());//线下购买
- // orderInfo.setIsScan("0");//默认未扫描
- /*//标记该订单已使用优惠券
- if(couponVo != null){
- couponVo.setUsed_time(new Date());
- couponVo.setIsUsed(Dict.isUsed.item_1.getItem());
- apiUserCouponMapper.update(couponVo);
- }*/
- return orderInfo;
- }
- public OrderGoodsEntity setOrderGoodsVo(OrderEntity orderInfo, OfflineCartEntity goodsItem) {
- GoodsEntity goodsVo = goodsDao.queryObject(goodsItem.getGoodsId());
- OrderGoodsEntity orderGoodsVo = new OrderGoodsEntity();
- orderGoodsVo.setOrderId(Integer.parseInt(orderInfo.getId() + ""));
- orderGoodsVo.setGoodsId(goodsItem.getGoodsId());
- orderGoodsVo.setGoodsSn(goodsItem.getGoodsSn());
- orderGoodsVo.setProductId(goodsItem.getProductId());
- orderGoodsVo.setGoodsName(goodsItem.getGoodsName());
- orderGoodsVo.setListPicUrl(goodsItem.getListPicUrl());
- orderGoodsVo.setMarketPrice(goodsItem.getMarketPrice());
- orderGoodsVo.setRetailPrice(goodsItem.getRetailPrice());
- orderGoodsVo.setNumber(goodsItem.getNumber());
- orderGoodsVo.setOrderBizType(Dict.orderBizType.item_11.getItem());
- orderGoodsVo.setCreateTime(new Date());
- orderGoodsVo.setModTime(new Date());
- orderGoodsVo.setGoodsRate(goodsVo.getGoodsRate());
- orderGoodsVo.setSku(goodsVo.getSku());
- return orderGoodsVo;
- }
- // public OrderGoodsEntity setOrderGoods(OrderEntity orderInfo, LinkedHashMap goods) {
- // GoodsEntity goodsVo = goodsDao.queryObject(goods.get("goodsId"));
- // ProductEntity productEntity = productDao.queryObjectByGoodsIdAndStoreId(goodsVo.getId() + "", null);
- // OrderGoodsEntity orderGoodsVo = new OrderGoodsEntity();
- // orderGoodsVo.setOrderId(Integer.parseInt(orderInfo.getId() + ""));
- // orderGoodsVo.setGoodsId(goodsVo.getId().intValue());
- // orderGoodsVo.setGoodsSn(goodsVo.getGoodsSn());
- // orderGoodsVo.setProductId(productEntity.getId().intValue());
- // orderGoodsVo.setGoodsName(goodsVo.getName());
- // orderGoodsVo.setListPicUrl(goodsVo.getListPicUrl());
- //
- //
- // orderGoodsVo.setMarketPrice((BigDecimal) goods.get("storeMarketPrice"));
- // orderGoodsVo.setRetailPrice((BigDecimal) goods.get("storeRetailPrice"));
- // orderGoodsVo.setNumber((Integer) goods.get("sellVolume"));
- // orderGoodsVo.setOrderBizType(Dict.orderBizType.item_10.getItem());
- // orderGoodsVo.setCreateTime(new Date());
- // orderGoodsVo.setModTime(new Date());
- // orderGoodsVo.setGoodsRate(goodsVo.getGoodsRate());
- // orderGoodsVo.setSku(goodsVo.getSku());
- //
- //
- // BigDecimal number = new BigDecimal(Long.valueOf(goodsItem.getNumber()));
- // BigDecimal goodsTotal = goodsItem.getRetail_price().multiply(number);//单商品总价
- // BigDecimal rate = goodsTotal.divide(orderInfo.getGoods_price(),2, BigDecimal.ROUND_HALF_UP);//当前商品总价/订单总价(不含运费、不含优惠券)
- // BigDecimal freightPrice = BigDecimal.valueOf(orderInfo.getFreight_price());
- // BigDecimal settlePrice = Constant.ZERO;
- // if(orderInfo.getFreight_price() != 0 && !"0".equalsIgnoreCase(orderInfo.getCoupon_price()+"")){
- // //运费-优惠券
- // BigDecimal rateTotal = freightPrice.subtract(orderInfo.getCoupon_price());
- // //商品结算平摊价格(含优惠券、运费金额) = 单商品总价 + 当前商品总价/订单总价(不含运费、不含优惠券) * 运费与优惠券合计税率
- // settlePrice = goodsTotal.add(rate.multiply(rateTotal));
- // }else{
- // if(orderInfo.getFreight_price()!=0){
- // //运费税率 = 单商品总价/订单总价(不含运费)* 运费金额
- // BigDecimal freightRate = rate.multiply(freightPrice);
- // //商品结算平摊价格(含运费金额) = 单商品总价+运费税率
- // settlePrice = goodsTotal.add(freightRate);
- // }
- // if(!"0".equalsIgnoreCase(orderInfo.getCoupon_price()+"")){
- // //优惠券税率 = 单商品总价/订单总价(不含优惠券)* 优惠券金额
- // BigDecimal couponRate = rate.multiply(orderInfo.getCoupon_price());
- // //商品结算平摊价格(含优惠券金额) = 单商品总价-优惠券税率
- // settlePrice = goodsTotal.subtract(couponRate);
- // }
- // }
- // if(settlePrice.compareTo(BigDecimal.valueOf(0)) == 0){
- // orderGoodsVo.setSettlePrice(goodsTotal);//商品结算平摊价格
- // }else{
- // orderGoodsVo.setSettlePrice(settlePrice);//商品结算平摊价格
- // }
- //
- // return orderGoodsVo;
- // }
- @Override
- public OrderEntity queryObjectBySysUser(Long id) {
- OrderEntity orderEntity = orderDao.queryObjectBySysUser(id);
- Map<String, Object> map = new HashMap<String, Object>();
- map.put("orderId", id);
- List<OrderGoodsEntity> orderGoodsEntityList = orderGoodsDao.queryList(map);
- orderEntity.setOrderGoodsEntityList(orderGoodsEntityList);
- return orderEntity;
- }
- @Override
- public int confirmPay(Long id, String payFlag, String orderSnWx) {
- SysUserEntity user = ShiroUtils.getUserEntity();
- if (user == null) {
- throw new RRException("用户登录超时,请重新登录");
- }
- if (!user.getRoleType().equalsIgnoreCase("2")) {
- throw new RRException("该操作只允许店员账户操作");
- }
- OrderEntity orderEntity = queryObject(id);
- if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())) {
- throw new RRException("此订单已付款!");
- }
- if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_301.getItem())) {
- throw new RRException("此订单已完成!");
- }
- if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_101.getItem())) {
- throw new RRException("此订单已取消!");
- }
- if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_102.getItem())) {
- throw new RRException("此订单已删除!");
- }
- orderEntity.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_201.getItem()));
- orderEntity.setPayStatus(Integer.parseInt(Dict.payStatus.item_2.getItem()));
- orderEntity.setPayFlag(payFlag);
- orderEntity.setPayTime(new Date());
- if (Dict.payFlag.item_alipay.getItem().equalsIgnoreCase(payFlag)) {
- orderEntity.setAliTradeNo(orderSnWx);
- } else {
- if (orderSnWx != null) {
- orderEntity.setOrderSnWx(orderSnWx);
- }
- }
- // Date now = new Date();
- // Integer storeId = orderEntity.getStoreId();
- // Map queryParams = new HashMap();
- // queryParams.put("orderId", orderEntity.getId());
- // List<OrderGoodsEntity> orderGoodsList = orderGoodsDao.queryList(queryParams);
- // // 遍历订单下的详情商品,修改商品的最后销售时间
- // if (orderGoodsList!=null && orderGoodsList.size()>0){
- // orderGoodsList.forEach(orderGoods ->{
- // Integer goodsId = orderGoods.getGoodsId();
- // GoodsEntity goodsEntity = goodsDao.queryObject(goodsId);
- // if (Objects.nonNull(goodsEntity)){
- // goodsEntity.setLastSaleTime(now);
- // goodsDao.update(goodsEntity);
- // }
- // if (Objects.nonNull(storeId)){
- // ProductStoreRelaEntity productStoreRelaEntity = productStoreRelaDao.queryByGoodsIdAndStoreId(Long.valueOf(storeId), Long.valueOf(goodsId));
- // if (Objects.nonNull(productStoreRelaEntity)){
- // productStoreRelaEntity.setLastSaleTime(now);
- // productStoreRelaDao.update(productStoreRelaEntity);
- // }
- // }
- // });
- // }
- orderDao.update(orderEntity);
- return 0;
- }
- @Override
- public List<OrderEntity> queryExportList(Map<String, Object> map) {
- List<OrderEntity> list = orderDao.queryExportList(map);
- for (OrderEntity order : list) {
- OrderProcessRecordEntity orderProcessRecord = orderProcessRecordDao.queryObjectByOrderSn(order.getOrderSn());
- order.setOrderProcessRecord(orderProcessRecord);
- // 查询活动价
- BigDecimal topicPrice = orderDao.queryTopicPriceByOrderSnAndSku(order.getOrderSn(), order.getSku());
- order.setTopicPrice(topicPrice);
- }
- return list;
- }
- @Override
- public List<OrderEntity> queryOffilineOrderList(Map<String, Object> map) {
- return orderDao.queryOffilineOrderList(map);
- }
- /**
- * 还原查验单库存方法
- *
- * @param orderSns 查验单订单编号
- * @return 是否还原成功, true: 成功,false: 失败
- */
- @Override
- @Transactional(rollbackFor = Exception.class)
- public Boolean restore(String orderSns) {
- if (org.springframework.util.StringUtils.isEmpty(orderSns)) {
- LOGGER.error("还原查验单库存,订单编号为空!");
- return false;
- }
- List<String> orderIdStrList = new ArrayList<>();
- if (orderSns.contains(",")) {
- String[] split = orderSns.split(",");
- orderIdStrList.addAll(Arrays.asList(split));
- } else {
- orderIdStrList.add(orderSns);
- }
- List<Integer> orderIdList = orderIdStrList.parallelStream().map(Integer::valueOf).collect(Collectors.toList());
- // 查询订单详细信息
- List<OrderGoodsRestoreVo> orderGoodsRestoreVos = orderGoodsService.queryListByOrderIds(orderIdList);
- List<String> orderSnList = orderGoodsRestoreVos.stream().map(OrderGoodsRestoreVo::getOrderSn).collect(Collectors.toList());
- // 查询记录表, 不能还原多次
- List<String> snList = newRetailOrderRestoreStockRecordService.queryListByOrderSnList(orderSnList);
- // 不为空则说明有订单已经被还原过, 返回失败
- if (!CollectionUtils.isEmpty(snList)) {
- LOGGER.error(String.format("订单【%s】已经还原过库存,不可继续还原!", snList));
- throw new RRException(String.format("订单【%s】已经还原过库存,不可继续还原!", snList));
- }
- // 需要更新门店商品库存(mall_product_store_rela)和园区库存(mall_goods)
- // 园区库存, 无门店概念
- List<GoodsEntity> goodsEntities = new ArrayList<>();
- // 门店商品库存
- List<ProductStoreRelaEntity> productStoreRelaEntities = new ArrayList<>();
- // 组装数据
- orderGoodsRestoreVos.forEach(orderGoodsRestoreVo -> {
- goodsEntities.add(wrapGoods(orderGoodsRestoreVo));
- productStoreRelaEntities.add(wrapProductStoreRela(orderGoodsRestoreVo));
- });
- // 还原园区库存
- goodsService.restoreBatch(goodsEntities);
- // 还原门店库存
- productStoreRelaService.restoreBatch(productStoreRelaEntities);
- LOGGER.info("还原【{}】查验订单库存成功!", orderSnList);
- // 查验完成的单已经转成保税备货,800放行后不会通知到kmall,所以需要将状态修改为已发货
- orderDao.updateOrderStatusByOrderSnList(orderSnList);
- LOGGER.info("更新【{}】查验订单状态为已发货成功!", orderSnList);
- // 添加还原记录
- List<NewRetailOrderRestoreStockRecordEntity> stockRecordEntityList = orderGoodsRestoreVos.stream().map(this::wrapRestoreRecord).collect(Collectors.toList());
- newRetailOrderRestoreStockRecordService.saveBatch(stockRecordEntityList);
- LOGGER.info("新增【{}】查验订单还原记录成功!", orderSnList);
- return true;
- }
- /**
- * 组装查验单库存还原记录实体
- * @param orderGoodsRestoreVo 实体
- * @return 查验单库存还原记录
- */
- private NewRetailOrderRestoreStockRecordEntity wrapRestoreRecord(OrderGoodsRestoreVo orderGoodsRestoreVo){
- NewRetailOrderRestoreStockRecordEntity entity = new NewRetailOrderRestoreStockRecordEntity();
- SysUserEntity user = ShiroUtils.getUserEntity();
- entity.setOrderId(orderGoodsRestoreVo.getOrderId());
- entity.setOrderSn(orderGoodsRestoreVo.getOrderSn());
- entity.setRestoreNum(orderGoodsRestoreVo.getNumber());
- entity.setStoreId(orderGoodsRestoreVo.getStoreId());
- entity.setShopName(orderGoodsRestoreVo.getShopName());
- entity.setSku(orderGoodsRestoreVo.getSku());
- entity.setCreateSn(String.valueOf(user.getUserId()));
- entity.setCreateTime(new Date());
- entity.setUpdateSn(String.valueOf(user.getUserId()));
- entity.setUpdateTime(new Date());
- entity.setStatus(Dict.stockRestoreEnum.SUCCESS.getCode());
- return entity;
- }
- /**
- * 组装成ProductStoreRelaEntity, 还原操作
- * @param orderGoodsRestoreVo 订单详细数据
- * @return 门店库存
- */
- private ProductStoreRelaEntity wrapProductStoreRela(OrderGoodsRestoreVo orderGoodsRestoreVo) {
- ProductStoreRelaEntity productStoreRelaEntity = new ProductStoreRelaEntity();
- productStoreRelaEntity.setStoreId(orderGoodsRestoreVo.getStoreId().longValue());
- productStoreRelaEntity.setSku(orderGoodsRestoreVo.getSku());
- productStoreRelaEntity.setStockNum(orderGoodsRestoreVo.getNumber());
- return productStoreRelaEntity;
- }
- /**
- * 组装成GoodsEntity, 还原操作
- * @param orderGoodsRestoreVo 订单详细数据
- * @return 库存
- */
- private GoodsEntity wrapGoods(OrderGoodsRestoreVo orderGoodsRestoreVo) {
- GoodsEntity goodsEntity = new GoodsEntity();
- goodsEntity.setGoodsNumber(orderGoodsRestoreVo.getNumber());
- goodsEntity.setSku(orderGoodsRestoreVo.getSku());
- return goodsEntity;
- }
- @Override
- public List<OrderEntity> queryPickUpCodeList(Map<String, Object> map) {
- return orderDao.queryPickUpCodeList(map);
- }
- @Override
- public int uploadExcel(List<OrderExpressDto> orderExpressDtoList) {
- SysUserEntity user = ShiroUtils.getUserEntity();
- boolean isFail = false;
- List<String> failShippingNameList = new ArrayList<>();
- List<String> failOrderSnList = new ArrayList<>();
- List<String> failShippingCodeList = new ArrayList<>();
- List<String> failCodeSnList = new ArrayList<>();
- List<String> failNameSnList = new ArrayList<>();
- List<String> failStatusOrderSnList = new ArrayList<>();
- if (orderExpressDtoList != null && orderExpressDtoList.size() > 0) {
- for (int i = 0; i < orderExpressDtoList.size(); i++) {
- OrderExpressDto orderExpressDto = orderExpressDtoList.get(i);
- OrderEntity orderEntity = new OrderEntity();
- Map<String, Object> valideDate = MapBeanUtil.fromObject(orderExpressDto);
- ImmutableBiMap.Builder builder = new ImmutableBiMap.Builder();
- builder.put("orderSn", "订单编号");
- builder.put("shippingNo", "快递单号");
- builder.put("shippingName", "快递公司");
- builder.put("shippingCode", "快递简写");
- R r = ValidatorUtil.isEmpty(builder.build(), valideDate);
- if (Integer.valueOf(r.get("code").toString()) != 0) {
- throw new RRException(r.get("msg").toString());
- } else {
- r = ValidatorUtil.isEmpty(builder.build(), valideDate);
- if (Integer.valueOf(r.get("code").toString()) != 0) {
- throw new RRException(r.get("msg").toString());
- }
- }
- OrderEntity order = orderDao.queryObjectByOrderSn(orderExpressDto.getOrderSn());
- if (order == null) {
- isFail = true;
- failOrderSnList.add(orderExpressDto.getOrderSn());
- } else {
- if (!(order.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())
- && order.getPayStatus() == Integer.parseInt(Dict.payStatus.item_2.getItem()))) {
- isFail = true;
- failStatusOrderSnList.add(orderExpressDto.getOrderSn());
- }
- }
- ShippingEntity shippingEntity = shippingDao.queryObjectByCode(orderExpressDto.getShippingCode());
- if (shippingEntity == null) {
- isFail = true;
- failShippingCodeList.add(orderExpressDto.getShippingCode());
- failCodeSnList.add(orderExpressDto.getOrderSn());
- } else {
- if (!orderExpressDto.getShippingName().equalsIgnoreCase(shippingEntity.getName())) {
- isFail = true;
- failShippingNameList.add(orderExpressDto.getShippingName());
- failNameSnList.add(orderExpressDto.getOrderSn());
- }
- }
- if (!isFail) {//false则有错误的数据
- if (order != null) {// 修改商品
- // orderEntity.setOrderSn(orderExpressDto.getOrderSn());
- orderEntity.setShippingNo(orderExpressDto.getShippingNo());
- orderEntity.setShippingCode(orderExpressDto.getShippingCode());
- orderEntity.setShippingName(orderExpressDto.getShippingName());
- orderEntity.setShippingStatus(Integer.parseInt(Dict.shippingStatus.item_1.getItem()));
- orderEntity.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_300.getItem()));
- orderEntity.setModerSn(user.getUsername());
- orderEntity.setCreateTime(new Date());
- orderEntity.setModTime(new Date());
- orderEntity.setId(order.getId());
- orderDao.update(orderEntity);
- }
- }
- }
- if (failOrderSnList != null && failOrderSnList.size() > 0) {
- throw new RRException("导入数据异常,订单编号不存在,不存在的订单编号【" + failOrderSnList + "】,请删除掉再继续操作");
- }
- if (failStatusOrderSnList != null && failStatusOrderSnList.size() > 0) {
- throw new RRException("导入数据异常,修改订单快递功能只支持已付款未发货的订单,以下订单编号无效【" + failStatusOrderSnList + "】,请删除掉再继续操作");
- }
- if (failShippingCodeList != null && failShippingCodeList.size() > 0) {
- throw new RRException("导入数据异常,快递简写不在可支持的范围中,简写错误的订单编号【" + failCodeSnList + "】,错误的快递简写【" + failShippingCodeList + "】," +
- "正确数据可下载订单页面的快递公司简写Excel中查看");
- }
- if (failShippingNameList != null && failShippingNameList.size() > 0) {
- throw new RRException("导入数据异常,快递简写对应的快递公司不一致,快递公司错误的订单编号【" + failNameSnList + "】,请修改Excel数据中订单编号对应的快递公司错误信息," +
- "正确数据可下载订单页面的快递公司简写Excel中查看");
- }
- // if(failFreightGoodsSnList != null && failFreightGoodsSnList.size() > 0){
- // exportExceptionDataEntity.setExportExceptionData("运费信息请在商城配置》运费模板中维护,运费与商户信息对应,请检查该商品商户信息下的运费是否维护,不存在的商品编码【"+failFreightGoodsSnList+"】,运费【"+failFreightList+"】");
- // exportExceptionDataDao.save(exportExceptionDataEntity);
- // throw new RRException("导入数据异常,异常信息请在商品管理》》商品导入异常数据中查看检查");
- // }
- } else {
- throw new RRException("导入数据为空,或者检查商品编码数据是否为空");
- }
- return 1;
- }
- @Override
- public List<OrderEntity> promOrderList(Map<String, Object> map) {
- Integer[] statusList = {201};
- List<OrderEntity> list = orderDao.promOrderList(map);
- for (OrderEntity orderEntity : list) {
- Map<String, Object> queryMap = new HashMap<>();
- queryMap.put("goodsId", orderEntity.getGoodsId());
- queryMap.put("statusList", statusList);
- queryMap.put("orderId", orderEntity.getId());
- Double promActualPrice = orderDao.getActualPriceByOutProm(queryMap);
- if (promActualPrice == null) {
- promActualPrice = 0d;
- }
- orderEntity.setPromActualPrice(BigDecimal.valueOf(promActualPrice));
- }
- return list;
- }
- @Override
- public int queryPromOrderTotal(Map<String, Object> map) {
- return orderDao.queryPromOrderTotal(map);
- }
- @Override
- public List<OrderEntity> promOrderListExport(Map<String, Object> map) {
- Integer[] statusList = {201};
- List<OrderEntity> list = orderDao.promOrderListExport(map);
- for (OrderEntity orderEntity : list) {
- Map<String, Object> queryMap = new HashMap<>();
- queryMap.put("goodsId", orderEntity.getGoodsId());
- queryMap.put("orderId", orderEntity.getId());
- queryMap.put("statusList", statusList);
- Double promActualPrice = orderDao.getActualPriceByOutProm(queryMap);
- if (promActualPrice == null) {
- promActualPrice = 0d;
- }
- orderEntity.setPromActualPrice(BigDecimal.valueOf(promActualPrice));
- }
- return list;
- }
- @Override
- public List<OrderEntity> storeTopicOrderList(Map<String, Object> map) {
- List<OrderEntity> list = orderDao.storeTopicOrderList(map);
- return list;
- }
- @Override
- public int queryStoreTopicOrderTotal(Map<String, Object> map) {
- return orderDao.queryStoreTopicOrderTotal(map);
- }
- @Override
- public List<WxOrderEntity> wxOrderResendQueryAllList(Map<String, Object> map) {
- // String requestData = JacksonUtil.toJson(map);
- String url = OmsMerchPropertiesBuilder.instance().getWxOrderResendUrl();
- // 同步访问,返回结果字符串
- String response = OkHttpUtils.post(map, url, "SSL");
- ResponseData responseData = JacksonUtils.fromStringJson(response, ResponseData.class);
- if (responseData.getCode().equalsIgnoreCase("0")) {
- List<WxOrderEntity> list = responseData.getData().getRows();
- return list;
- }
- return null;
- }
- @Override
- public List<OrderRecognitionDto> queryOrderListByRecognition(Map<String, Object> map) {
- String value = sysConfigDao.queryByKey("FACE_COLLECT_FREQUENCY_TIME");
- if (value == null) {
- throw new RRException("请联系管理员配系统参数置FACE_COLLECT_FREQUENCY_TIME信息!");
- }
- List<OrderRecognitionDto> list = orderDao.queryOrderListByRecognition(map);
- for (OrderRecognitionDto orderRecognitionDto : list) {
- Integer frequencySecondTime = Integer.parseInt(value);
- String lastFaceTime = orderRecognitionDto.getLastFaceTime();
- if (StringUtils.isNotEmpty(lastFaceTime)) {
- Date lastFaceDate = DateUtils.convertStringToDate(lastFaceTime, DateUtils.DATE_TIME_PATTERN);
- Calendar calendar = Calendar.getInstance();
- calendar.setTime(lastFaceDate);
- calendar.add(Calendar.SECOND, frequencySecondTime);
- Date addSecondTime = calendar.getTime();
- Date nowDate = new Date();
- if (addSecondTime.getTime() > nowDate.getTime()) {
- orderRecognitionDto.setAddSecondTime(DateUtils.format(addSecondTime, DateUtils.DATE_TIME_PATTERN));
- orderRecognitionDto.setIsDateLast("false");
- } else {
- //可调用身份验证范围内
- orderRecognitionDto.setIsDateLast("true");
- }
- } else {//可调用身份验证范围内
- orderRecognitionDto.setIsDateLast("true");
- }
- }
- return list;
- }
- @Override
- public int queryOrderListByRecognitionTotal(Map<String, Object> map) {
- return orderDao.queryOrderListByRecognitionTotal(map);
- }
- /**
- * 海控,提交订单并付款
- * @param param 收银端提交的参数
- * @param user 当前收银端用户
- * @return 结果
- */
- @Override
- @Transactional
- public synchronized Map offlineRetailSubmitHaiKong(Map param, SysUserEntity user) {
- // 解析订单数据 List
- List<LinkedHashMap> goodsList = (List<LinkedHashMap>) param.get("goodsList");
- // 解析用户信息 LinkedHashMap
- Map userInfo = (Map) param.get("userInfo");
- // 解析支付码 String
- String parCode = (String) param.get("payCode");
- // 解析sessionId(WebSocket) String
- String sessionId = (String) param.get("sessionId");
- // machineCode
- String machineCode = (String) param.get("machineCode");
- //选择的方式 1柜取 0邮寄
- int status = Integer.parseInt(param.get("status").toString());
- // 会员码
- String couponBarCode = param.get("couponBarCode").toString();
- Map<String, String> mapAddr = new HashMap<>();
- if (status == 0) {
- //省
- String cmbProvince = (String) param.get("cmbProvince");
- //市
- String cmbCity = (String) param.get("cmbCity");
- //区
- String cmbArea = (String) param.get("cmbArea");
- //详细地址
- String addrUser = (String) param.get("addrUser");
- mapAddr.put("cmbProvince", cmbProvince);
- mapAddr.put("cmbCity", cmbCity);
- mapAddr.put("cmbArea", cmbArea);
- mapAddr.put("addrUser", addrUser);
- }
- try {
- machineCode = URLDecoder.decode(machineCode, "UTF-8");
- } catch (Exception e) {
- LOGGER.error("机器码:", e);
- }
- Map resultObj = Maps.newHashMap();
- if (user == null) {
- resultObj.put("errno", 400);
- resultObj.put("errmsg", "用户登录超时,请重新登录");
- return resultObj;
- }
- if (!user.getRoleType().equalsIgnoreCase("2")) {
- resultObj.put("errno", 400);
- resultObj.put("errmsg", "该操作只允许店员账户操作");
- return resultObj;
- }
- if (org.apache.commons.lang3.StringUtils.isEmpty(user.getMerchSn())) {
- resultObj.put("errno", 400);
- resultObj.put("errmsg", "操作用户的商户编号为空,请先维护用户商户编号信息再来操作");
- return resultObj;
- }
- Long userId = user.getUserId();
- Integer storeId = user.getStoreId();
- // TODO 海控需求,下单流程修改,收银端接收会员码,付款码,用户信息,订单数据
- // 1. 校验库存:保税仓库存 + 展销店库存 - 出区数 >= 购买数
- // 获取保税仓库存
- String queryWarehouseStockResponse = haiKongWarehouseTemplate.queryWarehouseStock(null);
- if (org.springframework.util.StringUtils.isEmpty(queryWarehouseStockResponse)) {
- LOGGER.error("调用库存系统接口出现错误!返回结果为空!");
- throw new ServiceException("调用库存系统接口出现错误!");
- }
- WareQueryStockResponseDTO wareQueryStockResponseDTO = JacksonUtil.fromStringJson(queryWarehouseStockResponse, WareQueryStockResponseDTO.class);
- if (Objects.isNull(wareQueryStockResponseDTO)) {
- throw new ServiceException("解析一步达库存系统响应数据出现错误!");
- }
- List<WareQueryStockResponseDTO.WareQueryStockResponseItemDTO> items = wareQueryStockResponseDTO.getItems();
- // 解析xml,组装成map key=>sku value=>库存
- Map<String, Integer> stockMap = new HashMap<>(16);
- items.forEach(item -> {
- String itemCode = item.getItemCode();
- Integer quantity = item.getQuantity();
- if (stockMap.containsKey(itemCode)) {
- // 避免出现sku相同情况
- stockMap.put(itemCode, stockMap.get(itemCode) + quantity);
- } else {
- stockMap.put(itemCode, quantity);
- }
- });
- // 订单总价格(含税价)
- BigDecimal orderPrice = BigDecimal.ZERO;
- // 商品总价格(不含税)
- BigDecimal goodsPrice = BigDecimal.ZERO;
- // 订单所占用的税
- BigDecimal totalTax = BigDecimal.ZERO;
- List<OrderGoodsEntity> orderGoodsEntities = new ArrayList<>();
- List<GoodsEntity> goodsEntities = new ArrayList<>();
- // TODO 根据商品条码、sku、门店id查询相对应的商品信息,并组装成对象
- List<QueryGoodsVO> queryGoodsVOList = new ArrayList<>();
- goodsList.forEach(map -> {
- QueryGoodsVO queryGoodsVo = new QueryGoodsVO();
- queryGoodsVo.setProdBarcode((String) map.get("prodBarcode"));
- queryGoodsVo.setSku((String) map.get("goodsSn"));
- queryGoodsVo.setStoreId(storeId);
- queryGoodsVo.setSellVolume((Integer) map.get("sellVolume"));
- queryGoodsVo.setRetailPrice(new BigDecimal(String.valueOf(map.get("retailPrice"))));
- queryGoodsVo.setGoodsTaxes(new BigDecimal(String.valueOf(map.get("goodstaxes"))));
- queryGoodsVo.setDisCountedPrice(new BigDecimal(String.valueOf(map.get("disCountedPrice"))));
- queryGoodsVOList.add(queryGoodsVo);
- });
- // 将在循环中查询数据库改为一次性查询
- List<GoodsEntity> goodsEntityList = goodsService.queryGoodsStockByQueryGoodsVoList(queryGoodsVOList);
- // 复制集合数据
- ListUtils listUtils = BeanUtils.instantiate(ListUtils.class);
- listUtils.copyList(goodsEntityList, queryGoodsVOList);
- // 用来存储是否达到满赠条件的map
- Map<String, BigDecimal> categoryConditionMap = new HashMap<>();
- Map<String, BigDecimal> brandConditionMap = new HashMap<>();
- for (QueryGoodsVO goodsEntity : queryGoodsVOList) {
- OrderGoodsEntity orderGoodsEntity = new OrderGoodsEntity();
- // 要购买的数量
- Integer sellVolume = goodsEntity.getSellVolume();
- // 条码
- String prodBarcode = goodsEntity.getProdBarcode();
- // 当前sku
- String sku = goodsEntity.getSku();
- // 订单金额(含税价),订单总金额,用户支付的金额
- BigDecimal retailPrice = goodsEntity.getRetailPrice();
- // 商品预估税率
- BigDecimal goodsTaxes = goodsEntity.getGoodsTaxes();
- // 商品优惠金额
- BigDecimal disCountedPrice = goodsEntity.getDisCountedPrice();
- // 商品金额(不包含税的价格),推送海关电子订单需要
- goodsPrice = goodsPrice.add(retailPrice.subtract(goodsTaxes));
- // 累加订单价格(含税价)
- orderPrice = orderPrice.add(retailPrice);
- // 总税款
- totalTax = totalTax.add(goodsTaxes);
- // 当前sku
- String currentSku = goodsEntity.getSku();
- // 仓库库存
- Integer warehouseStock = stockMap.get(currentSku);
- // 门店库存
- Integer stockNum = goodsEntity.getStockNum();
- // 判断库存。。
- if (!stockMap.containsKey(currentSku)) {
- LOGGER.error("库存系统中不包含此sku:【{}】,校验库存出错!下单失败!", currentSku);
- throw new ServiceException(String.format("不包含此sku:【%s】", currentSku));
- } else {
- // 保税仓库存 + 展销店库存 - 出区数 >= 购买数
- // 当前出区数
- Integer exitRegionNumber = goodsEntity.getExitRegionNumber();
- // 保税仓库存 + 门店库存 - 出区数 >= 购买数
- if (!((warehouseStock + stockNum) - exitRegionNumber >= sellVolume)) {
- // 库存不足
- LOGGER.error("sku【{}】库存不足!商品条码:【{}】,门店库存:【{}】,保税仓库存:【{}】,当前出区数:【{}】", currentSku, prodBarcode, stockNum, warehouseStock, exitRegionNumber);
- throw new ServiceException(String.format("sku【%s】库存不足!商品条码:【%s】,门店库存:【%s】,保税仓库存:【%s】,当前出区数:【%s】", currentSku, prodBarcode, stockNum, warehouseStock, exitRegionNumber));
- }
- }
- // 设置订单详情信息
- GoodsEntity entity = new GoodsEntity(goodsEntity);
- wrapOrderGoods(orderGoodsEntity, entity);
- orderGoodsEntities.add(orderGoodsEntity);
- // 设置条件信息,暂不支持门店满赠活动
- String categoryId = String.valueOf(entity.getCategoryId());
- String brandId = String.valueOf(entity.getBrandId());
- if (!categoryConditionMap.containsKey(categoryId)) {
- categoryConditionMap.put(categoryId, retailPrice);
- } else {
- categoryConditionMap.put(categoryId, categoryConditionMap.get(categoryId).add(retailPrice));
- }
- // if (!brandConditionMap.containsKey(brandId)) {
- // brandConditionMap.put(brandId, retailPrice);
- // } else {
- // brandConditionMap.put(brandId, brandConditionMap.get(brandId).add(retailPrice));
- // }
- }
- // 2. 判断购买的商品是否能参与满减活动
- // 2.1 查询当前门店是否有满赠的活动
- List<MkActivitiesEntity> activitiesEntities = mkActivitiesService.queryByNowByMz(String.valueOf(storeId), DateUtils.format(new Date(), "yyyy-MM-dd"));
- if (CollectionUtils.isEmpty(activitiesEntities)) {
- LOGGER.error("----- 该门店【{}】暂无满赠活动! -----", storeId);
- } else {
- // 当前门店的活动编号
- List<Long> activitiesSnList = activitiesEntities.stream().map(MkActivitiesEntity::getMkaId).collect(Collectors.toList());
- // 活动
- List<MkActivitiesFullGiftEntity> mkActivitiesFullGiftEntities = mkActivitiesFullGiftService.queryByMkaIdList(activitiesSnList);
- if (CollectionUtils.isEmpty(mkActivitiesFullGiftEntities)) {
- LOGGER.error("----- 该门店【{}】暂无满赠活动! -----", storeId);
- } else {
- mkActivitiesFullGiftEntities.forEach(mkActivitiesFullGiftEntity -> {
- // 存在品牌满赠活动,暂不支持品牌满赠活动
- // String brandId = String.valueOf(mkActivitiesFullGiftEntity.getBrandId());
- // if (brandConditionMap.containsKey(brandId)) {
- // if (brandConditionMap.get(brandId).compareTo(mkActivitiesFullGiftEntity.getQualifiedAmount()) > 0) {
- // // 该品牌满足满赠条件
- //
- // }
- // }
- // 存在分类满赠活动
- String categoryId = String.valueOf(mkActivitiesFullGiftEntity.getCategoryId());
- if (!CollectionUtils.isEmpty(categoryConditionMap) && categoryConditionMap.containsKey(categoryId)) {
- if (categoryConditionMap.get(categoryId).compareTo(mkActivitiesFullGiftEntity.getQualifiedAmount()) > 0) {
- // 该分类满足满赠条件
- String giftBarcode = mkActivitiesFullGiftEntity.getGiftBarcode();
- String giftGoodsSn = mkActivitiesFullGiftEntity.getGiftGoodsSn();
- String shopSn = mkActivitiesFullGiftEntity.getShopSn();
- GoodsEntity goodsEntity = goodsService.queryGoodsStockByBarcodeAndStoreIdAndSku(giftBarcode, Integer.parseInt(shopSn), giftGoodsSn);
- // 存储赠送数
- goodsEntity.setGoodsNumber(mkActivitiesFullGiftEntity.getGiftNumber());
- OrderGoodsEntity orderGoodsEntity = new OrderGoodsEntity();
- wrapOrderGoods(orderGoodsEntity, goodsEntity);
- orderGoodsEntity.setRetailPrice(BigDecimal.ZERO);
- orderGoodsEntity.setDiscountedPrice(BigDecimal.ZERO);
- orderGoodsEntity.setActualPaymentAmount(BigDecimal.ZERO);
- orderGoodsEntities.add(orderGoodsEntity);
- }
- }
- });
- }
- }
- // 3. 校验是否是会员,调用会员系统查询会员信息,查询接口:
- // 优惠后价格
- BigDecimal afterDiscountPrice;
- if (org.springframework.util.StringUtils.isEmpty(couponBarCode)) {
- // 不是会员,不享受积分抵扣,只能使用门店的优惠券
- afterDiscountPrice = calculatePreferentialPrice(orderPrice, 0, goodsList, storeId, userInfo);
- } else {
- // 会员,计算优惠价
- String queryMemberInfoResponse;
- try {
- // 查询会员信息
- queryMemberInfoResponse = haiKongMemberTemplate.getMemberInfoByCode("{\"code\":\"" + couponBarCode + "\"}");
- Response<MemberInfoDTO> response = JacksonUtil.fromListJson(queryMemberInfoResponse, new TypeReference<Response<MemberInfoDTO>>() {
- });
- if (Objects.nonNull(response) && response.getSuccess()) {
- MemberInfoDTO memberInfoDTO = response.getData();
- Integer score = memberInfoDTO.getScore();
- if (Objects.nonNull(score) && score > 0) {
- // 有积分
- afterDiscountPrice = calculatePreferentialPrice(orderPrice, score, goodsList, storeId, userInfo);
- } else {
- // 无积分
- afterDiscountPrice = calculatePreferentialPrice(orderPrice, 0, goodsList, storeId, userInfo);
- }
- } else {
- LOGGER.error("查询会员信息失败!响应结果:{}", queryMemberInfoResponse);
- throw new ServiceException("查询会员信息失败!请重新下单!");
- }
- } catch (Exception e) {
- LOGGER.error("查询会员信息失败!请重新下单!");
- throw new ServiceException("查询会员信息失败!请重新下单!");
- }
- }
- // 4. 调用付款接口
- // 判断是微信的支付码还是支付宝的支付码
- if (parCode.startsWith("28")) {
- // 支付宝支付
- try {
- // AliPay(user, parCode, order, processRecordEntity, orderWXPayRecordCurrent, store);
- } catch (Exception e) {
- e.printStackTrace();
- throw e;
- }
- } else {
- // 微信支付
- try {
- // wxPay(user, parCode, resultObj, order, processRecordEntity, orderWXPayRecordCurrent, store);
- } catch (Exception e) {
- e.printStackTrace();
- throw e;
- }
- }
- // 5. 扣减库存
- // 6. 订单入库
- return resultObj;
- }
- /**
- * 设置订单商品详情数据
- * @param orderGoodsEntity 订单商品详情
- * @param goodsEntity 商品信息
- * @return 订单商品详情
- */
- private OrderGoodsEntity wrapOrderGoods(OrderGoodsEntity orderGoodsEntity, GoodsEntity goodsEntity) {
- // 设置商品信息
- BeanUtils.copyProperties(goodsEntity, orderGoodsEntity);
- // 设置订单信息
- // 销售数
- orderGoodsEntity.setNumber(goodsEntity.getGoodsNumber());
- // TODO other...
- return orderGoodsEntity;
- }
- /**
- * 计算优惠后的价格
- * 1、优惠券优先于积分抵扣
- * 2、限时特价与积分不互斥,虽然海控没说哪个优先,但我觉得应该是限时特价优先于积分
- * 3、优惠券之间互斥
- * 4、活动和优惠券互斥
- * @param orderPrice 订单总价
- * @param score 会员积分
- * @param goodsEntities 订单商品明细
- * @param storeId 门店id
- * @param userInfo 用户信息
- * @return 优惠后的价格
- */
- private BigDecimal calculatePreferentialPrice (BigDecimal orderPrice, Integer score, List<LinkedHashMap> goodsEntities, Integer storeId, Map userInfo) {
- // 优惠后的价格
- BigDecimal preferentialPrice = BigDecimal.ZERO;
- // 1. 判断是否有积分,是否需要计算积分抵扣后的价格
- AtomicBoolean isCalculateScorePrice = new AtomicBoolean(false);
- if (Objects.nonNull(score) && score > 0) {
- isCalculateScorePrice.set(true);
- }
- // 2. 查询订单商品是否有优惠券和参加活动
- goodsEntities.forEach(map -> {
- // 2-1. 判断活动和优惠券之间的互斥关系
- // 2-2. 计算优惠、活动后的总价格
- });
- // 3. 计算积分抵扣后的总价格
- if (isCalculateScorePrice.get()) {
- // 3-1. 计算总价的50%
- BigDecimal halfPrice = preferentialPrice.multiply(new BigDecimal("0.5")).setScale(2, BigDecimal.ROUND_HALF_UP);
- Integer scoreLimit = haiKongProperties.getMemberScoreLimit();
- if (score < scoreLimit) {
- LOGGER.warn("用户【{}】的积分数量为:{},最低需要30积分才能抵扣!", userInfo.get("customName"), score);
- return preferentialPrice;
- } else {
- // 3-2. 计算出积分能抵扣的价格
- int scoreMayDeductionPrice = score % scoreLimit == 0 ? score / scoreLimit : (int) (score / scoreLimit);
- // 3-3. 计算积分抵扣后的价格
- BigDecimal scoreMayDeductionPriceDecimal = new BigDecimal(scoreMayDeductionPrice);
- if (halfPrice.compareTo(scoreMayDeductionPriceDecimal) > 0) {
- preferentialPrice = preferentialPrice.subtract(scoreMayDeductionPriceDecimal);
- } else {
- // 积分能抵扣的金额如果比总价的50%还要多,只能抵扣50%
- // 总价50%的值
- int halfPriceInt = halfPrice.setScale(0, BigDecimal.ROUND_FLOOR).intValue();
- int i = scoreMayDeductionPrice - halfPriceInt;
- preferentialPrice = preferentialPrice.subtract(new BigDecimal(halfPriceInt));
- }
- }
- }
- return preferentialPrice;
- }
- /**
- * 提交订单并付款
- *
- * @param param 提交的订单数据、包括用户信息、支付码、会话id、机器码(收银台)、取货方式、收货地址信息、会员码
- * @param user
- * @return
- */
- @Override
- @Transactional
- public synchronized Map offlineRetailSubmit(Map param, SysUserEntity user) {
- // 解析订单数据 List
- List<LinkedHashMap> goodsList = (List<LinkedHashMap>) param.get("goodsList");
- // 解析用户信息 LinkedHashMap
- Map userInfo = (Map) param.get("userInfo");
- // 解析支付码 String
- String parCode = (String) param.get("payCode");
- // 解析sessionId(WebSocket) String
- String sessionId = (String) param.get("sessionId");
- // machineCode
- String machineCode = (String) param.get("machineCode");
- //选择的方式 1柜取 0邮寄
- int status = Integer.parseInt(param.get("status").toString());
- Map<String, String> mapAddr = new HashMap<>();
- if (status == 0) {
- //省
- String cmbProvince = (String) param.get("cmbProvince");
- //市
- String cmbCity = (String) param.get("cmbCity");
- //区
- String cmbArea = (String) param.get("cmbArea");
- //详细地址
- String addrUser = (String) param.get("addrUser");
- mapAddr.put("cmbProvince", cmbProvince);
- mapAddr.put("cmbCity", cmbCity);
- mapAddr.put("cmbArea", cmbArea);
- mapAddr.put("addrUser", addrUser);
- }
- try {
- machineCode = URLDecoder.decode(machineCode, "UTF-8");
- } catch (Exception e) {
- // e.printStackTrace();
- }
- Map resultObj = Maps.newHashMap();
- try {
- if (user == null) {
- resultObj.put("errno", 400);
- resultObj.put("errmsg", "用户登录超时,请重新登录");
- return resultObj;
- }
- if (!user.getRoleType().equalsIgnoreCase("2")) {
- resultObj.put("errno", 400);
- resultObj.put("errmsg", "该操作只允许店员账户操作");
- return resultObj;
- }
- if (org.apache.commons.lang3.StringUtils.isEmpty(user.getMerchSn())) {
- resultObj.put("errno", 400);
- resultObj.put("errmsg", "操作用户的商户编号为空,请先维护用户商户编号信息再来操作");
- return resultObj;
- }
- Long userId = user.getUserId();
- Integer storeId = user.getStoreId();
- List<GoodsEntity> goodsEntities = new ArrayList<>();
- BigDecimal totalTax = new BigDecimal(0);
- // 检查库存和更新库存
- for (LinkedHashMap goodsDto : goodsList) {
- // 要购买的数量
- Integer sellVolume = (Integer) goodsDto.get("sellVolume");
- Integer goodsSellNumber = (Integer) goodsDto.get("sellVolume");
- String prodBarcode = (String) goodsDto.get("prodBarcode");
- String sku = (String) goodsDto.get("goodsSn");
- Map<GoodsEntity, Integer> numberMap = new HashMap<>();
- // 根据商品条码,门店id,sku查找库存
- List<GoodsEntity> queryGoodsList = goodsDao.queryListByBarcode(prodBarcode, storeId,sku);
- if (queryGoodsList != null && queryGoodsList.size() != 0) {
- for (GoodsEntity goodsEntity : queryGoodsList) {
- // 如果当前还有需要购买的
- if (sellVolume > 0) {
- // 当前商品剩余的数量, 门店库存
- Integer remainAmount = Integer.parseInt(goodsEntity.getStockNum());
- if (sellVolume >= remainAmount) {
- // 证明该sku库存不足,需要继续向下个sku消费
- sellVolume -= remainAmount;
- // 记录该商品用了多少个数量
- numberMap.put(goodsEntity, remainAmount);
- } else {
- // 记录该商品用了多少个数量
- numberMap.put(goodsEntity, sellVolume);
- sellVolume = 0;
- }
- }
- }
- }
- // 园区库存是有问题的, 这里去掉校验极端情况下可能会导致园区库存为负数
- // if (sellVolume > 0) {
- // resultObj.put("errno", 400);
- // resultObj.put("errmsg", "订单提交失败:条形码:" + prodBarcode + ",电商门店库存不足");
- // return resultObj;
- // }
- Iterator<GoodsEntity> goodsIterator = numberMap.keySet().iterator();
- // 循环购买的商品map,重新计算数量跟价格
- while (goodsIterator.hasNext()) {
- GoodsEntity goodsEntity = goodsIterator.next();
- // 该商品购买数量
- Integer num = numberMap.get(goodsEntity);
- // 取得规格的信息,判断规格库存,门店库存
- ProductStoreRelaEntity productInfo = productStoreRelaDao
- .queryByGoodsIdAndStoreId(Long.valueOf(storeId), Long.valueOf(goodsEntity.getId()));
- // 判断园区库存
- synchronized (productInfo) {
- // if (null == productInfo || null == productInfo.getStockNum() ||
- // productInfo.getStockNum() < (num)) {
- // resultObj.put("errno", 400);
- // resultObj.put("errmsg", "条形码:" + prodBarcode + ",电商门店库存不足,仅剩余" + productInfo.getStockNum());
- // return resultObj;
- // } else {
- // 判断销售价是否低于底线价
- // if(productInfo.getBottomLinePrice() != null){
- // BigDecimal bottomLinePrice = new BigDecimal(productInfo.getBottomLinePrice());
- // if (goodsEntity.getStoreRetailPrice().compareTo(bottomLinePrice) <= -1) {
- // LOGGER.error("销售价格小于底线价格");
- //
- // // 记录该信息,到价格过低日志表中,这里没有活动id
- // Mall2LowPriceWarningEntity lowPriceWarningEntity = new Mall2LowPriceWarningEntity();
- // lowPriceWarningEntity.setSalePrice(goodsEntity.getStoreRetailPrice());
- // lowPriceWarningEntity.setWarningPrice(bottomLinePrice);
- // lowPriceWarningEntity.setSku(goodsEntity.getGoodsSn());
- // lowPriceWarningEntity.setWarningType("00");
- // lowPriceWarningEntity.setStoreId(storeId+"");
- // lowPriceWarningEntity.setCreateTime(new Date());
- //
- // lowPriceWarningDao.save(lowPriceWarningEntity);
- // resultObj.put("errno", 400);
- // resultObj.put("errmsg", "商品"+goodsEntity.getName()+"的销售价格小于底线价格");
- // return resultObj;
- // }
- // }
- // 门店库存变化记录
- StoreMngChangeEntity storeMngChangeEntity = new StoreMngChangeEntity();
- storeMngChangeEntity.setChangeType(Dict.changeType.item_1.getItem());
- storeMngChangeEntity.setChangeReason("商品销售扣减");
- storeMngChangeEntity.setGoodsId(Integer.parseInt(String.valueOf(productInfo.getGoodsId())));
- storeMngChangeEntity.setStoreId(Integer.parseInt(String.valueOf(productInfo.getStoreId())));
- storeMngChangeEntity.setMerchSn(productInfo.getMerchSn());
- storeMngChangeEntity.setStoreChangeNum(num);
- storeMngChangeEntity.setStoreOriginalNum(productInfo.getStockNum());
- storeMngChangeEntity.setStoreValidNum(productInfo.getStockNum() - num);
- storeMngChangeEntity.setCreateTime(new Date());
- storeMngChangeEntity.setModTime(new Date());
- storeMngChangeEntity.setCreaterSn(user.getUsername());
- storeMngChangeEntity.setModerSn(user.getUsername());
- storeMngChangeEntity.setIsValid(0);
- storeMngChangeDao.save(storeMngChangeEntity);
- int validNum = productInfo.getStockNum() - num;
- if (goodsEntity != null) {
- MngChangeEntity mngChangeEntity = new MngChangeEntity();
- mngChangeEntity.setThirdPartyMerchCode(goodsEntity.getThirdPartyMerchCode());
- mngChangeEntity.setChangeReason("商品销售扣减");
- mngChangeEntity.setCreateTime(new Date());
- mngChangeEntity.setModTime(new Date());
- mngChangeEntity.setCreaterSn(user.getUsername());
- mngChangeEntity.setModerSn(user.getUsername());
- mngChangeEntity.setIsValid(0);
- mngChangeEntity.setMerchSn(goodsEntity.getMerchSn());
- mngChangeEntity.setOriginalNum(goodsEntity.getGoodsNumber());//原库存数
- mngChangeEntity.setValidNum(goodsEntity.getGoodsNumber() - num);//可用数
- mngChangeEntity.setChangeNum(num);//变化数
- mngChangeEntity.setChangeType(Dict.changeType.item_1.getItem());
- mngChangeEntity.setGoodsId(Integer.parseInt(String.valueOf(goodsEntity.getId())));
- mngChangeDao.save(mngChangeEntity);
- // 如果园区库存数量小于等于0, 则不更新园区库存, 园区库存只做参考
- int diff = Math.max(goodsEntity.getGoodsNumber() - num, 0);
- goodsEntity.setGoodsNumber(diff);
- goodsEntity.setLastSaleTime(new Date());
- goodsDao.update(goodsEntity);
- }
- // 门店库存
- productInfo.setStockNum(validNum);
- productInfo.setStoreId(Long.valueOf(storeId));
- productInfo.setSellVolume(productInfo.getSellVolume() + num);
- productInfo.setLastSaleTime(new Date());
- productStoreRelaDao.updateStockNum(productInfo);//修改普通商品库存
- }
- BigDecimal retailPrice = new BigDecimal(0);
- BigDecimal storeRetailPrice = new BigDecimal(0);
- if (goodsDto.get("retailPrice") instanceof Double) {
- retailPrice = new BigDecimal((Double) goodsDto.get("retailPrice")); // 单价
- storeRetailPrice = new BigDecimal((Double) goodsDto.get("retailPrice")); // 单价
- } else if (goodsDto.get("retailPrice") instanceof Integer) {
- retailPrice = new BigDecimal((Integer) goodsDto.get("retailPrice"));
- storeRetailPrice = new BigDecimal((Integer) goodsDto.get("retailPrice"));
- } else if (goodsDto.get("retailPrice") instanceof Float) {
- retailPrice = new BigDecimal((Float) goodsDto.get("retailPrice"));
- storeRetailPrice = new BigDecimal((Float) goodsDto.get("retailPrice"));
- }
- // 优惠价
- BigDecimal disCountedPrice = new BigDecimal(0);
- // 实际支付价
- BigDecimal actualPaymentAmount = new BigDecimal(0);
- if (goodsDto.get("discountedPrice") instanceof Double) {
- disCountedPrice = new BigDecimal((Double) goodsDto.get("discountedPrice")); // 优惠金额
- } else if (goodsDto.get("discountedPrice") instanceof Integer) {
- disCountedPrice = new BigDecimal((Integer) goodsDto.get("discountedPrice"));
- } else if (goodsDto.get("discountedPrice") instanceof Float) {
- disCountedPrice = new BigDecimal((Float) goodsDto.get("discountedPrice"));
- }
- if (goodsDto.get("actualPaymentAmount") instanceof Double) {
- actualPaymentAmount = new BigDecimal((Double) goodsDto.get("actualPaymentAmount")); // 实际支付价格
- } else if (goodsDto.get("actualPaymentAmount") instanceof Integer) {
- actualPaymentAmount = new BigDecimal((Integer) goodsDto.get("actualPaymentAmount"));
- } else if (goodsDto.get("actualPaymentAmount") instanceof Float) {
- actualPaymentAmount = new BigDecimal((Float) goodsDto.get("actualPaymentAmount"));
- }
- disCountedPrice = disCountedPrice
- .divide(new BigDecimal(goodsSellNumber), 3, RoundingMode.HALF_UP)
- .multiply(new BigDecimal(num))
- .setScale(2, RoundingMode.HALF_UP);
- actualPaymentAmount = actualPaymentAmount
- .divide(new BigDecimal(goodsSellNumber), 3, RoundingMode.HALF_UP)
- .multiply(new BigDecimal(num))
- .setScale(2, RoundingMode.HALF_UP);
- goodsEntity.setRetailPrice(retailPrice);
- goodsEntity.setStoreRetailPrice(storeRetailPrice);
- goodsEntity.setDiscountedPrice(disCountedPrice);
- goodsEntity.setActualPaymentAmount(actualPaymentAmount);
- // 借用这个字段来存储购买数
- goodsEntity.setGoodsNumber(num);
- goodsEntity.setActivity((String) goodsDto.get("activity"));
- goodsEntities.add(goodsEntity);
- }
- // 计算该购物车所需要的所有税费
- Object taxObject = goodsDto.get("goodstaxes");
- BigDecimal tax = new BigDecimal(0);
- if (taxObject instanceof Double) {
- tax = new BigDecimal((Double) taxObject);
- } else if (taxObject instanceof Integer) {
- tax = new BigDecimal((Integer) taxObject);
- } else if (taxObject instanceof Float) {
- tax = new BigDecimal((Float) taxObject);
- } else if (taxObject instanceof String) {
- tax = new BigDecimal((String) taxObject);
- }
- totalTax = totalTax.add(tax).setScale(2, BigDecimal.ROUND_HALF_DOWN); // 计算总的税额
- }
- UserEntity userEntity = userDao.queryByMobile((String) userInfo.get("customPhone"));
- if (userEntity == null) {
- // 保存用户信息
- userEntity = new UserEntity();
- userEntity.setUsername((String) userInfo.get("customName"));
- userEntity.setPassword("");
- userEntity.setIdNo((String) userInfo.get("customIDCard"));
- userEntity.setMobile((String) userInfo.get("customPhone"));
- userEntity.setGender(1);
- userEntity.setRegisterTime(new Date());
- userEntity.setLastLoginTime(new Date());
- userEntity.setIdNo((String) userInfo.get("customIDCard"));
- userDao.save(userEntity);
- MerchUserEntity merchUserEntity = new MerchUserEntity();
- merchUserEntity.setMerchSn(user.getMerchSn());
- merchUserEntity.setStoreId(storeId);
- merchUserEntity.setUserId(userEntity.getId());
- merchUserEntity.setCreateTime(new Date());
- merchUserEntity.setIsLoadGoods("0");
- merchUserDao.save(merchUserEntity);
- } else {
- userEntity.setUsername((String) userInfo.get("customName"));
- userEntity.setIdNo((String) userInfo.get("customIDCard"));
- userEntity.setMobile((String) userInfo.get("customPhone"));
- userDao.update(userEntity);
- }
- // TODO 查询使用的优惠券,并减扣金额
- String couponSn = (String) userInfo.get("couponSn");
- // 获取当前时间
- String currentTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
- MkActivitiesCouponEntity couponEntity = mkActivitiesCouponService.queryByCouponSn(couponSn, currentTime);
- // // 优惠金额
- BigDecimal disCountAmount = new BigDecimal(0);
- if (couponEntity != null) {
- disCountAmount = couponEntity.getCouponPrice();
- }
- // 判断该用户是否是生日
- Boolean isBirth = false;
- String birthday = "";
- if (userEntity.getIdNo().length() == 15) {
- birthday = userEntity.getIdNo().substring(8, 10) + "-" + userEntity.getIdNo().substring(10, 12);
- } else if (userEntity.getIdNo().length() == 18) {
- birthday = userEntity.getIdNo().substring(10, 12) + "-" + userEntity.getIdNo().substring(12, 14);
- }
- SimpleDateFormat format = new SimpleDateFormat("MM-dd");
- String today = format.format(new Date());
- if (birthday.equalsIgnoreCase(today)) {
- isBirth = true;
- }
- // 生成订单
- String merchOrderSn = "EMATO" + CommonUtil.generateOrderNumber();
- OrderVo order = setOrderVo(goodsEntities, userEntity, storeId.longValue(), user.getMerchSn(), disCountAmount, totalTax, status, mapAddr);
- order.setStore_id(storeId.longValue());
- // if(storeTopic != null){
- // order.setActivity_id(storeTopic.getId().longValue());
- // }
- order.setMerchOrderSn(merchOrderSn);
- order.setCoupon_name(couponSn); // 借用这个字段来记录是否使用优惠券
- //插入订单信息和订单商品
- orderDao.saveOrderVo(order);
- // TODO req_2021-07-19 电商端下单时间 req_20210826_001
- customsClearanceTimeliness.send(Arrays.asList(order.getOrder_sn()), "customerOrder");
- // TODO 订单流转表
- OrderProcessRecordEntity processRecordEntity = new OrderProcessRecordEntity();
- processRecordEntity.setOrderSn(order.getOrder_sn());
- processRecordEntity.setUserId(Integer.valueOf(userEntity.getId() + ""));
- processRecordEntity.setAddOrderStartTime(order.getCreateTime());
- processRecordEntity.setIsAddOrderSend(Dict.isSend.item_1.getItem());
- processRecordEntity.setOrderBizType(Dict.orderBizType.item_10.getItem());
- if (null == order.getId()) {
- resultObj.put("errno", 400);
- resultObj.put("errmsg", "订单提交失败");
- return resultObj;
- }
- List<OrderGoodsVo> orderGoodsVoList = new ArrayList<>();
- for (GoodsEntity goodsDto : goodsEntities) {
- OrderGoodsVo orderGoodsVo = setOrderGoodsVo(order, goodsDto);
- //新增订单详情
- orderGoodsDao.saveOrderGoodsVo(orderGoodsVo);
- orderGoodsVoList.add(orderGoodsVo);
- }
- //清空预订单商品临时表
- Map orderInfoMap = Maps.newHashMap();
- orderInfoMap.put("orderInfo", order);
- resultObj.put("errno", 0);
- resultObj.put("errmsg", "订单提交成功");
- resultObj.put("data", orderInfoMap);
- //判断支付类型,并支付订单
- R r = null;
- //保存支付记录
- OrderWXPayRecordEntity orderWXPayRecordCurrent = orderWXPayRecordService.saveRecordVo(order);
- StoreEntity store = storeService.queryObject(order.getStore_id().intValue());
- // 设置支付单开始时间
- // TODO req_2021-07-19 顾客付款时间 req_20210826_001
- customsClearanceTimeliness.send(Arrays.asList(order.getOrder_sn()), "customerPay");
- processRecordEntity.setPaymentStartTime(new Date());
- // 判断是微信的支付码还是支付宝的支付码
- // if (parCode.startsWith("28")) {
- // // 支付宝支付
- // try {
- // AliPay(user, parCode, order, processRecordEntity, orderWXPayRecordCurrent, store);
- // } catch (Exception e) {
- // e.printStackTrace();
- // throw e;
- // }
- // } else {
- // // 微信支付
- // try {
- // wxPay(user, parCode, resultObj, order, processRecordEntity, orderWXPayRecordCurrent, store);
- // } catch (Exception e) {
- // e.printStackTrace();
- // throw e;
- // }
- // }
- // TODO req_2021-07-19 客户付款完成时间 req_20210826_001
- customsClearanceTimeliness.send(Arrays.asList(order.getOrder_sn()), "customerPayFinished");
- processRecordEntity.setPaymentStartTime(new Date());
- // TODO 到时候要注释掉,测试用而已
- OrderEntity orderEntity = queryObject(order.getId());
- orderEntity.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_201.getItem()));
- orderEntity.setPayStatus(Integer.parseInt(Dict.payStatus.item_2.getItem()));
- orderEntity.setPayTime(new Date());
- orderDao.update(orderEntity);
- resultObj.put("shopName", store.getStoreName()); // 根据门店编号查询
- resultObj.put("userName", user.getUsername());
- // 保存订单流转表
- // 设置下单完成时间
- processRecordEntity.setAddOrderSuccTime(order.getPay_time());
- orderProcessRecordDao.save(processRecordEntity);
- // 生成销售记录
- SaleRecordEntity saleRecordEntity = new SaleRecordEntity();
- // 根据收银机机器码,查询收银机
- CashierEntity cashierEntity = cashierDao.queryByMachineCode(machineCode, storeId + "");
- if (cashierEntity != null) {
- saleRecordEntity.setCashierSn(cashierEntity.getCashierSn());
- saleRecordEntity.setOrderSn(order.getOrder_sn());
- saleRecordEntity.setSallerId(userId + "");
- saleRecordEntity.setSalesTime(new Date());
- // saleRecordEntity.setDiscountId(topicId + "");
- saleRecordEntity.setCreateTime(new Date());
- saleRecordDao.save(saleRecordEntity);
- }
- // 查询积分规则 ,默认先按消费金额1:1积分
- Mall2PointsRulesEntity pointsRules = null;
- // 增加该会员的积分
- Mall2MemberPointsEntity memberPointsEntity = memberPointsDao.queryByUserId(userEntity.getId());
- if (memberPointsEntity == null) {
- memberPointsEntity = new Mall2MemberPointsEntity();
- memberPointsEntity.setUserId(userEntity.getId() + "");
- memberPointsEntity.setPoints(order.getActual_price().intValue());
- memberPointsEntity.setCreaterSn(userId + "");
- memberPointsEntity.setCreateTime(new Date());
- memberPointsDao.save(memberPointsEntity);
- } else {
- memberPointsEntity.setPoints(order.getActual_price().add(new BigDecimal(memberPointsEntity.getPoints())).intValue());
- memberPointsEntity.setModerSn(userId + "");
- memberPointsEntity.setModTime(new Date());
- memberPointsDao.update(memberPointsEntity);
- }
- // 增加该会员的消费记录
- Mall2MemberConsumptionRecordsEntity consumptionRecords = new Mall2MemberConsumptionRecordsEntity();
- consumptionRecords.setUserId(userEntity.getId() + "");
- consumptionRecords.setOrderSn(order.getOrder_sn());
- consumptionRecords.setConsumptionTime(new Date());
- consumptionRecords.setShopSn(storeId + "");
- // TODO 判断是否有使用生日优惠
- if (isBirth) {
- consumptionRecords.setIsUseBirthdayOffer("0"); // 使用生日优惠
- } else {
- consumptionRecords.setIsUseBirthdayOffer("1"); // 没使用生日优惠
- }
- consumptionRecords.setCreaterSn(userId + "");
- consumptionRecords.setCreateTime(new Date());
- memberConsumptionRecordsDao.save(consumptionRecords);
- // 生成取票码
- PickUpCodeEntity pickUpCodeEntity = new PickUpCodeEntity();
- pickUpCodeEntity.setOrderSn(order.getOrder_sn());
- pickUpCodeEntity.setPickUpCodeSn(cashierEntity.getCashierSn());//小票码前段
- pickUpCodeService.save(pickUpCodeEntity);
- resultObj.put("code", pickUpCodeEntity.getPickUpCodeSn()); // 系统中累加
- resultObj.put("time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
- resultObj.put("orderNo", order.getOrder_sn()); //
- resultObj.put("phone", (String) userInfo.get("customPhone"));
- // 通知WebSocket
- WebSocketServer.sendMessage(sessionId, order.getOrder_sn(), order.getStore_id()
- + "");
- // TODO 下单流程完成了,现在将下单的库存明细存入表中,准备发送到中控
- // List<KtoEccsEntity> ktoEccsEntities = new LinkedList<>();
- //// orderGoodsVoList
- // for (OrderGoodsVo orderGoodsVo : orderGoodsVoList) {
- // KtoEccsEntity ktoEccsEntity = new KtoEccsEntity();
- // ktoEccsEntity.setRequestData(JSON.toJSONString(orderGoodsVo));
- // ktoEccsEntity.setRequestType("03");
- // ktoEccsEntity.setSendStatus("00");
- // ktoEccsEntity.setCreaterSn(user.getUserId()+"");
- // ktoEccsEntity.setCreateTime(new Date());
- // ktoEccsEntities.add(ktoEccsEntity);
- // }
- //
- //
- // if(ktoEccsEntities.size() > 0){
- // if(ktoEccsEntities.size() > 50){
- // List<List<KtoEccsEntity>> partition = Lists.partition(ktoEccsEntities, 50);
- // for (List<KtoEccsEntity> ktoEccs : partition) {
- // ktoEccsService.saveBatch(ktoEccs);
- // }
- // }else{
- // ktoEccsService.saveBatch(ktoEccsEntities);
- // }
- // }
- return resultObj;
- } catch (Exception e) {
- e.printStackTrace();
- resultObj.put("errno", 400);
- resultObj.put("errmsg", "订单异常------" + e.getMessage());
- throw new RuntimeException(e);
- }
- }
- // private BigDecimal getDisCountAmout(List<GoodsEntity> goodsEntities) {
- // BigDecimal disCountAmount;
- // // TODO 生成订单之前,先查询是否有优惠券或者满减
- // // TODO 20200610 要修改成全部商品
- // // 优惠券的集合
- // List<MkStoreTicketDiscountEntity> mkStoreTicketDiscountEntities = new ArrayList<>();
- // // 满减的集合
- // List<MkStoreCampMinusLevelEntity> mkStoreCampMinusEntities = new ArrayList<>();
- // // 存商品跟金额的关系
- // Map<Long,BigDecimal> moneyMap = new HashMap<>();
- // // 商品总价
- // BigDecimal totalPrice = new BigDecimal(0);
- //
- // for(GoodsEntity goodsEntity : goodsEntities){
- // Long goodsId = goodsEntity.getId();
- // // 计算该商品的价格
- // BigDecimal goodsPrice = goodsEntity.getStoreRetailPrice().multiply(new BigDecimal(goodsEntity.getGoodsNumber())).setScale(2, RoundingMode.HALF_UP);
- // moneyMap.put(goodsId,goodsPrice);
- // totalPrice = totalPrice.add(goodsPrice);
- // // 查询该商品id是否有优惠券
- // List<MkStoreTicketDiscountEntity> mkStoreTicketDiscountEntity = mkStoreTicketDiscountService.queryByGoodsId(goodsId);
- // if(mkStoreTicketDiscountEntity != null) {
- // mkStoreTicketDiscountEntities.addAll(mkStoreTicketDiscountEntity);
- // }
- // // 查询该商品id是否有满减
- // List<MkStoreCampMinusLevelEntity> mkStoreCampMinusEntity = mkStoreCampMinusService.queryByGoodsId(goodsId);
- // if(mkStoreCampMinusEntity != null) {
- // mkStoreCampMinusEntities.addAll(mkStoreCampMinusEntity);
- // }
- // }
- //
- // // 满减优惠的金额
- // BigDecimal campDisCountAmount = new BigDecimal(0);
- // if(mkStoreCampMinusEntities.size() > 0){
- // // 上一次所需金额,用于取最大的优惠力度
- // BigDecimal lastAmount = new BigDecimal(0);
- // for (int i = 0 ; i < mkStoreCampMinusEntities.size() ; i++){
- // MkStoreCampMinusLevelEntity mkStoreCampMinusLevelEntity = mkStoreCampMinusEntities.get(i);
- // // TODO 20200610还有满多少件,跟满多少元打折的,逻辑复杂,下次开发
- // BigDecimal discCond = mkStoreCampMinusLevelEntity.getYuanMinusCond();
- // // 判断这次金额是否大于上次金额,如果不大于,直接continue
- // if(discCond.compareTo(lastAmount) > 0){
- // // 如果总金额大于所需金额,则可以使用该优惠券,记录该优惠券的角标,金额跟优惠的钱
- // if(totalPrice.compareTo(discCond) > 0){
- // // 记录上一次金额
- // lastAmount = discCond;
- // campDisCountAmount = mkStoreCampMinusLevelEntity.getYuanMinusPref();
- // }
- // }
- // }
- // }
- //
- // // 优惠券优惠的金额
- // BigDecimal ticketDisCountAmount = new BigDecimal(0);
- // if(mkStoreTicketDiscountEntities.size() > 0){
- // // 上一次所需金额,用于取最大的优惠力度
- // BigDecimal lastAmount = new BigDecimal(0);
- // BigDecimal lastRadio = new BigDecimal(0);
- // for (int i = 0 ; i < mkStoreTicketDiscountEntities.size() ; i++){
- // MkStoreTicketDiscountEntity mkStoreTicketDiscountEntity = mkStoreTicketDiscountEntities.get(i);
- // // 代金券所需金额
- // // TODO 20200610还有折扣券的,逻辑较为复杂,下次在开发
- //
- // if("00".equals(mkStoreTicketDiscountEntity.getApplyType())){
- // BigDecimal discCond = mkStoreTicketDiscountEntity.getVoucherCond();
- // // 判断这次金额是否大于上次金额,如果不大于,直接continue
- // if(discCond.compareTo(lastAmount) > 0){
- // // 如果总金额大于所需金额,则可以使用该优惠券,记录该优惠券的角标,金额跟优惠的钱
- // if(totalPrice.compareTo(discCond) > 0){
- // // 记录上一次金额
- // lastAmount = discCond;
- // ticketDisCountAmount = mkStoreTicketDiscountEntity.getVoucherMoney();
- // }
- // }
- // }else if("01".equals(mkStoreTicketDiscountEntity.getApplyType())){
- // BigDecimal discCond = mkStoreTicketDiscountEntity.getDiscCond();
- // if(totalPrice.compareTo(discCond) > 0){
- // // 打的折扣
- // lastRadio = mkStoreTicketDiscountEntity.getDiscRatio();
- // }
- //
- //
- // }
- //
- //
- // }
- // }
- //
- //
- // disCountAmount = ticketDisCountAmount.compareTo(campDisCountAmount) > 0 ? ticketDisCountAmount : campDisCountAmount;
- // return disCountAmount;
- // }
- private void AliPay(SysUserEntity user, String parCode, OrderVo order, OrderProcessRecordEntity processRecordEntity, OrderWXPayRecordEntity orderWXPayRecordCurrent, StoreEntity store) throws Exception {
- AliPayRequestParams params = new AliPayRequestParams();
- String orderBizTypeZn = "普通货物";
- if ("00".equals(order.getOrderBizType())) {
- orderBizTypeZn = "保税备货";
- } else if ("02".equals(order.getOrderBizType())) {
- orderBizTypeZn = "保税展示补货";
- } else if ("10".equals(order.getOrderBizType())) {
- orderBizTypeZn = "保税展示跨境";
- }
- params.setAuthCode(parCode);
- params.setBody(order.getApprovalRemark());
- params.setOutTradeNo(order.getOrder_sn());
- params.setSubject(store.getMerchName() + "-" + store.getStoreName() + "-" + orderBizTypeZn);
- params.setStoreId(store.getId() + "");
- params.setTotalAmount(order.getActual_price().setScale(2, BigDecimal.ROUND_HALF_UP) + "");
- LOGGER.info("调用阿里支付接口的请求参数:" + JacksonUtils.toJson(params));
- AliPayMicropayApiResult aliPayMicropayApiResult = AliPayUtil.aliTradePay(params);
- orderWXPayRecordService.updateRecordByAli(orderWXPayRecordCurrent.getId(), aliPayMicropayApiResult);
- LOGGER.info("调用阿里支付接口的同步返回结果:" + JacksonUtils.toJson(aliPayMicropayApiResult));
- // 修改订单状态
- //当支付成功时,修改订单,并把其他支付记录撤销
- if (AliPayUtil.AliPayTradeState.SUCC.getCode().equals(aliPayMicropayApiResult.getCode())) {
- // //查询当前订单所有的支付记录
- // List<OrderWXPayRecordEntity> orderWXPayRecordEntitys =
- // orderWXPayRecordService.getRecordsByOutTradeNo(order.getOrder_sn());
- this.confirmPay(order.getId(), Dict.payFlag.item_alipay.getItem(), aliPayMicropayApiResult.getTradeNo());
- // 设置支付单完成时间
- processRecordEntity.setPaymentSuccTime(aliPayMicropayApiResult.getGmtPayment());
- processRecordEntity.setPayTransactionId(aliPayMicropayApiResult.getTradeNo());
- // 系统繁忙
- } else if (AliPayUtil.AliPayTradeState.SERVER_FAIL.getCode().equals(aliPayMicropayApiResult.getCode())) {
- LOGGER.info(aliPayMicropayApiResult.getSubMsg());
- throw new RuntimeException(aliPayMicropayApiResult.getSubMsg() + ",请稍后再试");
- // 支付失败
- } else if (AliPayUtil.AliPayTradeState.BUSINESS_FAIL.getCode().equals(aliPayMicropayApiResult.getCode())) {
- // 系统异常
- if (AliPayUtil.BusinessFailState.SYSTEM_ERROR.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())) {
- LOGGER.info(aliPayMicropayApiResult.getSubMsg());
- throw new RuntimeException(aliPayMicropayApiResult.getSubMsg() + ",请稍后再试");
- // 订单总额超过限额
- } else if (AliPayUtil.BusinessFailState.TOTAL_FEE_EXCEED.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())) {
- LOGGER.info(aliPayMicropayApiResult.getSubMsg());
- throw new RuntimeException(aliPayMicropayApiResult.getSubMsg() + ",请告知顾客");
- // 授权码无效
- } else if (AliPayUtil.BusinessFailState.PAYMENT_AUTH_CODE_INVALID.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())) {
- LOGGER.info(aliPayMicropayApiResult.getSubMsg());
- throw new RuntimeException(aliPayMicropayApiResult.getSubMsg() + ",请顾客刷新条码后,重新支付");
- // 交易信息被篡改
- } else if (AliPayUtil.BusinessFailState.CONTEXT_INCONSISTENT.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())) {
- LOGGER.info(aliPayMicropayApiResult.getSubMsg());
- throw new RuntimeException(aliPayMicropayApiResult.getSubMsg() + ",请重试");
- // 余额支付功能关闭
- } else if (AliPayUtil.BusinessFailState.ERROR_BALANCE_PAYMENT_DISABLE.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())) {
- LOGGER.info(aliPayMicropayApiResult.getSubMsg());
- throw new RuntimeException(aliPayMicropayApiResult.getSubMsg() + ",请用户打开余额支付");
- // 交易买家不匹配
- } else if (AliPayUtil.BusinessFailState.TRADE_BUYER_NOT_MATCH.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())) {
- LOGGER.info(aliPayMicropayApiResult.getSubMsg());
- throw new RuntimeException(aliPayMicropayApiResult.getSubMsg() + ",请重试");
- // 买家状态非法
- } else if (AliPayUtil.BusinessFailState.BUYER_ENABLE_STATUS_FORBID.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())) {
- LOGGER.info(aliPayMicropayApiResult.getSubMsg());
- throw new RuntimeException(aliPayMicropayApiResult.getSubMsg() + ",请买家联系支付宝小二,确认为什么非法");
- // 唤起移动收银台失败
- } else if (AliPayUtil.BusinessFailState.PULL_MOBILE_CASHIER_FAIL.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())) {
- LOGGER.info(aliPayMicropayApiResult.getSubMsg());
- throw new RuntimeException(aliPayMicropayApiResult.getSubMsg() + ",请用户刷新条码后,重新支付");
- // 用户的无限支付开关关闭
- } else if (AliPayUtil.BusinessFailState.MOBILE_PAYMENT_SWITCH_OFF.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())) {
- LOGGER.info(aliPayMicropayApiResult.getSubMsg());
- throw new RuntimeException(aliPayMicropayApiResult.getSubMsg() + ",请用户在PC上打开无线支付开关后,在发起支付");
- // 支付失败
- } else if (AliPayUtil.BusinessFailState.PAYMENT_FAIL.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())) {
- LOGGER.info(aliPayMicropayApiResult.getSubMsg());
- throw new RuntimeException(aliPayMicropayApiResult.getSubMsg() + ",请重试");
- // 商户账号被冻结
- } else if (AliPayUtil.BusinessFailState.SELLER_BEEN_BLOCKED.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())) {
- LOGGER.info(aliPayMicropayApiResult.getSubMsg());
- throw new RuntimeException(aliPayMicropayApiResult.getSubMsg() + ",请联系支付宝小二解冻");
- // 买家未通过人行认证
- } else if (AliPayUtil.BusinessFailState.ERROR_BUYER_CERTIFY_LEVEL_LIMIT.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())) {
- LOGGER.info(aliPayMicropayApiResult.getSubMsg());
- throw new RuntimeException(aliPayMicropayApiResult.getSubMsg() + ",请买家联系支付宝小二");
- // 用户当面付付款开关管壁
- } else if (AliPayUtil.BusinessFailState.USER_FACE_PAYMENT_SWITCH_OFF.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())) {
- LOGGER.info(aliPayMicropayApiResult.getSubMsg());
- throw new RuntimeException(aliPayMicropayApiResult.getSubMsg() + ",请买家打开当面付付款开关");
- } else {
- LOGGER.info(aliPayMicropayApiResult.getSubMsg());
- throw new RuntimeException(aliPayMicropayApiResult.getSubMsg());
- }
- // 其他支付异常状态
- } else {
- LOGGER.info(aliPayMicropayApiResult.getSubMsg());
- throw new RuntimeException(aliPayMicropayApiResult.getSubMsg() + "...........请联系管理员");
- }
- }
- private void wxPay(SysUserEntity user, String parCode, Map resultObj, OrderVo order, OrderProcessRecordEntity processRecordEntity, OrderWXPayRecordEntity orderWXPayRecordCurrent, StoreEntity store) throws ParseException {
- R r;
- String ip = "127.0.0.1";
- try {
- InetAddress ia = InetAddress.getLocalHost();
- // String localname=ia.getHostName();
- ip = ia.getHostAddress();
- } catch (Exception e) {
- e.printStackTrace();
- }
- WechatMicropayApiResult wechatMicropayApiResult = WechatUtil
- .wxMicropay(store.getMerchName() + "-" + store.getStoreName(), order.getOrderBizType(), null,
- orderWXPayRecordCurrent.getOutTradeNoWX(), order.getActual_price().doubleValue(),
- ip, parCode);
- orderWXPayRecordService.updateRecord(orderWXPayRecordCurrent.getId(), wechatMicropayApiResult);
- resultObj.put("shopName", store.getStoreName()); // 根据门店编号查询
- resultObj.put("userName", user.getUsername());
- // 修改订单状态
- //当支付成功时,修改订单,并把其他支付记录撤销
- if (WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatMicropayApiResult.getTrade_state())) {
- //查询当前订单所有的支付记录
- List<OrderWXPayRecordEntity> orderWXPayRecordEntitys =
- orderWXPayRecordService.getRecordsByOutTradeNo(order.getOrder_sn());
- LOGGER.info("wechatMicropayApiResult.getTransaction_id()" + wechatMicropayApiResult.getTransaction_id());
- Map orderRaram = Maps.newHashMap();
- orderRaram.put("payTransactionId", wechatMicropayApiResult.getTransaction_id());
- orderRaram.put("orderId", order.getId());
- orderDao.updateOrderInfo(orderRaram);
- this.confirmPay(order.getId(), Dict.payFlag.item_weixin.getItem(), orderWXPayRecordCurrent.getOutTradeNoWX());
- // 设置支付单完成时间
- processRecordEntity.setPaymentSuccTimeStr(wechatMicropayApiResult.getTime_end());
- processRecordEntity.setPaymentSuccTime(
- new SimpleDateFormat("yyyyMMddHHmmss").parse(wechatMicropayApiResult.getTime_end()));
- processRecordEntity.setPayTransactionId(wechatMicropayApiResult.getTransaction_id());
- //用户支付中
- } else if (WechatUtil.WXTradeState.USERPAYING.getCode().equals(wechatMicropayApiResult.getTrade_state())) {
- r = R.error(WechatUtil.WXTradeState.USERPAYING.getCodeZn() + ",稍等片刻后请刷新页面重新查看订单状态");
- int times = 0;
- // 查询是否支付了
- while (true) {
- boolean flag = orderQuery(order, processRecordEntity);
- if (flag) {
- break;
- }
- try {
- Thread.currentThread().sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- if (times >= 60) {
- throw new RuntimeException("超过60s未支付,订单下单失败");
- }
- times++;
- }
- //用户支付失败
- } else if (WechatUtil.WXTradeState.PAYERROR.getCode().equals(wechatMicropayApiResult.getTrade_state())) {
- WechatReverseApiResult wechatReverseApiResult =
- WechatUtil.wxReverse(orderWXPayRecordCurrent.getOutTradeNoWX());
- //撤销订单成功
- if (WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatReverseApiResult.getReturn_code()) &&
- WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatReverseApiResult.getResult_code())) {
- //调用订单查询接口
- WechatRefundApiResult wechatRefundApiResult =
- WechatUtil.wxOrderQuery(orderWXPayRecordCurrent.getOutTradeNoWX());
- if (WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatRefundApiResult.getReturn_code()) &&
- WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatRefundApiResult.getResult_code())) {
- // 修改订单支付记录
- orderWXPayRecordService
- .updateWXPayRecordTradeState(orderWXPayRecordCurrent.getId(), wechatRefundApiResult);
- }
- r = R.error(orderWXPayRecordCurrent.getErrCodeDes());
- } else {
- r = R.error(wechatReverseApiResult.getErr_code_des());
- }
- throw new RuntimeException("订单支付失败");
- } else {
- throw new RuntimeException("未支付或支付失败,请联系管理员");
- }
- }
- private boolean orderQuery(OrderVo order, OrderProcessRecordEntity processRecordEntity) {
- LOGGER.info(">>>>>>>>>>>>>>>>>>>>wxOrderQuery 微信查询接口调用");
- String merchOrderSn = order.getMerchOrderSn();
- String orderId = order.getId() + "";
- String orderSn = order.getOrder_sn();
- WechatRefundApiResult result = WechatUtil.wxOrderQuery(orderSn);
- if (result.getReturn_code().equalsIgnoreCase(WechatUtil.WXTradeState.SUCCESS.getCode())) {
- if (result.getResult_code().equalsIgnoreCase(WechatUtil.WXTradeState.SUCCESS.getCode())) {
- if (result.getTrade_state().equalsIgnoreCase(Dict.tradeState.item_SUCCESS.getItem())) {
- Date successTime = DateUtils.convertStringToDate(result.getTime_end(),
- DateUtils.DATE_TIME_PATTERN_YYYY_MM_DD_HH_MM_SS);
- Map orderRaram = Maps.newHashMap();
- orderRaram.put("payStatus", Dict.payStatus.item_2.getItem());//已支付
- orderRaram.put("orderStatus", Dict.orderStatus.item_201.getItem());//已支付
- orderRaram.put("payTransactionId", result.getTransaction_id());
- orderRaram.put("payTime", successTime);
- orderRaram.put("orderId", orderId);
- orderRaram.put("payFlag", Dict.payFlag.item_weixin.getItem());
- orderDao.updateOrderInfo(orderRaram);
- Map processParam = Maps.newHashMap();
- processParam.put("payTime", successTime);
- processParam.put("orderSn", orderSn);
- orderDao.updateOrderProcessRecord(processParam);
- // orderWXPayRecordService
- // .updateWXPayRecordTradeState(orderWXPayRecordTemp.getId(), wechatRefundApiResult);
- // 设置支付单完成时间
- processRecordEntity.setPaymentSuccTimeStr(result.getTime_end());
- processRecordEntity.setPaymentSuccTime(successTime);
- processRecordEntity.setPayTransactionId(result.getTransaction_id());
- return true;
- } else if (result.getTrade_state().equalsIgnoreCase(Dict.tradeState.item_NOTPAY.getItem())) {//订单未支付
- Map orderRaram = Maps.newHashMap();
- orderRaram.put("payStatus", Dict.payStatus.item_0.getItem());//支付状态未支付
- orderRaram.put("orderStatus", Dict.orderStatus.item_0.getItem());//订单状态未支付
- orderRaram.put("orderId", orderId);
- orderDao.updateOrderInfo(orderRaram);
- } else if (result.getTrade_state().equalsIgnoreCase(Dict.tradeState.item_CLOSED.getItem())) {
- Map orderRaram = Maps.newHashMap();
- orderRaram.put("payStatus", Dict.payStatus.item_7.getItem());
- orderRaram.put("orderStatus", Dict.orderStatus.item_500.getItem());
- orderRaram.put("orderId", orderId);
- orderDao.updateOrderInfo(orderRaram);
- LOGGER.info(">>>>>>>>>>>>>>>>>>>>wxOrderByTransactionIdQueryUpdFail 根据支付单查询微信接口返回信息:state 【" + result.getTrade_state() +
- "】,des【" + result.getTrade_state_desc() + "】");
- return false;
- } else if (result.getTrade_state().equalsIgnoreCase(Dict.tradeState.item_PAYERROR.getItem())) {
- Map orderRaram = Maps.newHashMap();
- orderRaram.put("payStatus", Dict.payStatus.item_8.getItem());
- orderRaram.put("orderStatus", Dict.orderStatus.item_501.getItem());
- orderRaram.put("orderId", orderId);
- orderDao.updateOrderInfo(orderRaram);
- LOGGER.info(">>>>>>>>>>>>>>>>>>>>wxOrderByTransactionIdQueryUpdFail 根据支付单查询微信接口返回信息:state 【" + result.getTrade_state() +
- "】,des【" + result.getTrade_state_desc() + "】");
- return false;
- } else if (result.getTrade_state().equalsIgnoreCase(Dict.tradeState.item_USERPAYING.getItem())) {
- Map orderRaram = Maps.newHashMap();
- orderRaram.put("payStatus", Dict.payStatus.item_1.getItem());
- orderRaram.put("orderStatus", Dict.orderStatus.item_100.getItem());
- orderRaram.put("orderId", orderId);
- orderDao.updateOrderInfo(orderRaram);
- LOGGER.info(">>>>>>>>>>>>>>>>>>>>wxOrderByTransactionIdQueryUpdFail 根据支付单查询微信接口返回信息:state 【" + result.getTrade_state() +
- "】,des【" + result.getTrade_state_desc() + "】");
- } else if (result.getTrade_state().equalsIgnoreCase(Dict.tradeState.item_REVOKED.getItem())) {
- LOGGER.info(">>>>>>>>>>>>>>>>>>>>wxOrderByTransactionIdQueryUpdFail 根据支付单查询微信接口返回信息:state 【" + result.getTrade_state() +
- "】,des【" + result.getTrade_state_desc() + "】");
- return false;
- }
- } else {
- LOGGER.info(">>>>>>>>>>>>>>>>>>>>wxOrderQuery 微信查询接口返回失败信息:code 【" + result.getErr_code() +
- "】,des【" + result.getErr_code_des() + "】");
- }
- return false;
- } else {
- LOGGER.info(">>>>>>>>>>>>>>>>>>>>wxOrderQuery 微信查询接口调用失败: " + result.getReturn_msg());
- return false;
- }
- }
- @Override
- public OrderEntity queryObjectByOrderSn(String orderSn) {
- return orderDao.queryObjectByOrderSn(orderSn);
- }
- ExecutorService service = Executors.newSingleThreadExecutor();
- // 收银端退款的代码
- @Override
- @Transactional
- public synchronized R orderRefund(OrderEntity order, String sessionId, SysUserEntity user) throws Exception {
- OrderEntity orderInfo = order;
- if (null == orderInfo) {
- return R.error("订单不存在");
- }
- if (orderInfo.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_401.getItem()) ||
- orderInfo.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_402.getItem())) {
- return R.error("订单已退款");
- }
- if (orderInfo.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_0.getItem())) {
- return R.error("订单正在准备,请稍等!");
- }
- if (orderInfo.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_100.getItem())) {
- return R.error("订单尚未支付完成,无法进行退款!");
- }
- if (orderInfo.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_101.getItem())) {
- return R.error("订单尚未支付完成,无法进行退款!");
- }
- if (orderInfo.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_102.getItem())) {
- return R.error("订单尚未支付完成,无法进行退款!");
- }
- String payFlag = order.getPayFlag();
- String key = "kmall_order_refund_" + order.getOrderSn();
- if (JedisUtil.exists(key)) {
- return R.error("订单退款操作过快,请等待!");
- }
- JedisUtil.set(key, System.currentTimeMillis() + "", 3);
- if (orderInfo.getPayStatus() == Integer.parseInt(Dict.payStatus.item_3.getItem())) {
- return R.error("订单正在退款中,请勿重复退款");
- }
- CountDownLatch cdl = new CountDownLatch(1);
- service.submit(()-> {
- try {
- orderDao.updateOrderRefunding(order.getId());
- } finally {
- cdl.countDown();
- }
- });
- cdl.await();
- if (Dict.payFlag.item_weixin.getItem().equals(payFlag)) {
- Double totalActualPrice = orderDao.getTotalActualPrice(orderInfo.getMerchOrderSn());
- if (totalActualPrice == null) {
- totalActualPrice = 0d;
- }
- if (orderInfo.getOrderStatus() != Integer.parseInt(Dict.orderStatus.item_0.getItem())) {
- LOGGER.info("[微信退款开始--------orderRefund]"+order.getOrderSn());
- WechatRefundApiResult result = WechatUtil.wxRefund(orderInfo.getOrderSn(), totalActualPrice,
- orderInfo.getActualPrice().doubleValue());
- order.setPayStatus(Integer.parseInt(Dict.payStatus.item_5.getItem()));
- order.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_401.getItem()));
- //修改为退款成功
- orderDao.update(order);
- // 修改小票码
- PickUpCodeEntity pickUpCodeEntity = pickUpCodeService.queryObject(order.getOrderSn());
- pickUpCodeEntity.setPickUpCodeStatus("3");
- pickUpCodeService.update(pickUpCodeEntity);
- //还原库存,调用免税mall接口退款
- restoreInventoryMsMall(order);
- //新增退款记录
- OrderRefundEntity orderRefund = orderRefundLog(result.getRefund_id(),result.getOut_trade_no(),result.getRefund_fee(),order.getId(),user.getUserId(),order.getMerchOrderSn());
- orderRefundDao.save(orderRefund);
- }
- // 支付宝的退款代码
- } else if (Dict.payFlag.item_alipay.getItem().equals(payFlag)) {
- LOGGER.info("[支付宝退款开始--------orderRefund]"+order.getOrderSn());
- AliPayMicropayApiResult userRefund = AliPayUtil.aliTradeRefund(order.getOrderSn(), order.getActualPrice().toString(),
- "用户退款", order.getStoreId() + "");
- // 是否已退款校验
- try {
- String fundChange = userRefund.getFundChange();
- if ("N".equals(fundChange)) {
- return R.error("资金已退回,请勿重复退款!");
- }
- } catch (Exception e) {
- LOGGER.error("[支付宝退款校验出错]",e.getMessage());
- }
- LOGGER.info(userRefund.getSubMsg());
- order.setPayStatus(Integer.parseInt(Dict.payStatus.item_5.getItem()));
- order.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_401.getItem()));
- //修改为退款成功
- orderDao.update(order);
- // 修改小票码
- PickUpCodeEntity pickUpCodeEntity = pickUpCodeService.queryObject(order.getOrderSn());
- pickUpCodeEntity.setPickUpCodeStatus("3");
- pickUpCodeService.update(pickUpCodeEntity);
- //还原库存,调用免税mall接口退款
- restoreInventoryMsMall(order);
- //新增退款记录
- OrderRefundEntity orderRefund = orderRefundLog(userRefund.getTradeNo(),userRefund.getOutTradeNo(),userRefund.getRefundFee(),order.getId(),user.getUserId(),order.getMerchOrderSn());
- orderRefundDao.save(orderRefund);
- }
- return R.ok("退款成功");
- }
- /**
- * 新增退款记录
- * @param refundId
- * @param OutTradeNo
- * @param refundFee
- * @param orderId
- * @param userId
- * @param merchOrderSn
- * @return
- */
- private OrderRefundEntity orderRefundLog(String refundId,String OutTradeNo,String refundFee,Long orderId,Long userId,String merchOrderSn){
- OrderRefundEntity orderRefund = new OrderRefundEntity();
- orderRefund.setRefundId(refundId);
- orderRefund.setOutRefundNo(OutTradeNo);
- orderRefund.setRefundMoney(BigDecimal.valueOf(Long.valueOf(refundFee)).divide(Constant.ONE_HUNDRED));
- orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_2.getItem()));//退款处理中
- orderRefund.setModTime(new Date());
- orderRefund.setRefundTime(new Date());
- orderRefund.setOrderId(orderId.intValue());
- orderRefund.setUserId(userId.intValue());
- orderRefund.setRefundId(userId + "");
- orderRefund.setCreateTime(new Date());
- Integer sum = orderDao.queryObjectByMerchOrderSnHkMall(merchOrderSn);
- if (sum > 1) {//多条订单
- orderRefund.setRefundType(Integer.parseInt(Dict.RefundType.item_2.getItem()));//部分退款
- } else {
- orderRefund.setRefundType(Integer.parseInt(Dict.RefundType.item_1.getItem()));//用户全额退款
- }
- orderRefund.setRestore(1);
- return orderRefund;
- }
- /**
- * 海控订单退款
- * @param order
- */
- private void restoreInventoryMsMall(OrderEntity order) {
- Map<String, Object> map = new HashMap();
- SysUserEntity user = ShiroUtils.getUserEntity();
- map.put("orderId", order.getId());
- //mall_order_goodsd,订单明细
- List<OrderGoodsEntity> orderGoodsVoList = orderGoodsDao.queryListHkMall(map);
- for (OrderGoodsEntity orderGoodsEntity : orderGoodsVoList) {
- ProductStoreRelaEntity storeRelaEntity = productStoreRelaDao
- .queryByGoodsIdAndStoreIdHkMall(order.getStoreId().longValue(), orderGoodsEntity.getGoodsId().longValue());
- if (null == storeRelaEntity || null == storeRelaEntity.getSellVolume()) {
- storeRelaEntity.setSellVolume(0);
- }
- //销售量 - 商品数量
- BigDecimal sellVolume = new BigDecimal(storeRelaEntity.getSellVolume() - orderGoodsEntity.getNumber());//销售量
- if (sellVolume.compareTo(Constant.ZERO) < 0) {
- sellVolume = Constant.ZERO;
- }
- //还原门店库存
- if (null != storeRelaEntity.getStockNum()) {
- resetStoreGoodsStockMall(storeRelaEntity.getStockNum(), storeRelaEntity, orderGoodsEntity, sellVolume, user);
- }
- }
- //调用免税mall接口
- vmcShopMall(order);
- }
- /**
- *海控免税mall接口
- * @param order
- */
- private void vmcShopMall(OrderEntity order) {
- LOGGER.info("=======> [调用VMCShop接口开始发送退款订单数据]"+order.getOrderSn());
- String body = JacksonUtil.toJson(order.getOrderSn());
- String response = vmcShopTemplate.refundOrder(body);
- //解析响应数据
- LOGGER.info("=======> [发送退款订单数据成功,开始处理后续流程]"+response);
- //Map<String,String> res = JSON.parseObject(response,Map.class);
- saveVmcSend(order.getOrderSn(),VmcconnectUrlEnum.ORDERS_CANCEL_ORDER.getMethod(),body,response);
- LOGGER.info(order.getOrderSn()+"[发送退款订单数据]"+JSON.toJSONString(order));
- }
- @Transactional
- public void toBeRestoreInventory(OrderEntity order) {
- Map<String, Object> map = new HashMap();
- SysUserEntity user = ShiroUtils.getUserEntity();
- map.put("orderId", order.getId());
- List<OrderGoodsEntity> orderGoodsVoList = orderGoodsDao.queryList(map);
- for (OrderGoodsEntity orderGoodsEntity : orderGoodsVoList) {
- // 当前订单商品数量
- Integer restoreNumber = orderGoodsEntity.getNumber();
- ProductStoreRelaEntity storeRelaEntity = productStoreRelaDao
- .queryByGoodsIdAndStoreId(order.getStoreId().longValue(), orderGoodsEntity.getGoodsId().longValue());
- Integer toBeRestored = storeRelaEntity.getToBeRestored();
- if (toBeRestored == null) {
- toBeRestored = 0;
- }
- // 修改门店商品待退款的数量 = 当前订单商品数量 + 门店待退款数量
- storeRelaEntity.setToBeRestored(toBeRestored + restoreNumber);
- GoodsEntity goodsEntity = goodsDao.queryObject(orderGoodsEntity.getGoodsId());
- toBeRestored = goodsEntity.getToBeRestored();
- if (toBeRestored == null) {
- toBeRestored = 0;
- }
- goodsEntity.setToBeRestored(toBeRestored + restoreNumber);
- productStoreRelaDao.update(storeRelaEntity);
- goodsDao.update(goodsEntity);
- }
- }
- /**
- * 查询oms系统是否有该订单
- *
- * @param orderSn
- * @return
- */
- private boolean arrivedOms(String orderSn) {
- Map<String, String> sParaTemp = new TreeMap<String, String>();
- // sParaTemp.put("data","ZWCW2020122749351849");
- sParaTemp.put("data", orderSn);
- sParaTemp.put("merchId", omsMerchProperties.getMerchSn());
- String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
- sParaTemp.put("timestamp", timestamp);
- //生成要请求给oms秘钥
- // String sign = OmsSign.sign(sParaTemp,cus.getWaybill().get("secret-key"));
- LOGGER.info("md5混淆码参数:" + omsMerchProperties.getMd5Salt());
- String sign = OmsSign.sign(sParaTemp, omsMerchProperties.getMd5Salt());
- sParaTemp.put("sign", sign);
- //构建Request
- String url = omsMerchProperties.getQueryInveResponseUrl();
- Request request = com.kmall.admin.utils.oms.OkHttpUtils.buildRequest(url, JSON.toJSONString(sParaTemp));
- LOGGER.info("oms的请求报文:" + request);
- // 同步访问,返回结果字符串
- String responseString = null;
- try {
- responseString = com.kmall.admin.utils.oms.OkHttpUtils.post(request);
- } catch (Exception e) {
- e.printStackTrace();
- }
- LOGGER.info("oms的响应报文" + responseString);
- //解析响应数据
- Gson gson = new Gson();
- ResponseMessage result = gson.fromJson(responseString, ResponseMessage.class);
- if (result == null) {
- String info = "解析响应数据Result失败";
- LOGGER.error("--- {}", info);
- throw new RuntimeException(info);
- }
- if ("oms无该订单".equals(result.getMsg())) {
- return false;
- }
- return true;
- }
- private String wxRefund(OrderEntity orderInfo, Double totalActualPrice) {
- WechatRefundApiResult result = WechatUtil.wxRefund(orderInfo.getOrderSn().toString(), totalActualPrice,
- orderInfo.getActualPrice().doubleValue());
- if (result.getResult_code().equals(WechatUtil.WXTradeState.SUCCESS.getCode())) {
- refund(orderInfo, result);
- } else {
- OrderRefundEntity mallOrderRefund = orderRefundService.queryObjectByOrderId(orderInfo.getId());
- OrderRefundEntity orderRefund = new OrderRefundEntity();
- orderRefund.setRefundType(Integer.parseInt(Dict.RefundType.item_1.getItem()));
- orderRefund.setRefundMoney(BigDecimal.valueOf(orderInfo.getActualPrice().doubleValue()));
- orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_4.getItem()));
- SysUserEntity user = ShiroUtils.getUserEntity();
- orderRefund.setModerSn(user.getUsername());
- orderRefund.setModTime(new Date());
- // orderRefund.setOutRefundNo(result.getOut_refund_no());
- if (mallOrderRefund != null) {
- orderRefund.setId(mallOrderRefund.getId());
- orderRefundService.update(orderRefund);//退款记录
- }
- OrderExceptionRecordEntity mallOrderExceptionRecord = new OrderExceptionRecordEntity();
- mallOrderExceptionRecord.setOrderSn(orderInfo.getOrderSn());
- mallOrderExceptionRecord.setUserId(Integer.parseInt(orderInfo.getUserId() + ""));
- mallOrderExceptionRecord.setExceptionStatus(Dict.exceptionStatus.item_03.getItem());
- mallOrderExceptionRecord.setExceptionContent("退款失败" + result.getErr_code_des());
- mallOrderExceptionRecord.setCreateTime(new Date());
- orderExceptionRecordService.save(mallOrderExceptionRecord);
- return result.getErr_code_des();
- }
- return "";
- }
- @Override
- public int queryOffilineOrderTotal(Query query) {
- return orderDao.queryOffilineOrderTotal(query);
- }
- @Override
- public List<PurchaseSalesInStockDetail> purchaseSalesInStockDetailList(Query query) {
- return orderDao.purchaseSalesInStockDetailList(query);
- }
- @Override
- public int purchaseSalesInStockDetailTotal(Query query) {
- return orderDao.purchaseSalesInStockDetailTotal(query);
- }
- @Override
- public List<OrderEntity> queryExportOffilineOrderList(Map<String, Object> params) {
- List<OrderEntity> orderEntityList = orderDao.queryExportOffilineOrderList(params);
- // if (orderEntityList!=null && orderEntityList.size()>0){
- // for (OrderEntity orderEntity : orderEntityList) {
- // // 查询活动价
- // BigDecimal topicPrice = orderDao.queryTopicPriceByOrderSnAndSku(orderEntity.getOrderSn(),orderEntity.getSku());
- // orderEntity.setTopicPrice(topicPrice);
- // }
- // }
- return orderEntityList;
- }
- @Override
- public List<OrderEntity> queryMasterExportOffilineOrderList(Map<String, Object> params) {
- return orderDao.queryMasterExportOffilineOrderList(params);
- }
- @Override
- public List<OrderEntity> queryMasterExportList(Map<String, Object> params) {
- return orderDao.queryMasterExportList(params);
- }
- @Override
- public List<SystemFormatDto> queryExportSystemFormatList(Map<String, Object> params) {
- List<SystemFormatDto> systemFormatList = orderDao.queryExportSystemFormatList(params);
- return systemFormatList;
- }
- @Override
- public List<OrderEntity> queryLastDayOrder(String comparedDate) {
- Map<String, Object> map = new HashMap<>();
- //
- // DateFormat dateFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//格式化一下时间
- //
- // Date dNow = new Date(); //当前时间
- //
- // Date dBefore = new Date();
- //
- // Calendar calendar = Calendar.getInstance(); //得到日历
- //
- // calendar.setTime(dNow);//把当前时间赋给日历
- //
- // calendar.add(Calendar.DAY_OF_MONTH, -1); //设置为前一天
- //
- // dBefore = calendar.getTime(); //得到前一天的时间
- String defaultStartDate = comparedDate + " 00:00:00";
- String defaultEndDate = comparedDate + " 23:59:59";
- map.put("startTime", defaultStartDate);
- map.put("endTime", defaultEndDate);
- return orderDao.queryOffilineOrderList(map);
- }
- /**
- * 查询CW保税+新零售销售报表第一个sheet
- *
- * @param billDate
- * @param storeId
- * @return
- */
- @Override
- public ExportExcelDto querySumAmount(String billDate, String storeId) {
- ExportExcelDto exportExcelDto = new ExportExcelDto();
- ExportExcelDto totalAmount = orderDao.totalAmount(billDate, storeId);
- ExportExcelDto refundCurrentAmount = orderDao.refundCurrentAmount(billDate, storeId);
- ExportExcelDto refundPreviousAmount = orderDao.refundPreviousAmount(billDate, storeId);
- ExportExcelDto currentTax = orderDao.currentTax(billDate, storeId);
- ExportExcelDto refundPreviousTax = orderDao.refundPreviousTax(billDate, storeId);
- // 以下是直接从数据库中查出来的
- exportExcelDto.setTotalAmount(totalAmount.getTotalAmount()); // 总销售额
- exportExcelDto.setTotalCount(totalAmount.getTotalCount()); // 总销售数
- exportExcelDto.setRefundCurrentAmount(refundCurrentAmount.getRefundCurrentAmount()); // 当期退款额
- exportExcelDto.setRefundCurrentCount(refundCurrentAmount.getRefundCurrentCount()); // 当期退款数
- exportExcelDto.setRefundPreviousAmount(refundPreviousAmount.getRefundPreviousAmount()); // 退前期销售额
- exportExcelDto.setRefundPreviousCount(refundPreviousAmount.getRefundPreviousCount()); // 退前期销售数
- exportExcelDto.setCurrentTax(currentTax.getCurrentTax()); // 当前税额
- exportExcelDto.setPreviousTax(refundPreviousTax.getPreviousTax()); // 前期税额
- // 以下是通过计算的出来的
- // 销售净额
- exportExcelDto.setNetAmount(new BigDecimal(exportExcelDto.getTotalAmount()).subtract(new BigDecimal(exportExcelDto.getRefundPreviousAmount())).setScale(2, RoundingMode.HALF_UP).toString());
- // 总税额
- exportExcelDto.setTotalTax(new BigDecimal(exportExcelDto.getCurrentTax()).add(new BigDecimal(exportExcelDto.getPreviousTax())).setScale(2, RoundingMode.HALF_UP).toString());
- // 税前总额
- exportExcelDto.setPreTaxTotalAmount(new BigDecimal(exportExcelDto.getNetAmount()).subtract(new BigDecimal(exportExcelDto.getTotalTax())).setScale(2, RoundingMode.HALF_UP).toString());
- // 成功单数
- exportExcelDto.setSuccessNumber(new BigDecimal(exportExcelDto.getTotalCount()).subtract(new BigDecimal(exportExcelDto.getRefundPreviousCount())).setScale(2, RoundingMode.HALF_UP).toString());
- // 退款总额
- exportExcelDto.setRefundAmount(new BigDecimal(exportExcelDto.getRefundCurrentAmount()).add(new BigDecimal(exportExcelDto.getRefundPreviousAmount())).setScale(2, RoundingMode.HALF_UP).toString());
- // 退单单数
- exportExcelDto.setRefundCount(new BigDecimal(exportExcelDto.getRefundCurrentCount()).add(new BigDecimal(exportExcelDto.getRefundPreviousCount())).setScale(2, RoundingMode.HALF_UP).toString());
- return exportExcelDto;
- }
- @Override
- public Map<String, List<OrderEntity>> querySaleOrderList(String billDate, String storeId) {
- Map<String, List<OrderEntity>> result = new HashMap<>();
- // 查询当天所有订单
- List<OrderEntity> orderEntityList = orderDao.queryCurrentPreviousOrderList(billDate, storeId);
- result.put("current", orderEntityList);
- // 查询当天退前期订单
- List<OrderEntity> refundPreviousOrderList = orderDao.queryRefundPreviousOrderList(billDate, storeId);
- result.put("previous", refundPreviousOrderList);
- return result;
- }
- @Override
- public Map<String, List<TaxDetailDto>> queryTaxDetailList(String billDate, String storeId) {
- Map<String, List<TaxDetailDto>> result = new HashMap<>();
- // 查询当天所有订单税单
- List<TaxDetailDto> taxDetailList = orderDao.queryCurrentTaxDetailList(billDate, storeId);
- // 计算税前价,增值税,消费税
- BigDecimal discountRate = new BigDecimal(0.7);
- if (taxDetailList != null && taxDetailList.size() != 0) {
- for (TaxDetailDto taxDetailDto : taxDetailList) {
- // 获取实际支付价格
- String postTaxPrice = taxDetailDto.getPostTaxPrice();
- // 获取总税额
- String taxStr = taxDetailDto.getTax();
- // 税前金额
- BigDecimal tax = new BigDecimal(taxStr);
- BigDecimal pretaxPrice = new BigDecimal(postTaxPrice).subtract(tax).setScale(2, RoundingMode.HALF_UP);
- // 计算综合税率
- BigDecimal taxRate = tax.divide(pretaxPrice, 4, RoundingMode.HALF_UP);
- // 消费税率
- BigDecimal saleTaxRate = new BigDecimal(taxDetailDto.getSaleTaxRate()).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
- // 综合税率
- BigDecimal vatRate = new BigDecimal(taxDetailDto.getVatRate()).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
- // 消费税 = (明细商品总价 / (1-消费税税率)) * 消费税税率
- // 增值税 = (明细商品总价 + 消费税) * 增值税税率
- // 订单该商品总税费 = (商品消费税 + 商品增值税)* 0.7
- // 如果大于,要算消费税
- BigDecimal saleTax = new BigDecimal(0);
- BigDecimal vat = new BigDecimal(0);
- if (taxRate.compareTo(new BigDecimal("0.23")) > 0) {
- saleTax = pretaxPrice.divide(new BigDecimal(1).subtract(saleTaxRate), 2, RoundingMode.HALF_UP).multiply(saleTaxRate).
- setScale(2, RoundingMode.HALF_UP);
- vat = pretaxPrice.add(saleTax).multiply(vatRate).
- multiply(discountRate).setScale(2, RoundingMode.HALF_UP);
- saleTax = saleTax.multiply(discountRate).setScale(2, RoundingMode.HALF_UP);
- } else {
- // 不需要算消费税,增值税计算
- vat = pretaxPrice.multiply(vatRate).multiply(discountRate).setScale(2, RoundingMode.HALF_UP);
- }
- taxDetailDto.setSaleTax(saleTax.toString());
- taxDetailDto.setVat(vat.toString());
- }
- }
- result.put("current", taxDetailList);
- // 查询当天退前期订单税单
- List<TaxDetailDto> refundPrevioustaxDetailList = orderDao.queryRefundPreviousTaxDetailList(billDate, storeId);
- // 计算税前价,增值税,消费税
- if (refundPrevioustaxDetailList != null && refundPrevioustaxDetailList.size() != 0) {
- for (TaxDetailDto taxDetailDto : refundPrevioustaxDetailList) {
- // 获取实际支付价格
- String postTaxPrice = taxDetailDto.getPostTaxPrice();
- // 获取总税额
- String taxStr = taxDetailDto.getPreTax();
- // 税前金额
- BigDecimal tax = new BigDecimal(taxStr);
- BigDecimal pretaxPrice = new BigDecimal(postTaxPrice).subtract(tax).setScale(2, RoundingMode.HALF_UP);
- // 计算综合税率
- BigDecimal taxRate = tax.divide(pretaxPrice, 4, RoundingMode.HALF_UP);
- // 消费税率
- BigDecimal saleTaxRate = new BigDecimal(taxDetailDto.getPreSaleTax()).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
- // 综合税率
- BigDecimal vatRate = new BigDecimal(taxDetailDto.getPreVat()).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
- // 消费税 = (明细商品总价 / (1-消费税税率)) * 消费税税率
- // 增值税 = (明细商品总价 + 消费税) * 增值税税率
- // 订单该商品总税费 = (商品消费税 + 商品增值税)* 0.7
- // 如果大于,要算消费税
- BigDecimal saleTax = new BigDecimal(0);
- BigDecimal vat = new BigDecimal(0);
- if (taxRate.compareTo(new BigDecimal("0.23")) > 0) {
- saleTax = pretaxPrice.divide(new BigDecimal(1).subtract(saleTaxRate), 2, RoundingMode.HALF_UP).multiply(saleTaxRate).
- multiply(discountRate).setScale(2, RoundingMode.HALF_UP);
- vat = pretaxPrice.add(saleTax).multiply(vatRate).
- multiply(discountRate).setScale(2, RoundingMode.HALF_UP);
- } else {
- // 不需要算消费税,增值税计算
- vat = pretaxPrice.multiply(vatRate).multiply(discountRate).setScale(2, RoundingMode.HALF_UP);
- }
- taxDetailDto.setPreSaleTax(saleTax.compareTo(BigDecimal.ZERO) == 0 ? saleTax.toString() : "-" + saleTax.toString());
- taxDetailDto.setPreVat(vat.compareTo(BigDecimal.ZERO) == 0 ? vat.toString() : "-" + vat.toString());
- }
- }
- result.put("previous", refundPrevioustaxDetailList);
- return result;
- }
- @Override
- public List<String> queryInveResponse(String orderSn) throws IOException {
- Map<String, String> sParaTemp = new TreeMap<String, String>();
- sParaTemp.put("data", orderSn);
- sParaTemp.put("merchId", omsMerchProperties.getMerchSn());
- String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
- sParaTemp.put("timestamp", timestamp);
- //生成要请求给oms秘钥
- // String sign = OmsSign.sign(sParaTemp,cus.getWaybill().get("secret-key"));
- LOGGER.info("md5混淆码参数:" + omsMerchProperties.getMd5Salt());
- String sign = OmsSign.sign(sParaTemp, omsMerchProperties.getMd5Salt());
- sParaTemp.put("sign", sign);
- //构建Request
- String url = omsMerchProperties.getQueryInveResponseUrl();
- Request request = com.kmall.admin.utils.oms.OkHttpUtils.buildRequest(url, JSON.toJSONString(sParaTemp));
- LOGGER.info("oms的请求报文:" + request);
- // 同步访问,返回结果字符串
- String responseString = null;
- try {
- responseString = com.kmall.admin.utils.oms.OkHttpUtils.post(request);
- } catch (Exception e) {
- e.printStackTrace();
- throw e;
- }
- LOGGER.info("oms的响应报文" + responseString);
- //解析响应数据
- Gson gson = new Gson();
- ResponseMessage result = gson.fromJson(responseString, ResponseMessage.class);
- if (result == null) {
- String info = "解析响应数据Result失败";
- LOGGER.error("--- {}", info);
- throw new RuntimeException(info);
- }
- ResponseMessageData data = result.getData();
- List rows = data.getRows();
- List<String> resultMessage = new LinkedList<>();
- for (Object row : rows) {
- if (row instanceof ArrayList) {
- for (Object o : ((ArrayList<?>) row)) {
- if (o instanceof LinkedTreeMap) {
- String cusReturnInfo = (String) ((LinkedTreeMap<?, ?>) o).get("cusReturnInfo");
- resultMessage.add(cusReturnInfo);
- }
- }
- }
- }
- // cusReturnInfo -> [Code:2600;Desc:放行]
- return resultMessage;
- }
- /**
- * 查询所有状态为201的订单。且下单时间超过5分钟的订单
- *
- * @return
- */
- @Override
- public List<OrderEntity> queryAll201Order() {
- SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
- String date = format.format(new Date());
- return orderDao.queryAll201Order(date);
- }
- /**
- * 恢复kmall退单冻结的库存
- *
- * @param orderSn
- */
- @Override
- @Transactional
- public void toBeRestored(String orderSn) {
- // 查询该订单在库存是否已经释放过,避免重复恢复库存
- OrderEntity orderInfo = orderDao.queryObjectByOrderSn(orderSn);
- OrderRefundEntity orderRefundEntity = orderRefundService.queryObjectByOrderId(orderInfo.getId());
- if (orderRefundEntity == null) {
- LOGGER.error("该订单无退款记录,订单号{}", orderSn);
- throw new RuntimeException("该订单无退款记录,订单号:" + orderSn);
- }
- Integer restore = orderRefundEntity.getRestore();
- if (restore == 1) {
- LOGGER.error("该订单库存记录已恢复过,订单号{}", orderSn);
- throw new RuntimeException("该订单库存记录已恢复过,订单号:" + orderSn);
- }
- restoreInventory(orderInfo, "oms退单成功,恢复库存");
- orderRefundEntity.setRestore(1);
- orderRefundService.update(orderRefundEntity);
- }
- @Override
- public Ticket printMsgEwb(long id, String sessionId) {
- OrderEntity orderEntity = queryInfos(id);
- List<OrderGoodsEntity> orderGoodsEntityList = orderEntity.getOrderGoodsEntityList();
- // 获取门店
- StoreEntity storeEntity = storeDao.queryObject(orderEntity.getStoreId());
- // 获取清关信息
- OrderProcessRecordEntity orderProcessRecordEntity =
- orderProcessRecordDao.queryObjectByOrderSn(orderEntity.getOrderSn());
- // 小票头
- TicketHead head = new TicketHead();
- head.setTitle(storeEntity.getStoreName());
- // head.setMemberId(orderEntity.getUserName().toString());
- head.setOrderId(orderEntity.getOrderSn());
- head.setTradeTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss EEE").format(orderEntity.getPayTime()));
- // 商品信息
- Integer goodsTotal = 0; // 商品总个数
- BigDecimal total = Constant.ZERO; // 商品总计
- BigDecimal taxTotal = Constant.ZERO; //税费总计
- List<Goods> goodsList = new ArrayList<>();
- BigDecimal discountedPrice = Constant.ZERO; // 优惠金额
- for (OrderGoodsEntity orderGoods : orderGoodsEntityList) {
- goodsTotal += orderGoods.getNumber();
- total = total.add(orderGoods.getRetailPrice().multiply(new BigDecimal(orderGoods.getNumber())))
- .setScale(2, BigDecimal.ROUND_HALF_UP);
- discountedPrice = discountedPrice.add(orderGoods.getDiscountedPrice());
- GoodsEntity goodsEntity = goodsService.queryObject(orderGoods.getGoodsId());
- BigDecimal goodsTax = CalculateTax.calculateFinalTax(goodsEntity, orderGoods.getRetailPrice(), goodsService).setScale(3, RoundingMode.HALF_UP);
- goodsTax = goodsTax.multiply(new BigDecimal(orderGoods.getNumber())).setScale(2, RoundingMode.HALF_UP);
- taxTotal = taxTotal.add(goodsTax).setScale(2, RoundingMode.HALF_UP);
- Goods goods = new Goods(orderGoods.getGoodsName(),
- orderGoods.getRetailPrice().toString(), // 含税价
- // beforeTaxPrice.toString(),// 税前价
- goodsTax.toString(),
- orderGoods.getNumber().toString(),
- new BigDecimal(orderGoods.getNumber()).multiply(orderGoods.getRetailPrice()).setScale(2, RoundingMode.HALF_UP).toString(),
- orderGoods.getDiscountedPrice().toString());
- goodsList.add(goods);
- }
- // 收银信息
- CashInfo cashInfo = new CashInfo();
- cashInfo.setGoodsTotal(goodsTotal.toString());
- cashInfo.setTotal(total.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
- cashInfo.setTaxTotal(taxTotal.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
- cashInfo.setReceipts(orderEntity.getActualPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
- cashInfo.setOddChange(discountedPrice.toString());
- cashInfo.setCoupon(orderEntity.getCouponPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
- cashInfo.setFreight(
- new BigDecimal(orderEntity.getFreightPrice()).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
- if ("alipay".equals(orderEntity.getPayFlag())) {
- cashInfo.setPaymentMode("支付宝支付");
- } else {
- cashInfo.setPaymentMode("微信支付");
- }
- // 海关清单
- CusListing cusListing = new CusListing();
- cusListing.setOrderId(orderEntity.getOrderSn());
- if (!orderEntity.getOrderBizType().equalsIgnoreCase(Dict.orderBizType.item_11.getItem())) {
- cusListing.setWaybillId(orderProcessRecordEntity.getLogisticsNo());
- cusListing.setInvtNo(orderProcessRecordEntity.getInvtNo()==null?"":orderProcessRecordEntity.getInvtNo());
- cusListing.setConsignee(orderEntity.getConsignee());
- // 脱敏设置
- if (StringUtils.isNotEmpty(cusListing.getConsignee()) && cusListing.getConsignee().length() > 1) {
- cusListing.setConsignee(new StringBuilder(cusListing.getConsignee()).replace(1, 2, "*").toString());
- }
- cusListing.setConsigneeTel(orderEntity.getMobile());
- if (StringUtils.isNotEmpty(cusListing.getConsigneeTel())) {
- cusListing.setConsigneeTel(new StringBuilder(cusListing.getConsigneeTel()).replace(3, 7, "****").toString());
- }
- }
- cusListing.setOriginAddress(PrintTicketPropertiesBuilder.instance().getAddress());
- cusListing.setDeliveryAddress(storeEntity.getStoreAddress());
- // 尝试在取货码表中查询数据,如果有的话就改变状态
- // String orderSn = orderEntity.getOrderSn();
- // PickUpCodeEntity pickUpCodeEntity = pickUpCodeService.queryObject(orderSn);
- // if (pickUpCodeEntity != null) {
- // pickUpCodeEntity.setPickUpCodeStatus("0");
- // pickUpCodeService.update(pickUpCodeEntity);
- //
- // }
- TicketMailInfo mailInfo = new TicketMailInfo();
- String exprNo = orderProcessRecordEntity.getLogisticsNo();
- if (StringUtils.isNullOrEmpty(exprNo)) {
- throw new RRException("快递面单为空,请联系客服");
- }
- //图片地址
- mailInfo.setStoreImgUrl(storeEntity.getStoreImgUrl()==null?"/statics/img/cw_qrcode.png":storeEntity.getStoreImgUrl().trim());
- mailInfo.setExprNo(exprNo);
- String logoUrl = "/statics/img/yto_logo.jpg";
- Map<String, String> logoMap = new HashMap<>();
- logoMap.put("yto", "/statics/img/yto_logo.jpg");
- logoMap.put("best", "/statics/img/bestex_logo3.png");
- if (StringUtils.isNotEmpty(orderEntity.getShippingCode()) && logoMap.containsKey(orderEntity.getShippingCode())) {
- logoUrl = logoMap.get(orderEntity.getShippingCode());
- }
- mailInfo.setExprLogoUrl(logoUrl);
- byte[] barCode128 = BarcodeUtil.generateBarCode128(exprNo, 6.0D, null, true, false);
- String exprNoBase64Img = new String(Base64.getEncoder().encode(barCode128));
- mailInfo.setShopTel(storeEntity.getTelephoneNumber()==null?"0752-2688660":storeEntity.getTelephoneNumber().trim());
- // 发货人
- mailInfo.setSenderTel("0752-26886602");
- mailInfo.setSenderName("CW澳洲大药房");
- mailInfo.setSenderProvince("广东省");
- mailInfo.setSenderCity("深圳市");
- mailInfo.setSenderDistrict("南山区");
- mailInfo.setSenderAddress("前海综合保税区W104");
- // 收货人
- mailInfo.setConsigneeMob(new StringBuilder(orderEntity.getMobile()).replace(3, 7, "****").toString());
- mailInfo.setConsigneeName(new StringBuilder(orderEntity.getConsignee()).replace(1, 2, "*").toString());
- mailInfo.setConsigneeProvince(orderEntity.getProvince());
- mailInfo.setConsigneeCity(orderEntity.getCity());
- mailInfo.setConsigneeDistrict(orderEntity.getDistrict());
- mailInfo.setConsigneeAddress(orderEntity.getAddress());
- mailInfo.setExprNoBase64Img(exprNoBase64Img);
- return TicketPrintUtil.print(head, goodsList, cashInfo, cusListing, mailInfo);
- }
- /**
- * 计算优惠价格,活动价格
- *
- * @param calculateOrderDiscountPriceVo 请求参数
- * @return 商品集合
- */
- @Override
- public CalculateOrderDiscountPriceResponseVO calculateOrderDiscountPrice(CalculateOrderDiscountPriceVO calculateOrderDiscountPriceVo) {
- if (Objects.isNull(calculateOrderDiscountPriceVo)) {
- LOGGER.error("计算活动优惠价格,请求参数为null!");
- throw new ServiceException("计算活动优惠价格,请求参数为null!");
- }
- CalculateOrderDiscountPriceResponseVO calculateOrderDiscountPriceResponseVO = new CalculateOrderDiscountPriceResponseVO();
- String storeId = calculateOrderDiscountPriceVo.getStoreId();
- String memberCode = calculateOrderDiscountPriceVo.getMemberCode();
- List<GoodsDetailsDto> goodsDetailsDtos = calculateOrderDiscountPriceVo.getGoodsList();
- BigDecimal orderTotalPrice = BigDecimal.ZERO;
- List<QueryGoodsVO> goodsVos = new ArrayList<>();
- for (GoodsDetailsDto good : goodsDetailsDtos) {
- QueryGoodsVO queryGoodsVo = new QueryGoodsVO();
- BeanUtils.copyProperties(good, queryGoodsVo);
- queryGoodsVo.setSku(good.getGoodsSn());
- queryGoodsVo.setStoreId(Integer.parseInt(storeId));
- orderTotalPrice = orderTotalPrice.add(good.getActualPaymentAmount());
- goodsVos.add(queryGoodsVo);
- }
- calculateOrderDiscountPriceResponseVO.setOrderTotalPrice(orderTotalPrice);
- calculateOrderDiscountPriceResponseVO.setGoodsDetailsDtos(goodsDetailsDtos);
- // 查询商品表
- List<GoodsEntity> goodsEntities = goodsService.queryGoodsStockByQueryGoodsVoList(goodsVos);
- /*
- * 2.查询当前时间,该门店是否有活动,如果有活动,查询开启了哪些营销方式
- * 参数: 当前时间 门店id
- */
- List<MkActivitiesEntity> mkActivitiesEntityList = mkActivitiesService.queryByNow(storeId, DateUtils.format(new Date(), "yyyy-MM-dd"));
- // 活动优先级判定,特价>打折>满减/满赠>优惠券>积分抵扣;
- // List<Constants.ActivityTopicEnum> activityTopicEnums = Arrays.asList(Constants.ActivityTopicEnum.values());
- // for (MkActivitiesEntity mkActivitiesEntity : mkActivitiesEntityList) {
- // for (Constants.ActivityTopicEnum activityTopicEnum : activityTopicEnums) {
- // if (activityTopicEnum.get) {
- //
- // }
- // }
- // }
- /*
- * 活动相关规则:
- * 1. 优先优惠券再去计算积分
- * 2. 满赠的赠品商品在推送定时时零售价为0
- * 3. 任何活动都优先于积分计算
- * 4. 活动之间具有互斥性
- */
- if (CollectionUtils.isEmpty(mkActivitiesEntityList) && org.springframework.util.StringUtils.isEmpty(memberCode)) {
- LOGGER.info("门店【{}】,在当前时间无相关活动信息!", storeId);
- for (GoodsDetailsDto goodsDetailsDto : goodsDetailsDtos) {
- GoodsEntity goodsEntity = new GoodsEntity();
- BeanUtils.copyProperties(goodsDetailsDto, goodsEntity);
- goodsEntity.setGoodsRate(new BigDecimal(goodsDetailsDto.getGoodsRate()));
- // 无活动情况,实际支付价 = 零售价
- BigDecimal tax = CalculateTax.calculateFinalTax(goodsEntity , goodsEntity.getRetailPrice(), goodsService).setScale(3,RoundingMode.HALF_UP);
- // 预估税
- goodsDetailsDto.setGoodstaxes(String.valueOf(tax.multiply(new BigDecimal(goodsDetailsDto.getSellVolume()))));
- }
- calculateOrderDiscountPriceResponseVO.setGoodsDetailsDtos(goodsDetailsDtos);
- return calculateOrderDiscountPriceResponseVO;
- }
- List<Integer> brandIdList = goodsEntities.stream().map(GoodsEntity::getBrandId).collect(Collectors.toList());
- List<Integer> categoryIdList = goodsEntities.stream().map(GoodsEntity::getCategoryId).collect(Collectors.toList());
- // 活动互斥标识
- AtomicBoolean activityFlag = new AtomicBoolean(true);
- // 判断活动类型并排序,再确定购物栏中商品是否满足活动条件
- mkActivitiesEntityList.stream().sorted().forEach(mkActivitiesEntity -> {
- String mkaStoreId = mkActivitiesEntity.getMkaStoreId();
- Long mkaId = mkActivitiesEntity.getMkaId();
- String mkaTopic = mkActivitiesEntity.getMkaTopic();
- if (org.springframework.util.StringUtils.isEmpty(mkaTopic)) {
- LOGGER.error("活动主题为空!请检查活动设置!");
- throw new ServiceException("价活动主题为空!请检查活动设置!");
- }
- Constants.ActivityTopicEnum activityTopicEnum = Constants.ActivityTopicEnum.valueOf(mkaTopic.toUpperCase());
- // 活动之间的优先级:特价>打折>满减/满赠>优惠券>积分抵扣
- if (activityTopicEnum == Constants.ActivityTopicEnum.LSCX && activityFlag.get()) {
- // 判断商品是否符合限时特价活动要求
- List<MkActivitiesPromotionEntity> mkActivitiesPromotionEntities = mkActivitiesPromotionService.queryListByMkaIdAndStoreId(mkaId.intValue(), storeId);
- if (CollectionUtils.isEmpty(mkActivitiesPromotionEntities)) {
- LOGGER.error("查询临时促销活动信息结果为空!mka_id:{}, store_id:{}", mkaId, storeId);
- }
- // 限时特价,直接替换实际支付价即可,并且拿特价计算税款
- mkActivitiesPromotionEntities.forEach(mkActivitiesPromotionEntity -> {
- String entityBarcode = mkActivitiesPromotionEntity.getBarcode();
- String entityGoodsSn = mkActivitiesPromotionEntity.getGoodsSn();
- BigDecimal activityPrice = mkActivitiesPromotionEntity.getActivityPrice();
- String shopSn = mkActivitiesPromotionEntity.getShopSn();
- goodsEntities.forEach(goodsEntity -> {
- String sku = goodsEntity.getSku();
- String prodBarcode = goodsEntity.getProdBarcode();
- String storeId2 = String.valueOf(goodsEntity.getStoreId());
- BigDecimal retailPrice = goodsEntity.getRetailPrice();
- if (entityBarcode.equals(prodBarcode) && entityGoodsSn.equals(sku) && shopSn.equals(storeId2)) {
- GoodsDetailsDto goodsDetailsDto = new GoodsDetailsDto();
- BigDecimal tax = CalculateTax.calculateFinalTax(goodsEntity, activityPrice, goodsService).setScale(3, RoundingMode.HALF_UP);
- BeanUtils.copyProperties(goodsDetailsDto, goodsEntity);
- goodsDetailsDto.setActualPaymentAmount(activityPrice);
- goodsDetailsDto.setGoodstaxes(String.valueOf(tax.multiply(new BigDecimal(goodsDetailsDto.getSellVolume()))));
- goodsDetailsDto.setActivity("限时促销");
- goodsDetailsDto.setDiscountedPrice(retailPrice.subtract(activityPrice));
- goodsDetailsDtos.add(goodsDetailsDto);
- activityFlag.set(false);
- }
- });
- });
- } else if (activityTopicEnum == Constants.ActivityTopicEnum.MZ && activityFlag.get()) {
- // 判断商品是否符合满赠活动要求
- MkActivitiesFullGiftEntity mkActivitiesFullGiftEntity = mkActivitiesFullGiftService.queryObjectByMkaIdAndStoreId(mkaId.intValue(), storeId);
- if (Objects.isNull(mkActivitiesFullGiftEntity)) {
- LOGGER.error("查询满赠活动信息结果为空!mka_id:{}, store_id:{}", mkaId, storeId);
- } else {
- Long brandId = mkActivitiesFullGiftEntity.getBrandId();
- Long categoryId = mkActivitiesFullGiftEntity.getCategoryId();
- Constants.ActivityType fullGiftActivityType = Constants.ActivityType.valueOf(mkActivitiesFullGiftEntity.getFullGiftType());
- switch (fullGiftActivityType) {
- case BRAND:
- if (Objects.isNull(brandId)) {
- LOGGER.error("满赠活动品牌编号为空,计算失败!请检查活动设置!活动ID:{}", mkActivitiesFullGiftEntity.getMkaId());
- throw new ServiceException(String.format("满赠活动品牌编号为空,计算失败!请检查活动设置!活动ID:%s", mkActivitiesFullGiftEntity.getMkaId()));
- }
- if (brandIdList.contains(brandId.intValue())) {
- // 活动包含该商品品牌,此次订单该品牌商品
- List<GoodsEntity> goodsEntityList = goodsEntities.stream().filter(goodsEntity -> brandId.intValue() == goodsEntity.getBrandId()).collect(Collectors.toList());
- AtomicReference<BigDecimal> brandTotalPrice = new AtomicReference<>(BigDecimal.ZERO);
- goodsEntityList.forEach(goodsEntity -> {
- brandTotalPrice.set(brandTotalPrice.get().add(goodsEntity.getRetailPrice()));
- });
- if (brandTotalPrice.get().compareTo(mkActivitiesFullGiftEntity.getQualifiedAmount()) >= 0) {
- // 满足满赠条件
- String giftGoodsSn = mkActivitiesFullGiftEntity.getGiftGoodsSn();
- String giftBarcode = mkActivitiesFullGiftEntity.getGiftBarcode();
- GoodsEntity goodsEntity = goodsService.queryGoodsStockByBarcodeAndStoreIdAndSku(giftBarcode, Integer.parseInt(mkaStoreId), giftGoodsSn);
- GoodsDetailsDto goodsDetailsDto = new GoodsDetailsDto();
- BeanUtils.copyProperties(goodsEntity, goodsDetailsDto);
- // 除了限时促销(需要向海关备案),其它活动都拿海关备案价来算税款
- BigDecimal tax = CalculateTax.calculateFinalTax(goodsEntity, goodsEntity.getRetailPrice(), goodsService).setScale(3, RoundingMode.HALF_UP);
- goodsDetailsDto.setGoodstaxes(String.valueOf(tax.multiply(new BigDecimal(goodsDetailsDto.getSellVolume()))));
- goodsDetailsDto.setActualPaymentAmount(BigDecimal.ZERO);
- goodsDetailsDto.setActivity("满赠商品");
- goodsDetailsDto.setGiftNumber(mkActivitiesFullGiftEntity.getGiftNumber());
- goodsDetailsDto.setDiscountedPrice(goodsEntity.getRetailPrice());
- // 添加进商品详情列表
- goodsDetailsDtos.add(goodsDetailsDto);
- activityFlag.set(false);
- }
- }
- break;
- case CATEGORY:
- if (Objects.isNull(categoryId)) {
- LOGGER.error("满赠活动分类编号为空,计算失败!请检查活动设置!活动ID:{}", mkActivitiesFullGiftEntity.getMkaId());
- throw new ServiceException(String.format("满赠活动分类编号为空,计算失败!请检查活动设置!活动ID:%s", mkActivitiesFullGiftEntity.getMkaId()));
- }
- if (categoryIdList.contains(categoryId.intValue())) {
- // 活动包含该商品分类
- List<GoodsEntity> goodsEntityList = goodsEntities.stream().filter(goodsEntity -> brandId.equals(mkActivitiesFullGiftEntity.getCategoryId())).collect(Collectors.toList());
- AtomicReference<BigDecimal> categoryTotalPrice = new AtomicReference<>(BigDecimal.ZERO);
- goodsEntityList.forEach(goodsEntity -> {
- categoryTotalPrice.set(categoryTotalPrice.get().add(goodsEntity.getRetailPrice()));
- });
- if (categoryTotalPrice.get().compareTo(mkActivitiesFullGiftEntity.getQualifiedAmount()) >= 0) {
- // 满足满赠条件
- String giftGoodsSn = mkActivitiesFullGiftEntity.getGiftGoodsSn();
- String giftBarcode = mkActivitiesFullGiftEntity.getGiftBarcode();
- GoodsEntity goodsEntity = goodsService.queryGoodsStockByBarcodeAndStoreIdAndSku(giftBarcode, Integer.parseInt(mkaStoreId), giftGoodsSn);
- GoodsDetailsDto goodsDetailsDto = new GoodsDetailsDto();
- BeanUtils.copyProperties(goodsEntity, goodsDetailsDto);
- // 除了限时促销(需要向海关备案),其它活动都拿海关备案价来算税款
- BigDecimal tax = CalculateTax.calculateFinalTax(goodsEntity, goodsEntity.getRetailPrice(), goodsService).setScale(3, RoundingMode.HALF_UP);
- goodsDetailsDto.setGoodstaxes(String.valueOf(tax.multiply(new BigDecimal(goodsDetailsDto.getSellVolume()))));
- goodsDetailsDto.setActualPaymentAmount(BigDecimal.ZERO);
- goodsDetailsDto.setActivity("满赠商品");
- goodsDetailsDto.setGiftNumber(mkActivitiesFullGiftEntity.getGiftNumber());
- goodsDetailsDto.setDiscountedPrice(goodsEntity.getRetailPrice());
- // 添加进商品详情列表
- goodsDetailsDtos.add(goodsDetailsDto);
- activityFlag.set(false);
- }
- }
- break;
- default:
- LOGGER.error("未知满赠类型【{},{}】!请联系管理员!", fullGiftActivityType.getActivityType(), fullGiftActivityType.getActivityTypeCode());
- throw new ServiceException(String.format("未知满赠类型【%s,%s】!请联系管理员!", fullGiftActivityType.getActivityType(), fullGiftActivityType.getActivityTypeCode()));
- }
- }
- } else if (activityTopicEnum == Constants.ActivityTopicEnum.YHQ && activityFlag.get()) {
- // 判断商品是否符合优惠券活动要求
- List<MkActivitiesCouponEntity> mkActivitiesCouponEntities = mkActivitiesCouponService.queryListByMkaIdAndStoreId(mkaId, storeId);
- if (CollectionUtils.isEmpty(mkActivitiesCouponEntities)) {
- LOGGER.error("查询优惠券活动信息结果为空!活动ID:{}, 门店编号:{}", mkaId, storeId);
- } else {
- MkActivitiesCouponEntity mkActivitiesCouponEntity = mkActivitiesCouponEntities.get(0);
- Integer couponEntityBrandId = mkActivitiesCouponEntity.getBrandId();
- Integer couponEntityCategoryId = mkActivitiesCouponEntity.getCategoryId();
- String shopSn = mkActivitiesCouponEntity.getShopSn();
- if (org.springframework.util.StringUtils.isEmpty(shopSn)) {
- LOGGER.error("优惠券活动门店编号为空,计算失败!请检查活动设置!活动ID:{}", mkActivitiesCouponEntity.getMkaId());
- throw new ServiceException(String.format("优惠券活动门店编号为空,计算失败!请检查活动设置!活动ID:%s", mkActivitiesCouponEntity.getMkaId()));
- }
- Integer couponEntityStoreId = Integer.parseInt(shopSn);
- BigDecimal couponPrice = mkActivitiesCouponEntity.getCouponPrice();
- Constants.ActivityType couponActivityType = Constants.ActivityType.customValueOf(mkActivitiesCouponEntity.getActivityType());
- if (Objects.isNull(couponActivityType)) {
- LOGGER.error("错误的优惠券优惠类型:【{}】,请检查活动设置!活动ID:{}", mkActivitiesCouponEntity.getActivityType(), mkActivitiesCouponEntity.getMkaId());
- throw new ServiceException(String.format("错误的优惠券优惠类型:【%s】,请检查活动设置!活动ID:%s", mkActivitiesCouponEntity.getActivityType(), mkActivitiesCouponEntity.getMkaId()));
- }
- switch (couponActivityType) {
- case BRAND:
- if (Objects.isNull(couponEntityBrandId)) {
- LOGGER.error("优惠券活动品牌编号为空,计算失败!请检查活动设置!活动ID:{}", mkActivitiesCouponEntity.getMkaId());
- throw new ServiceException(String.format("优惠券活动品牌编号为空,计算失败!请检查活动设置!活动ID:%s", mkActivitiesCouponEntity.getMkaId()));
- }
- goodsEntities.forEach(goodsEntity -> {
- if (couponEntityBrandId.equals(goodsEntity.getBrandId())) {
- BigDecimal retailPrice = goodsEntity.getRetailPrice();
- String sku = goodsEntity.getSku();
- String prodBarcode = goodsEntity.getProdBarcode();
- if (couponPrice.compareTo(retailPrice) <= 0) {
- LOGGER.error("优惠券优惠金额【{}】大于或等于商品【条码:{},sku:{}】的零售价【{}】,请检查优惠券金额设置!", couponPrice, prodBarcode, sku, retailPrice);
- throw new ServiceException(String.format("优惠券优惠金额【%s】大于或等于商品【条码:%s,sku:%s】的零售价【%s】,请检查优惠券金额设置!", couponPrice, prodBarcode, sku, retailPrice));
- }
- BigDecimal discountAfterPrice = retailPrice.subtract(couponPrice);
- GoodsDetailsDto goodsDetailsDto = new GoodsDetailsDto();
- BeanUtils.copyProperties(goodsEntity, goodsDetailsDto);
- // 除了限时促销(需要向海关备案),其它活动都拿海关备案价来算税款
- BigDecimal tax = CalculateTax.calculateFinalTax(goodsEntity, goodsEntity.getRetailPrice(), goodsService).setScale(3, RoundingMode.HALF_UP);
- goodsDetailsDto.setActualPaymentAmount(discountAfterPrice);
- goodsDetailsDto.setGoodstaxes(String.valueOf(tax.multiply(new BigDecimal(goodsDetailsDto.getSellVolume()))));
- goodsDetailsDto.setActivity("优惠券活动");
- goodsDetailsDto.setDiscountedPrice(retailPrice.subtract(discountAfterPrice));
- goodsDetailsDtos.add(goodsDetailsDto);
- activityFlag.set(false);
- }
- });
- break;
- case CATEGORY:
- if (Objects.isNull(couponEntityCategoryId)) {
- LOGGER.error("优惠券活动分类编号为空,计算失败!请检查活动设置!活动ID:{}", mkActivitiesCouponEntity.getMkaId());
- throw new ServiceException(String.format("优惠券活动分类编号为空,计算失败!请检查活动设置!活动ID:%s", mkActivitiesCouponEntity.getMkaId()));
- }
- goodsEntities.forEach(goodsEntity -> {
- if (couponEntityCategoryId.equals(goodsEntity.getCategoryId())) {
- BigDecimal retailPrice = goodsEntity.getRetailPrice();
- String sku = goodsEntity.getSku();
- String prodBarcode = goodsEntity.getProdBarcode();
- if (couponPrice.compareTo(retailPrice) <= 0) {
- LOGGER.error("优惠券优惠金额【{}】大于或等于商品【条码:{},sku:{}】的零售价【{}】,请检查优惠券金额设置!", couponPrice, prodBarcode, sku, retailPrice);
- throw new ServiceException(String.format("优惠券优惠金额【%s】大于或等于商品【条码:%s,sku:%s】的零售价【%s】,请检查优惠券金额设置!", couponPrice, prodBarcode, sku, retailPrice));
- }
- BigDecimal discountAfterPrice = retailPrice.subtract(couponPrice);
- GoodsDetailsDto goodsDetailsDto = new GoodsDetailsDto();
- BeanUtils.copyProperties(goodsEntity, goodsDetailsDto);
- // 除了限时促销(需要向海关备案),其它活动都拿海关备案价来算税款
- BigDecimal tax = CalculateTax.calculateFinalTax(goodsEntity, goodsEntity.getRetailPrice(), goodsService).setScale(3, RoundingMode.HALF_UP);
- goodsDetailsDto.setActualPaymentAmount(discountAfterPrice);
- goodsDetailsDto.setGoodstaxes(String.valueOf(tax.multiply(new BigDecimal(goodsDetailsDto.getSellVolume()))));
- goodsDetailsDto.setActivity("优惠券活动");
- goodsDetailsDto.setDiscountedPrice(retailPrice.subtract(discountAfterPrice));
- goodsDetailsDtos.add(goodsDetailsDto);
- activityFlag.set(false);
- }
- });
- break;
- case PRODUCT:
- mkActivitiesCouponEntities.forEach(mkActivitiesCouponEntity1 -> {
- // 单个商品优惠券,有多条记录
- String activityProductBarcode = mkActivitiesCouponEntity1.getBarcode();
- String activitySku = mkActivitiesCouponEntity1.getGoodsSn();
- goodsEntities.forEach(goodsEntity -> {
- String sku = goodsEntity.getSku();
- String prodBarcode = goodsEntity.getProdBarcode();
- // 条码、sku、门店都需一致
- if (activitySku.equals(sku) && activityProductBarcode.equals(prodBarcode) && couponEntityStoreId.equals(goodsEntity.getStoreId())) {
- BigDecimal retailPrice = goodsEntity.getRetailPrice();
- if (couponPrice.compareTo(retailPrice) <= 0) {
- LOGGER.error("优惠券优惠金额【{}】大于或等于商品【条码:{},sku:{}】的零售价【{}】,请检查优惠券金额设置!", couponPrice, prodBarcode, sku, retailPrice);
- throw new ServiceException(String.format("优惠券优惠金额【%s】大于或等于商品【条码:%s,sku:%s】的零售价【%s】,请检查优惠券金额设置!", couponPrice, prodBarcode, sku, retailPrice));
- }
- BigDecimal discountAfterPrice = retailPrice.subtract(couponPrice);
- GoodsDetailsDto goodsDetailsDto = new GoodsDetailsDto();
- BeanUtils.copyProperties(goodsEntity, goodsDetailsDto);
- // 除了限时促销(需要向海关备案),其它活动都拿海关备案价来算税款
- BigDecimal tax = CalculateTax.calculateFinalTax(goodsEntity, goodsEntity.getRetailPrice(), goodsService).setScale(3, RoundingMode.HALF_UP);
- goodsDetailsDto.setActualPaymentAmount(discountAfterPrice);
- goodsDetailsDto.setGoodstaxes(String.valueOf(tax.multiply(new BigDecimal(goodsDetailsDto.getSellVolume()))));
- goodsDetailsDto.setActivity("优惠券活动");
- goodsDetailsDto.setDiscountedPrice(retailPrice.subtract(discountAfterPrice));
- goodsDetailsDtos.add(goodsDetailsDto);
- activityFlag.set(false);
- }
- });
- });
- break;
- default:
- LOGGER.error("未知的优惠券活动分类类型:【{},{}】,请联系管理员!", activityTopicEnum.getTopicCode(), activityTopicEnum.getTopicName());
- throw new ServiceException(String.format("未知的优惠券活动分类类型:【%s,%s】,请联系管理员!", activityTopicEnum.getTopicCode(), activityTopicEnum.getTopicName()));
- }
- }
- } else {
- LOGGER.error("未知的活动类型:【{},{}】,请检查活动设置!!", activityTopicEnum.getTopicCode(), activityTopicEnum.getTopicName());
- throw new ServiceException(String.format("未知的活动类型:【%s,%s】,请检查活动设置!!", activityTopicEnum.getTopicCode(), activityTopicEnum.getTopicName()));
- }
- });
- // 计算完活动优惠后,计算积分抵扣。(活动与积分抵扣不互斥)
- if (!org.springframework.util.StringUtils.isEmpty(memberCode)) {
- String memberInfoByCodeResponseJson;
- Response<Object> response;
- try {
- // 查询会员信息
- memberInfoByCodeResponseJson = haiKongMemberTemplate.getMemberInfoByPhone("{\"phone\":" + memberCode + "}");
- response = JacksonUtil.fromListJson(memberInfoByCodeResponseJson, new TypeReference<Response<Object>>() {
- });
- if (Objects.isNull(response) || Objects.nonNull(response.getErrorCode())) {
- LOGGER.error("请求会员系统出现异常!error:{}", memberInfoByCodeResponseJson);
- throw new ServiceException(String.format("请求会员系统出现异常!会员码:%s,error:%s", memberCode, memberInfoByCodeResponseJson));
- }
- } catch (Exception e) {
- LOGGER.error("请求会员系统失败或处理响应失败!", e);
- throw new ServiceException(e);
- }
- BigDecimal afterDiscountPrice;
- if (response.getSuccess()) {
- MemberInfoDTO memberInfoDTO = JacksonUtil.fromStringJson(JacksonUtil.toJson(response.getData()), MemberInfoDTO.class);
- assert memberInfoDTO != null : String.format("会员码:【%s】会员信息错误!%s", memberCode, JacksonUtil.toJson(response));
- Integer score = memberInfoDTO.getScore();
- if (Objects.nonNull(score) && score > 0) {
- // 有积分
- afterDiscountPrice = calculatePreferentialPrice(orderTotalPrice, score, storeId, memberCode);
- LOGGER.info("会员【{}】,当前积分:{},积分抵扣后的订单金额:{},积分抵扣前的订单金额:{}", memberCode, score, afterDiscountPrice, orderTotalPrice);
- calculateOrderDiscountPriceResponseVO.setOrderTotalPrice(afterDiscountPrice);
- calculateOrderDiscountPriceResponseVO.setGoodsDetailsDtos(goodsDetailsDtos);
- // 订单完成后再添加积分消费记录,以及同步积分信息
- return calculateOrderDiscountPriceResponseVO;
- } else {
- LOGGER.error("会员【{}】积分为0,积分抵扣失败!", memberCode);
- throw new ServiceException(String.format("会员【%s】积分为0,积分抵扣失败!", memberCode));
- }
- } else {
- LOGGER.error("查询会员信息失败!响应结果:{}", memberInfoByCodeResponseJson);
- throw new ServiceException(String.format("会员码:%s,错误码:%s,错误信息:%s", memberCode, response.getErrorCode(), response.getErrorMessage()));
- }
- }
- calculateOrderDiscountPriceResponseVO.setGoodsDetailsDtos(goodsDetailsDtos);
- orderTotalPrice = BigDecimal.ZERO;
- for (GoodsDetailsDto goodsDetailsDto : goodsDetailsDtos) {
- orderTotalPrice = orderTotalPrice.add(goodsDetailsDto.getActualPaymentAmount());
- }
- calculateOrderDiscountPriceResponseVO.setOrderTotalPrice(orderTotalPrice);
- return calculateOrderDiscountPriceResponseVO;
- }
- /**
- * 计算积分抵扣后的订单总金额
- * @param orderTotalPrice 订单商品详情
- * @param score 积分
- * @param storeId 门店id
- * @param memberCode 会员码
- * @return 积分抵扣后的订单总金额
- */
- private BigDecimal calculatePreferentialPrice(BigDecimal orderTotalPrice, Integer score, String storeId, String memberCode) {
- // 1. 判断是否有积分,是否需要计算积分抵扣后的价格
- AtomicBoolean isCalculateScorePrice = new AtomicBoolean(false);
- if (Objects.nonNull(score) && score > 0) {
- isCalculateScorePrice.set(true);
- }
- // 2. 计算积分抵扣后的总价格
- if (isCalculateScorePrice.get()) {
- // 3-1. 计算总价的50%,百分比可以进行设置,算出整数(向下取整)
- BigDecimal halfPrice = orderTotalPrice.multiply(new BigDecimal("0.5")).setScale(0, BigDecimal.ROUND_FLOOR);
- Integer scoreLimit = haiKongProperties.getMemberScoreLimit();
- if (score < scoreLimit) {
- LOGGER.warn("用户【{}】的积分数量为:{},最低需要30积分才能抵扣!", memberCode, score);
- return orderTotalPrice;
- } else {
- // 3-2. 计算出积分能抵扣的价格
- int scoreMayDeductionPrice = (int) (score / scoreLimit);
- BigDecimal scoreMayDeductionPriceDecimal = new BigDecimal(scoreMayDeductionPrice);
- // 3-3. 计算积分抵扣后的价格
- if (halfPrice.compareTo(scoreMayDeductionPriceDecimal) <= 0) {
- // 积分能抵扣的金额大于订单总额的50%,按50%抵扣
- scoreMayDeductionPriceDecimal = halfPrice;
- }
- orderTotalPrice = orderTotalPrice.subtract(scoreMayDeductionPriceDecimal);
- LOGGER.info("会员【{}】,当前积分:{},抵扣订单金额后剩余积分:{}", memberCode, score, (score - scoreMayDeductionPriceDecimal.multiply(new BigDecimal(scoreLimit)).intValue()));
- }
- } else {
- LOGGER.info("会员【{}】的积分为0,不参加积分抵扣!", memberCode);
- }
- return orderTotalPrice;
- }
- /**
- * 重发订单
- * @param orderSn
- * @return
- */
- @Override
- public R resendOrderHkMall(String orderSn) {
- LOGGER.info("=======> [调用VMCShop接口开始发送退款订单数据]"+orderSn);
- String body = JacksonUtil.toJson(orderSn);
- String response = vmcShopTemplate.resendOrder(body);
- //解析响应数据
- LOGGER.info("=======> [resendOrderHkMall---重发订单数据成功,开始处理后续流程]"+response);
- //记录发送至免税Mall日志
- saveVmcSend(orderSn,VmcconnectUrlEnum.ORDERS_RETRY_ORDER.getMethod(),body,response);
- Map<String,String> res = JSON.parseObject(response,Map.class);
- if("0".equals(res.get("code"))){
- return R.ok();
- }else{
- return R.error(500,"重发订单失败");
- }
- }
- /**
- * 记录发送至免税Mall日志
- * @param orderSn
- * @param body
- * @param response
- */
- private void saveVmcSend(String orderSn,String urlType,String body,String response){
- MallVmcSendlogEntity mallVmcSendlogEntity = new MallVmcSendlogEntity();
- mallVmcSendlogEntity.setOrderSn(orderSn);
- mallVmcSendlogEntity.setVmcType(urlType);
- mallVmcSendlogEntity.setRequestMsg(body);
- mallVmcSendlogEntity.setResponseMsg(response);
- mallVmcSendLogDao.saveVmcSend(mallVmcSendlogEntity);
- }
- /**
- * 设置订单数据
- *
- * @return
- */
- public OrderVo setOrderVo(List<GoodsEntity> goodsList, UserEntity loginUser, Long storeId, String merchSn, BigDecimal disCountAmount, BigDecimal totalTax) {
- OrderVo orderInfo = new OrderVo();
- BigDecimal goodsTotalPrice = new BigDecimal(0.00);
- BigDecimal fullCutCouponDec = Constant.ZERO; // 非现金抵扣 = 各种优惠价格 +优惠券的价格 暂时借用这个字段去,为了不改动ccnet系统
- BigDecimal couponPrice = disCountAmount;
- BigDecimal freightPrice = Constant.ZERO;
- BigDecimal actualPrice = Constant.ZERO;
- //订单价格计算:订单的总价+运费
- for (GoodsEntity goodsEntity : goodsList) {
- goodsTotalPrice = goodsTotalPrice
- .add(goodsEntity.getRetailPrice().multiply(new BigDecimal(goodsEntity.getGoodsNumber()))).setScale(2, RoundingMode.HALF_UP);
- fullCutCouponDec = fullCutCouponDec
- .add(goodsEntity.getDiscountedPrice()).setScale(2, RoundingMode.HALF_UP);
- actualPrice = actualPrice
- .add(goodsEntity.getActualPaymentAmount()).setScale(2, RoundingMode.HALF_UP);
- }
- BigDecimal orderTotalPrice = goodsTotalPrice.add(new BigDecimal(0));
- fullCutCouponDec = fullCutCouponDec.add(couponPrice).setScale(2, RoundingMode.HALF_UP);
- // 加上税额
- goodsTotalPrice = goodsTotalPrice.subtract(totalTax).setScale(2, RoundingMode.HALF_UP);
- SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
- String orderSn = "ZWCW" + format.format(new Date()) + CommonUtil.generateOrderNumber();
- orderInfo.setOrder_sn(orderSn);
- orderInfo.setMerchSn(merchSn);
- orderInfo.setUser_id(loginUser.getId().longValue());
- actualPrice = actualPrice.subtract(couponPrice);
- StoreEntity storeEntity = storeDao.queryObject(storeId);
- //收货地址和运费
- orderInfo.setConsignee(loginUser.getUsername());
- orderInfo.setMobile(loginUser.getMobile());
- orderInfo.setCountry("");
- orderInfo.setProvince(storeEntity.getProvinceName());
- orderInfo.setCity(storeEntity.getCityName());
- orderInfo.setDistrict(storeEntity.getCountyName());
- orderInfo.setAddress(storeEntity.getStoreAddress());
- orderInfo.setAddress_id(1L);
- orderInfo.setDelivery_date(new Date());
- orderInfo.setDelivery_remark("无");
- orderInfo.setStore_id(storeId);
- orderInfo.setFreight_price(freightPrice.intValue());
- orderInfo.setCoupon_id(Integer.parseInt(String.valueOf(0L)));
- orderInfo.setCoupon_price(couponPrice);
- orderInfo.setCoupon_name("无");
- orderInfo.setActivity_id(0L);
- //使用的促销费用
- orderInfo.setFull_cut_price(fullCutCouponDec);
- orderInfo.setCampMinusId(0);
- orderInfo.setCampName("");
- //留言
- orderInfo.setPostscript("无");
- orderInfo.setAdd_time(new Date());
- orderInfo.setGoods_price(goodsTotalPrice); // 商品总价
- orderInfo.setOrder_price(orderTotalPrice);
- orderInfo.setActual_price(actualPrice); // 实际支付金额
- orderInfo.setOrder_type("1");
- orderInfo.setOrder_status(0);
- orderInfo.setShipping_status(0);
- orderInfo.setPay_status(0);
- orderInfo.setShipping_id(0L);
- orderInfo.setShipping_fee(Constant.ZERO);
- orderInfo.setIntegral(0);
- orderInfo.setIntegral_money(Constant.ZERO);
- orderInfo.setCreateTime(new Date());
- orderInfo.setModTime(new Date());
- orderInfo.setPayMobile(loginUser.getMobile());
- // orderInfo.setPayTransactionId(orderInfo.getOrder_sn());
- orderInfo.setIsScan("0");//默认未扫描
- orderInfo.setPayMobile(loginUser.getMobile());
- orderInfo.setPay_name(loginUser.getUsername());
- orderInfo.setIsOnfflineOrder(Dict.isOnfflineOrder.item_1.getItem());
- orderInfo.setOrderBizType(Dict.orderBizType.item_10.getItem());
- return orderInfo;
- }
- /**
- * 设置订单数据
- *
- * @return
- */
- public OrderVo setOrderVo(List<GoodsEntity> goodsList, UserEntity loginUser, Long storeId, String merchSn, BigDecimal disCountAmount, BigDecimal totalTax, int status, Map mapAddr) {
- OrderVo orderInfo = new OrderVo();
- BigDecimal goodsTotalPrice = new BigDecimal(0.00);
- BigDecimal fullCutCouponDec = Constant.ZERO; // 非现金抵扣 = 各种优惠价格 +优惠券的价格 暂时借用这个字段去,为了不改动ccnet系统
- BigDecimal couponPrice = disCountAmount;
- BigDecimal freightPrice = Constant.ZERO;
- BigDecimal actualPrice = Constant.ZERO;
- //订单价格计算:订单的总价+运费
- for (GoodsEntity goodsEntity : goodsList) {
- goodsTotalPrice = goodsTotalPrice
- .add(goodsEntity.getRetailPrice().multiply(new BigDecimal(goodsEntity.getGoodsNumber()))).setScale(2, RoundingMode.HALF_UP);
- fullCutCouponDec = fullCutCouponDec
- .add(goodsEntity.getDiscountedPrice()).setScale(2, RoundingMode.HALF_UP);
- actualPrice = actualPrice
- .add(goodsEntity.getActualPaymentAmount()).setScale(2, RoundingMode.HALF_UP);
- }
- BigDecimal orderTotalPrice = goodsTotalPrice.add(new BigDecimal(0));
- fullCutCouponDec = fullCutCouponDec.add(couponPrice).setScale(2, RoundingMode.HALF_UP);
- // 加上税额
- goodsTotalPrice = goodsTotalPrice.subtract(totalTax).setScale(2, RoundingMode.HALF_UP);
- SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
- String orderSn = "ZWCW" + format.format(new Date()) + CommonUtil.generateOrderNumber();
- orderInfo.setOrder_sn(orderSn);
- orderInfo.setMerchSn(merchSn);
- orderInfo.setUser_id(loginUser.getId().longValue());
- actualPrice = actualPrice.subtract(couponPrice);
- StoreEntity storeEntity = storeDao.queryObject(storeId);
- //收货地址和运费
- orderInfo.setConsignee(loginUser.getUsername());
- orderInfo.setMobile(loginUser.getMobile());
- orderInfo.setCountry("");
- //根据 前端的选择方式 1 是柜取 0 是 邮寄
- if (status == 0) {
- //省
- String cmbProvince = (String) mapAddr.get("cmbProvince");
- //市
- String cmbCity = (String) mapAddr.get("cmbCity");
- //区
- String cmbArea = (String) mapAddr.get("cmbArea");
- //详细地址
- String addrUser = (String) mapAddr.get("addrUser");
- orderInfo.setProvince(cmbProvince);
- orderInfo.setCity(cmbCity);
- orderInfo.setDistrict(cmbArea);
- orderInfo.setAddress(addrUser);
- } else {
- orderInfo.setProvince(storeEntity.getProvinceName());
- orderInfo.setCity(storeEntity.getCityName());
- orderInfo.setDistrict(storeEntity.getCountyName());
- orderInfo.setAddress(storeEntity.getStoreAddress());
- }
- orderInfo.setAddress_id(1L);
- orderInfo.setDelivery_date(new Date());
- orderInfo.setDelivery_remark("无");
- orderInfo.setStore_id(storeId);
- orderInfo.setFreight_price(freightPrice.intValue());
- orderInfo.setCoupon_id(Integer.parseInt(String.valueOf(0L)));
- orderInfo.setCoupon_price(couponPrice);
- orderInfo.setCoupon_name("无");
- orderInfo.setActivity_id(0L);
- //使用的促销费用
- orderInfo.setFull_cut_price(fullCutCouponDec);
- orderInfo.setCampMinusId(0);
- orderInfo.setCampName("");
- //留言
- orderInfo.setPostscript("无");
- orderInfo.setAdd_time(new Date());
- orderInfo.setGoods_price(goodsTotalPrice); // 商品总价
- orderInfo.setOrder_price(orderTotalPrice);
- orderInfo.setActual_price(actualPrice); // 实际支付金额
- orderInfo.setOrder_type("1");
- orderInfo.setOrder_status(0);
- orderInfo.setShipping_status(0);
- orderInfo.setPay_status(0);
- orderInfo.setShipping_id(0L);
- orderInfo.setShipping_fee(Constant.ZERO);
- orderInfo.setIntegral(0);
- orderInfo.setIntegral_money(Constant.ZERO);
- orderInfo.setCreateTime(new Date());
- orderInfo.setModTime(new Date());
- orderInfo.setPayMobile(loginUser.getMobile());
- // orderInfo.setPayTransactionId(orderInfo.getOrder_sn());
- orderInfo.setIsScan("0");//默认未扫描
- orderInfo.setPayMobile(loginUser.getMobile());
- orderInfo.setPay_name(loginUser.getUsername());
- orderInfo.setIsOnfflineOrder(Dict.isOnfflineOrder.item_1.getItem());
- orderInfo.setOrderBizType(Dict.orderBizType.item_10.getItem());
- // 添加快递信息
- try {
- StoreExprActiveDto activeExpr = addressInfoService.queryByStoreId(storeId);
- if (activeExpr == null) {
- throw new RRException("门店未配置快递信息");
- }
- orderInfo.setShipping_id(activeExpr.getExprId());
- orderInfo.setShipping_code(activeExpr.getExprCode());
- orderInfo.setShipping_name(activeExpr.getExprName());
- } catch (Exception e) {
- LOGGER.error("订单写入门店快递配置信息有误:", e);
- }
- return orderInfo;
- }
- public OrderGoodsVo setOrderGoodsVo(OrderVo orderInfo, GoodsEntity goodsDto) {
- OrderGoodsVo orderGoodsVo = new OrderGoodsVo();
- orderGoodsVo.setOrder_id(orderInfo.getId());
- orderGoodsVo.setGoods_id(goodsDto.getId());
- orderGoodsVo.setGoods_sn(goodsDto.getGoodsSn());
- orderGoodsVo.setProduct_id(Long.valueOf(goodsDto.getProductId()));
- orderGoodsVo.setGoods_name(goodsDto.getName());
- orderGoodsVo.setList_pic_url(goodsDto.getListPicUrl());
- orderGoodsVo.setMarket_price(goodsDto.getStoreRetailPrice());
- orderGoodsVo.setRetail_price(goodsDto.getStoreRetailPrice());
- orderGoodsVo.setDiscountedPrice(goodsDto.getDiscountedPrice());
- orderGoodsVo.setActualPaymentAmount(goodsDto.getActualPaymentAmount());
- orderGoodsVo.setNumber(goodsDto.getGoodsNumber());
- // orderGoodsVo.setGoods_specification_name_value(goodsDto.get);
- // orderGoodsVo.setGoods_specification_ids(goodsItem.getGoods_specification_ids());
- orderGoodsVo.setOrderBizType(Dict.orderBizType.item_10.getItem());
- orderGoodsVo.setCreateTime(new Date());
- orderGoodsVo.setModTime(new Date());
- orderGoodsVo.setActivity(goodsDto.getActivity());
- orderGoodsVo.setGoodsRate(goodsDto.getGoodsRate());
- orderGoodsVo.setSku(goodsDto.getSku());
- BigDecimal number = new BigDecimal(Long.valueOf(goodsDto.getGoodsNumber()));
- BigDecimal goodsTotal = goodsDto.getRetailPrice().multiply(number);//单商品总价
- BigDecimal rate = goodsTotal.divide(orderInfo.getGoods_price(), 2, BigDecimal.ROUND_HALF_UP);//当前商品总价/订单总价(不含运费、不含优惠券)
- BigDecimal freightPrice = BigDecimal.valueOf(orderInfo.getFreight_price());
- BigDecimal settlePrice = Constant.ZERO; // ccnet 取的这个而价格
- if (orderInfo.getFreight_price() != 0 && !"0".equalsIgnoreCase(orderInfo.getCoupon_price() + "")) {
- //运费-优惠券
- BigDecimal rateTotal = freightPrice.subtract(orderInfo.getCoupon_price());
- //商品结算平摊价格(含优惠券、运费金额) = 单商品总价 + 当前商品总价/订单总价(不含运费、不含优惠券) * 运费与优惠券合计税率
- settlePrice = goodsTotal.add(rate.multiply(rateTotal));
- } else {
- if (orderInfo.getFreight_price() != 0) {
- //运费税率 = 单商品总价/订单总价(不含运费)* 运费金额
- BigDecimal freightRate = rate.multiply(freightPrice);
- //商品结算平摊价格(含运费金额) = 单商品总价+运费税率
- settlePrice = goodsTotal.add(freightRate);
- }
- if (!"0".equalsIgnoreCase(orderInfo.getCoupon_price() + "")) {
- //优惠券税率 = 单商品总价/订单总价(不含优惠券)* 优惠券金额
- BigDecimal couponRate = rate.multiply(orderInfo.getCoupon_price());
- //商品结算平摊价格(含优惠券金额) = 单商品总价-优惠券税率
- settlePrice = goodsTotal.subtract(couponRate);
- }
- }
- if (settlePrice.compareTo(BigDecimal.valueOf(0)) == 0) {
- orderGoodsVo.setSettlePrice(goodsTotal);//商品结算平摊价格
- } else {
- orderGoodsVo.setSettlePrice(settlePrice);//商品结算平摊价格
- }
- // 计算税费
- GoodsEntity goodsEntity = goodsService.queryObject(goodsDto.getId().intValue());
- BigDecimal goodsTax = CalculateTax.calculateFinalTax(goodsEntity, goodsDto.getStoreRetailPrice(), goodsService).setScale(3, RoundingMode.HALF_UP);
- goodsTax = goodsTax.multiply(number).setScale(2, RoundingMode.HALF_UP);
- orderGoodsVo.setTaxPrice(goodsTax);
- return orderGoodsVo;
- }
- }
|