StoreOrder.php 203 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496
  1. <<<<<<< HEAD
  2. <?php
  3. /**
  4. *
  5. * @author: xaboy<365615158@qq.com>
  6. * @day: 2017/12/20
  7. */
  8. namespace app\models\store;
  9. use app\admin\model\system\ShippingTemplatesFree;
  10. use app\admin\model\system\ShippingTemplatesRegion;
  11. use crmeb\basic\BaseModel;
  12. use think\db\exception\DataNotFoundException;
  13. use think\db\exception\DbException;
  14. use think\db\exception\ModelNotFoundException;
  15. use think\facade\Cache;
  16. use crmeb\traits\ModelTrait;
  17. use think\facade\Log;
  18. use app\models\system\SystemStore;
  19. use app\models\routine\RoutineTemplate;
  20. use app\models\user\{Out, ProxyAddress, User, UserAddress, UserBill, UserLevel, UserPartake, UserSpread, WechatUser};
  21. use crmeb\services\{
  22. SystemConfigService, WechatTemplateService, workerman\ChannelService
  23. };
  24. use crmeb\repositories\{
  25. GoodsRepository, PaymentRepositories, OrderRepository, ShortLetterRepositories, UserRepository
  26. };
  27. use app\admin\model\system\ShippingTemplates;
  28. /**
  29. * TODO 订单Model
  30. * Class StoreOrder
  31. * @package app\models\store
  32. */
  33. class StoreOrder extends BaseModel
  34. {
  35. /**
  36. * 数据表主键
  37. * @var string
  38. */
  39. protected $pk = 'id';
  40. /**
  41. * 模型名称
  42. * @var string
  43. */
  44. protected $name = 'store_order';
  45. use ModelTrait;
  46. protected $insert = ['add_time'];
  47. protected static $payType = ['weixin' => '微信支付', 'yue' => '余额支付', 'offline' => '线下支付', 'ali' => '支付宝支付'];
  48. protected static $deliveryType = ['send' => '商家配送', 'express' => '快递配送'];
  49. protected function setAddTimeAttr()
  50. {
  51. return time();
  52. }
  53. protected function setCartIdAttr($value)
  54. {
  55. return is_array($value) ? json_encode($value) : $value;
  56. }
  57. protected function getCartIdAttr($value)
  58. {
  59. return json_decode($value, true);
  60. }
  61. /**获取订单组信息
  62. * @param $cartInfo
  63. * @return array
  64. */
  65. public static function getOrderPriceGroup($cartInfo, $addr)
  66. {
  67. $storeFreePostage = floatval(sys_config('store_free_postage')) ?: 0;//满额包邮
  68. $totalPrice = self::getOrderSumPrice($cartInfo, 'truePrice');//获取订单总金额
  69. $totalIntegral = self::getOrderSumPrice($cartInfo, 'integral');//获取订单总积分
  70. $costPrice = self::getOrderSumPrice($cartInfo, 'costPrice');//获取订单成本价
  71. $vipPrice = self::getOrderSumPrice($cartInfo, 'vip_truePrice');//获取订单会员优惠金额
  72. //如果满额包邮等于0
  73. if (!$storeFreePostage) {
  74. $storePostage = 0;
  75. } else {
  76. if ($addr) {
  77. //按照运费模板计算每个运费模板下商品的件数/重量/体积以及总金额 按照首重倒序排列
  78. $temp_num = [];
  79. foreach ($cartInfo as $cart) {
  80. $temp = ShippingTemplates::get($cart['productInfo']['temp_id']);
  81. if (!$temp) $temp = ShippingTemplates::get(1);
  82. if ($temp->getData('type') == 1) {
  83. $num = $cart['cart_num'];
  84. } elseif ($temp->getData('type') == 2) {
  85. $num = $cart['cart_num'] * $cart['productInfo']['attrInfo']['weight'];
  86. } else {
  87. $num = $cart['cart_num'] * $cart['productInfo']['attrInfo']['volume'];
  88. }
  89. $region = ShippingTemplatesRegion::where('temp_id', $cart['productInfo']['temp_id'])->where('city_id', $addr['city_id'])->find();
  90. if (!$region) $region = ShippingTemplatesRegion::where('temp_id', $cart['productInfo']['temp_id'])->where('city_id', 0)->find();
  91. if (!$region) $region = ShippingTemplatesRegion::where('temp_id', 1)->where('city_id', 0)->find();
  92. if (!$region) {
  93. return self::setErrorInfo('运费模板不存在');
  94. }
  95. if (!isset($temp_num[$cart['productInfo']['temp_id']])) {
  96. $temp_num[$cart['productInfo']['temp_id']]['number'] = $num;
  97. $temp_num[$cart['productInfo']['temp_id']]['price'] = bcmul($cart['cart_num'], $cart['truePrice'], 2);
  98. $temp_num[$cart['productInfo']['temp_id']]['first'] = $region['first'];
  99. $temp_num[$cart['productInfo']['temp_id']]['first_price'] = $region['first_price'];
  100. $temp_num[$cart['productInfo']['temp_id']]['continue'] = $region['continue'];
  101. $temp_num[$cart['productInfo']['temp_id']]['continue_price'] = $region['continue_price'];
  102. $temp_num[$cart['productInfo']['temp_id']]['temp_id'] = $cart['productInfo']['temp_id'];
  103. $temp_num[$cart['productInfo']['temp_id']]['city_id'] = $addr['city_id'];
  104. } else {
  105. $temp_num[$cart['productInfo']['temp_id']]['number'] += $num;
  106. $temp_num[$cart['productInfo']['temp_id']]['price'] += bcmul($cart['cart_num'], $cart['truePrice'], 2);
  107. }
  108. }
  109. array_multisort(array_column($temp_num, 'first_price'), SORT_DESC, $temp_num);
  110. $type = $storePostage = 0;
  111. foreach ($temp_num as $k => $v) {
  112. if (ShippingTemplatesFree::where('temp_id', $v['temp_id'])->where('city_id', $v['city_id'])->where('number', '<=', $v['number'])->where('price', '<=', $v['price'])->find()) {
  113. unset($temp_num[$k]);
  114. }
  115. }
  116. foreach ($temp_num as $v) {
  117. if ($type == 0) {
  118. if ($v['number'] <= $v['first']) {
  119. $storePostage = bcadd($storePostage, $v['first_price'], 2);
  120. } else {
  121. if ($v['continue'] <= 0) {
  122. $storePostage = $storePostage;
  123. } else {
  124. $storePostage = bcadd(bcadd($storePostage, $v['first_price'], 2), bcmul(ceil(bcdiv(bcsub($v['number'], $v['first']), $v['continue'] ?? 0, 2)), $v['continue_price']), 2);
  125. }
  126. }
  127. $type = 1;
  128. } else {
  129. if ($v['continue'] <= 0) {
  130. $storePostage = $storePostage;
  131. } else {
  132. $storePostage = bcadd($storePostage, bcmul(ceil(bcdiv($v['number'], $v['continue'] ?? 0, 2)), $v['continue_price']), 2);
  133. }
  134. }
  135. }
  136. } else {
  137. $storePostage = 0;
  138. }
  139. if ($storeFreePostage <= $totalPrice) $storePostage = 0;//如果总价大于等于满额包邮 邮费等于0
  140. }
  141. return compact('storePostage', 'storeFreePostage', 'totalPrice', 'costPrice', 'vipPrice', 'totalIntegral');
  142. }
  143. /**获取某个字段总金额
  144. * @param $cartInfo
  145. * @param $key 键名
  146. * @return int|string
  147. */
  148. public static function getOrderSumPrice($cartInfo, $key = 'truePrice')
  149. {
  150. $SumPrice = 0;
  151. foreach ($cartInfo as $cart) {
  152. $SumPrice = bcadd($SumPrice, bcmul($cart['cart_num'], $cart[$key], 2), 2);
  153. }
  154. return $SumPrice;
  155. }
  156. /**
  157. * 拼团
  158. * @param $cartInfo
  159. * @return array
  160. */
  161. public static function getCombinationOrderPriceGroup($cartInfo)
  162. {
  163. $storePostage = floatval(sys_config('store_postage')) ?: 0;
  164. $storeFreePostage = floatval(sys_config('store_free_postage')) ?: 0;
  165. $totalPrice = self::getCombinationOrderTotalPrice($cartInfo);
  166. $costPrice = self::getCombinationOrderTotalPrice($cartInfo);
  167. if (!$storeFreePostage) {
  168. $storePostage = 0;
  169. } else {
  170. foreach ($cartInfo as $cart) {
  171. if (!StoreCombination::where('id', $cart['combination_id'])->value('is_postage'))
  172. $storePostage = bcadd($storePostage, StoreCombination::where('id', $cart['combination_id'])->value('postage'), 2);
  173. }
  174. if ($storeFreePostage <= $totalPrice) $storePostage = 0;
  175. }
  176. return compact('storePostage', 'storeFreePostage', 'totalPrice', 'costPrice');
  177. }
  178. /**
  179. * 拼团价格
  180. * @param $cartInfo
  181. * @return float
  182. */
  183. public static function getCombinationOrderTotalPrice($cartInfo)
  184. {
  185. $totalPrice = 0;
  186. foreach ($cartInfo as $cart) {
  187. if ($cart['combination_id']) {
  188. $totalPrice = bcadd($totalPrice, bcmul($cart['cart_num'], StoreCombination::where('id', $cart['combination_id'])->value('price'), 2), 2);
  189. }
  190. }
  191. return (float)$totalPrice;
  192. }
  193. /**
  194. * 缓存订单信息
  195. * @param $uid
  196. * @param $cartInfo
  197. * @param $priceGroup
  198. * @param array $other
  199. * @param int $cacheTime
  200. * @return string
  201. * @throws \Psr\SimpleCache\InvalidArgumentException
  202. */
  203. public static function cacheOrderInfo($uid, $cartInfo, $priceGroup, $other = [], $cacheTime = 600)
  204. {
  205. do {
  206. $key = md5(time() . rand(100000, 999999));
  207. } while (Cache::has('user_order_' . $uid . $key));
  208. Cache::set('user_order_' . $uid . $key, compact('cartInfo', 'priceGroup', 'other'), $cacheTime);
  209. return $key;
  210. }
  211. /**
  212. * 获取订单缓存信息
  213. * @param $uid
  214. * @param $key
  215. * @return mixed|null
  216. * @throws \Psr\SimpleCache\InvalidArgumentException
  217. */
  218. public static function getCacheOrderInfo($uid, $key)
  219. {
  220. $cacheName = 'user_order_' . $uid . $key;
  221. if (!Cache::has($cacheName)) return null;
  222. return Cache::get($cacheName);
  223. }
  224. /**
  225. * 删除订单缓存
  226. * @param $uid
  227. * @param $key
  228. */
  229. public static function clearCacheOrderInfo($uid, $key)
  230. {
  231. Cache::delete('user_order_' . $uid . $key);
  232. }
  233. /**
  234. * 生成订单
  235. * @param $uid
  236. * @param $key
  237. * @param $addressId
  238. * @param $payType
  239. * @param bool $useIntegral
  240. * @param int $couponId
  241. * @param string $mark
  242. * @param int $combinationId
  243. * @param int $pinkId
  244. * @param int $seckill_id
  245. * @param int $bargain_id
  246. * @param bool $test
  247. * @param int $isChannel
  248. * @param int $shipping_type
  249. * @param string $real_name
  250. * @param string $phone
  251. * @return StoreOrder|bool|\think\Model
  252. * @throws \think\Exception
  253. * @throws DataNotFoundException
  254. * @throws ModelNotFoundException
  255. * @throws \think\exception\DbException
  256. */
  257. public static function cacheKeyCreateOrder($uid, $key, $addressId, $payType, $useIntegral = false, $couponId = 0, $mark = '', $combinationId = 0, $pinkId = 0, $seckill_id = 0, $bargain_id = 0, $test = false, $isChannel = 0, $shipping_type = 1, $real_name = '', $phone = '', $storeId = 0)
  258. {
  259. self::beginTrans();
  260. try {
  261. $shipping_type = (int)$shipping_type;
  262. $offlinePayStatus = (int)sys_config('offline_pay_status') ?? (int)2;
  263. if ($offlinePayStatus == 2) unset(self::$payType['offline']);
  264. if (!array_key_exists($payType, self::$payType)) return self::setErrorInfo('选择支付方式有误!', true);
  265. if (self::be(['unique' => $key, 'uid' => $uid])) return self::setErrorInfo('请勿重复提交订单', true);
  266. $userInfo = User::getUserInfo($uid);
  267. if (!$userInfo) return self::setErrorInfo('用户不存在!', true);
  268. $cartGroup = self::getCacheOrderInfo($uid, $key);
  269. if (!$cartGroup) return self::setErrorInfo('订单已过期,请刷新当前页面!', true);
  270. $cartInfo = $cartGroup['cartInfo'];
  271. $priceGroup = $cartGroup['priceGroup'];
  272. $other = $cartGroup['other'];
  273. $payPrice = (float)$priceGroup['totalPrice'];
  274. $payIntegral = (float)$priceGroup['totalIntegral'];
  275. $addr = UserAddress::where('uid', $uid)->where('id', $addressId)->find();
  276. if ($payType == 'offline' && sys_config('offline_postage') == 1) {
  277. $payPostage = 0;
  278. } else {
  279. $payPostage = self::getOrderPriceGroup($cartInfo, $addr)['storePostage'];
  280. }
  281. if ($shipping_type === 1) {
  282. if (!$test && !$addressId) return self::setErrorInfo('请选择收货地址!', true);
  283. if (!$test && (!UserAddress::be(['uid' => $uid, 'id' => $addressId, 'is_del' => 0]) || !($addressInfo = UserAddress::find($addressId))))
  284. return self::setErrorInfo('地址选择有误!', true);
  285. } else {
  286. if ((!$real_name || !$phone) && !$test) return self::setErrorInfo('请填写姓名和电话', true);
  287. $addressInfo['real_name'] = $real_name;
  288. $addressInfo['phone'] = $phone;
  289. $addressInfo['province'] = '';
  290. $addressInfo['city'] = '';
  291. $addressInfo['district'] = '';
  292. $addressInfo['detail'] = '';
  293. }
  294. $cartIds = [];
  295. $totalNum = 0;
  296. $gainIntegral = 0;
  297. foreach ($cartInfo as $cart) {
  298. $cartIds[] = $cart['id'];
  299. $totalNum += $cart['cart_num'];
  300. if (!$seckill_id) $seckill_id = $cart['seckill_id'];
  301. if (!$bargain_id) $bargain_id = $cart['bargain_id'];
  302. if (!$combinationId) $combinationId = $cart['combination_id'];
  303. $cartInfoGainIntegral = isset($cart['productInfo']['give_integral']) ? bcmul($cart['cart_num'], $cart['productInfo']['give_integral'], 2) : 0;
  304. $gainIntegral = bcadd($gainIntegral, $cartInfoGainIntegral, 2);
  305. }
  306. $deduction = $seckill_id || $bargain_id || $combinationId;
  307. if ($deduction) {
  308. $couponId = 0;
  309. $useIntegral = false;
  310. if (!$test) {
  311. unset(self::$payType['offline']);
  312. if (!array_key_exists($payType, self::$payType)) return self::setErrorInfo('营销产品不能使用线下支付!', true);
  313. }
  314. }
  315. //使用优惠劵
  316. $res1 = true;
  317. if ($couponId) {
  318. $couponInfo = StoreCouponUser::validAddressWhere()->where('id', $couponId)->where('uid', $uid)->find();
  319. if (!$couponInfo) return self::setErrorInfo('选择的优惠劵无效!', true);
  320. $coupons = StoreCouponUser::getUsableCouponList($uid, ['valid' => $cartInfo], $payPrice);
  321. $flag = false;
  322. foreach ($coupons as $coupon) {
  323. if ($coupon['id'] == $couponId) {
  324. $flag = true;
  325. continue;
  326. }
  327. }
  328. if (!$flag)
  329. return self::setErrorInfo('不满足优惠劵的使用条件!', true);
  330. $payPrice = (float)bcsub($payPrice, $couponInfo['coupon_price'], 2);
  331. $res1 = StoreCouponUser::useCoupon($couponId);
  332. $couponPrice = $couponInfo['coupon_price'];
  333. } else {
  334. $couponId = 0;
  335. $couponPrice = 0;
  336. }
  337. if (!$res1) return self::setErrorInfo('使用优惠劵失败!', true);
  338. //$shipping_type = 1 快递发货 $shipping_type = 2 门店自提
  339. $store_self_mention = sys_config('store_self_mention') ?? 0;
  340. if (!$store_self_mention) $shipping_type = 1;
  341. if ($shipping_type === 1) {
  342. //是否包邮
  343. if ((isset($other['offlinePostage']) && $other['offlinePostage'] && $payType == 'offline')) $payPostage = 0;
  344. $payPrice = (float)bcadd($payPrice, $payPostage, 2);
  345. } else if ($shipping_type === 2) {
  346. //门店自提没有邮费支付
  347. $priceGroup['storePostage'] = 0;
  348. $payPostage = 0;
  349. if (!$storeId && !$test) {
  350. return self::setErrorInfo('请选择门店', true);
  351. }
  352. }
  353. //积分抵扣
  354. $res2 = true;
  355. $SurplusIntegral = $userInfo['integral'];
  356. if ($payIntegral > 0) {
  357. if ($userInfo['integral'] < $payIntegral) {
  358. return self::setErrorInfo('积分不足', true);
  359. } else {
  360. $res2 = false !== User::bcDec($userInfo['uid'], 'integral', $payIntegral, 'uid');
  361. }
  362. $SurplusIntegral = bcsub($userInfo['integral'], $payIntegral, 2);
  363. $res2 = $res2 && false != UserBill::expend('积分商品', $uid, 'integral', 'integral_product', $payIntegral, $key, $SurplusIntegral, '购买积分商品使用' . $payIntegral . '积分');
  364. }
  365. //积分抵扣
  366. if ($useIntegral && $SurplusIntegral > 0) {
  367. $deductionPrice = (float)bcmul($SurplusIntegral, $other['integralRatio'], 2);
  368. if ($deductionPrice < $payPrice) {
  369. $payPrice = bcsub($payPrice, $deductionPrice, 2);
  370. $usedIntegral = $SurplusIntegral;
  371. $SurplusIntegral = 0;
  372. $res2 = false !== User::edit(['integral' => 0], $userInfo['uid'], 'uid');
  373. } else {
  374. $deductionPrice = $payPrice;
  375. $usedIntegral = (float)bcdiv($payPrice, $other['integralRatio'], 2);
  376. $SurplusIntegral = bcsub($SurplusIntegral, $usedIntegral, 2);
  377. $res2 = false !== User::bcDec($userInfo['uid'], 'integral', $usedIntegral, 'uid');
  378. $payPrice = 0;
  379. }
  380. $res2 = $res2 && false != UserBill::expend('积分抵扣', $uid, 'integral', 'deduction', $usedIntegral, $key, $SurplusIntegral, '购买商品使用' . floatval($usedIntegral) . '积分抵扣' . floatval($deductionPrice) . '元');
  381. } else {
  382. $deductionPrice = 0;
  383. $usedIntegral = 0;
  384. }
  385. if (!$res2) return self::setErrorInfo('使用积分抵扣失败!', true);
  386. if ($payPrice <= 0) $payPrice = 0;
  387. if ($test) {
  388. self::rollbackTrans();
  389. return [
  390. 'total_price' => $priceGroup['totalPrice'],
  391. 'pay_price' => $payPrice,
  392. 'pay_postage' => $payPostage,
  393. 'coupon_price' => $couponPrice,
  394. 'deduction_price' => $deductionPrice,
  395. 'totalIntegral' => $payIntegral,
  396. 'SurplusIntegral' => $SurplusIntegral,
  397. ];
  398. }
  399. $orderInfo = [
  400. 'uid' => $uid,
  401. 'order_id' => $test ? 0 : self::getNewOrderId(),
  402. 'real_name' => $addressInfo['real_name'],
  403. 'user_phone' => $addressInfo['phone'],
  404. 'user_address' => $addressInfo['province'] . ' ' . $addressInfo['city'] . ' ' . $addressInfo['district'] . ' ' . $addressInfo['detail'],
  405. 'cart_id' => $cartIds,
  406. 'total_num' => $totalNum,
  407. 'total_price' => $priceGroup['totalPrice'],
  408. 'total_postage' => $priceGroup['storePostage'],
  409. 'coupon_id' => $couponId,
  410. 'coupon_price' => $couponPrice,
  411. 'pay_price' => $payPrice,
  412. 'pay_postage' => $payPostage,
  413. 'deduction_price' => $deductionPrice,
  414. 'paid' => 0,
  415. 'pay_type' => $payType,
  416. 'use_integral' => $usedIntegral + $payIntegral,
  417. 'gain_integral' => $gainIntegral,
  418. 'mark' => htmlspecialchars($mark),
  419. 'combination_id' => $combinationId,
  420. 'pink_id' => $pinkId,
  421. 'seckill_id' => $seckill_id,
  422. 'bargain_id' => $bargain_id,
  423. 'cost' => $priceGroup['costPrice'],
  424. 'is_channel' => $isChannel,
  425. 'add_time' => time(),
  426. 'unique' => $key,
  427. 'shipping_type' => $shipping_type,
  428. ];
  429. if ($shipping_type === 2) {
  430. $orderInfo['verify_code'] = self::getStoreCode();
  431. $orderInfo['store_id'] = SystemStore::getStoreDispose($storeId, 'id');
  432. if (!$orderInfo['store_id']) return self::setErrorInfo('暂无门店无法选择门店自提!', true);
  433. }
  434. $order = self::create($orderInfo);
  435. if (!$order) return self::setErrorInfo('订单生成失败!', true);
  436. $res5 = true;
  437. foreach ($cartInfo as $cart) {
  438. //减库存加销量
  439. if ($combinationId) $res5 = $res5 && StoreCombination::decCombinationStock($cart['cart_num'], $combinationId, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  440. else if ($seckill_id) $res5 = $res5 && StoreSeckill::decSeckillStock($cart['cart_num'], $seckill_id, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  441. else if ($bargain_id) $res5 = $res5 && StoreBargain::decBargainStock($cart['cart_num'], $bargain_id, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  442. else $res5 = $res5 && StoreProduct::decProductStock($cart['cart_num'], $cart['productInfo']['id'], isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  443. }
  444. //保存购物车商品信息
  445. $res4 = false !== StoreOrderCartInfo::setCartInfo($order['id'], $cartInfo);
  446. //购物车状态修改
  447. $res6 = false !== StoreCart::where('id', 'IN', $cartIds)->update(['is_pay' => 1]);
  448. if (!$res4 || !$res5 || !$res6) return self::setErrorInfo('订单生成失败!', true);
  449. //自动设置默认地址
  450. UserRepository::storeProductOrderCreateEbApi($order, compact('cartInfo', 'addressId'));
  451. self::clearCacheOrderInfo($uid, $key);
  452. self::commitTrans();
  453. StoreOrderStatus::status($order['id'], 'cache_key_create_order', '订单生成');
  454. return $order;
  455. } catch (\PDOException $e) {
  456. self::rollbackTrans();
  457. return self::setErrorInfo('生成订单时SQL执行错误错误原因:' . $e->getMessage());
  458. } catch (\Exception $e) {
  459. self::rollbackTrans();
  460. return self::setErrorInfo('生成订单时系统错误错误原因:' . $e->getMessage());
  461. }
  462. }
  463. /**
  464. * 回退积分
  465. * @param $order 订单信息
  466. * @return bool
  467. */
  468. public static function RegressionIntegral($order)
  469. {
  470. if ($order['paid'] || $order['status'] == -2 || $order['is_del']) return true;
  471. if ($order['use_integral'] <= 0) return true;
  472. if ((int)$order['status'] != -2 && (int)$order['refund_status'] != 2 && $order['back_integral'] >= $order['use_integral']) return true;
  473. $res = User::bcInc($order['uid'], 'integral', $order['use_integral']);
  474. if (!$res) return self::setErrorInfo('回退积分增加失败');
  475. UserBill::income('积分回退', $order['uid'], 'integral', 'deduction', $order['use_integral'], $order['unique'], User::where('uid', $order['uid'])->value('integral'), '购买商品失败,回退积分' . floatval($order['use_integral']));
  476. return false !== self::where('order_id', $order['order_id'])->update(['back_integral' => $order['use_integral']]);
  477. }
  478. /**
  479. * 回退库存和销量
  480. * @param $order 订单信息
  481. * @return bool
  482. * @throws DataNotFoundException
  483. * @throws ModelNotFoundException
  484. * @throws \think\exception\DbException
  485. */
  486. public static function RegressionStock($order)
  487. {
  488. if ($order['paid'] || $order['status'] == -2 || $order['is_del']) return true;
  489. $combinationId = $order['combination_id'];
  490. $seckill_id = $order['seckill_id'];
  491. $bargain_id = $order['bargain_id'];
  492. $res5 = true;
  493. $cartInfo = StoreOrderCartInfo::where('cart_id', 'in', $order['cart_id'])->select();
  494. foreach ($cartInfo as $cart) {
  495. //增库存减销量
  496. if ($combinationId) $res5 = $res5 && StoreCombination::incCombinationStock($cart['cart_info']['cart_num'], $combinationId);
  497. else if ($seckill_id) $res5 = $res5 && StoreSeckill::incSeckillStock($cart['cart_info']['cart_num'], $seckill_id);
  498. else if ($bargain_id) $res5 = $res5 && StoreBargain::incBargainStock($cart['cart_info']['cart_num'], $bargain_id);
  499. else $res5 = $res5 && StoreProduct::incProductStock($cart['cart_info']['cart_num'], $cart['cart_info']['productInfo']['id'], isset($cart['cart_info']['productInfo']['attrInfo']) ? $cart['cart_info']['productInfo']['attrInfo']['unique'] : '');
  500. }
  501. return $res5;
  502. }
  503. /**
  504. * 回退优惠卷
  505. * @param $order 订单信息
  506. * @return bool
  507. */
  508. public static function RegressionCoupon($order)
  509. {
  510. if ($order['paid'] || $order['status'] == -2 || $order['is_del']) return true;
  511. $res = true;
  512. if ($order['coupon_id'] && StoreCouponUser::be(['id' => $order['coupon_id'], 'uid' => $order['uid'], 'status' => 1])) {
  513. $res = $res && false !== StoreCouponUser::where('id', $order['coupon_id'])->where('uid', $order['uid'])->update(['status' => 0, 'use_time' => 0]);
  514. }
  515. return $res;
  516. }
  517. /**
  518. * 取消订单
  519. * @param string order_id 订单id
  520. * @param $uid
  521. * @return bool
  522. * @throws DataNotFoundException
  523. * @throws ModelNotFoundException
  524. * @throws \think\exception\DbException
  525. */
  526. public static function cancelOrder($order_id, $uid)
  527. {
  528. $order = self::where('order_id', $order_id)->where('uid', $uid)->find();
  529. if (!$order) return self::setErrorInfo('没有查到此订单');
  530. self::beginTrans();
  531. try {
  532. $res = self::RegressionIntegral($order) && self::RegressionStock($order) && self::RegressionCoupon($order);
  533. $order->is_del = 1;
  534. if ($res && $order->save()) {
  535. self::commitTrans();
  536. return true;
  537. } else
  538. return false;
  539. } catch (\Exception $e) {
  540. self::rollbackTrans();
  541. return self::setErrorInfo(['line' => $e->getLine(), 'message' => $e->getMessage()]);
  542. }
  543. }
  544. /**
  545. * 生成订单唯一id
  546. * @param $uid 用户uid
  547. * @return string
  548. */
  549. public static function getNewOrderId()
  550. {
  551. do {
  552. list($msec, $sec) = explode(' ', microtime());
  553. $msectime = number_format((floatval($msec) + floatval($sec)) * 1000, 0, '', '');
  554. $orderId = 'wx' . $msectime . mt_rand(10000, 99999);
  555. } while (self::be(['order_id' => $orderId]));// $orderId = 'wx' . $msectime . mt_rand(10000, 99999);
  556. return $orderId;
  557. }
  558. /**
  559. * 修改订单号
  560. * @param $orderId
  561. * @return string
  562. */
  563. public static function changeOrderId($orderId)
  564. {
  565. $ymd = substr($orderId, 2, 8);
  566. $key = substr($orderId, 16);
  567. return 'wx' . $ymd . date('His') . $key;
  568. }
  569. /**
  570. * 查找购物车里的所有产品标题
  571. * @param $cartId 购物车id
  572. * @return bool|string
  573. */
  574. public static function getProductTitle($cartId)
  575. {
  576. $title = '';
  577. try {
  578. $orderCart = StoreOrderCartInfo::where('cart_id', 'in', $cartId)->field('cart_info')->select();
  579. foreach ($orderCart as $item) {
  580. if (isset($item['cart_info']['productInfo']['store_name'])) {
  581. $title .= $item['cart_info']['productInfo']['store_name'] . '|';
  582. }
  583. }
  584. unset($item);
  585. if (!$title) {
  586. $productIds = StoreCart::where('id', 'in', $cartId)->column('product_id');
  587. $productlist = ($productlist = StoreProduct::getProductField($productIds, 'store_name')) ? $productlist->toArray() : [];
  588. foreach ($productlist as $item) {
  589. if (isset($item['store_name'])) $title .= $item['store_name'] . '|';
  590. }
  591. }
  592. if ($title) $title = substr($title, 0, strlen($title) - 1);
  593. unset($item);
  594. } catch (\Exception $e) {
  595. }
  596. return $title;
  597. }
  598. /**
  599. * 获取门店自提唯一核销码
  600. * @return bool|string
  601. */
  602. public static function getStoreCode()
  603. {
  604. list($msec, $sec) = explode(' ', microtime());
  605. $num = bcadd(time(), mt_rand(10, 999999), 0) . '' . substr($msec, 2, 3);//生成随机数
  606. if (strlen($num) < 12)
  607. $num = str_pad((string)$num, 12, 0, STR_PAD_RIGHT);
  608. else
  609. $num = substr($num, 0, 12);
  610. if (self::be(['verify_code' => $num])) return self::getStoreCode();
  611. return $num;
  612. }
  613. /**
  614. * 余额支付
  615. * @param $order_id
  616. * @param $uid
  617. * @param string $formId
  618. * @return bool
  619. * @throws \think\Exception
  620. * @throws DataNotFoundException
  621. * @throws ModelNotFoundException
  622. * @throws \think\exception\DbException
  623. */
  624. public static function yuePay($order_id, $uid, $formId = '')
  625. {
  626. $orderInfo = self::where('uid', $uid)->where('order_id', $order_id)->where('is_del', 0)->find();
  627. if (!$orderInfo) return self::setErrorInfo('订单不存在!');
  628. if ($orderInfo['paid']) return self::setErrorInfo('该订单已支付!');
  629. // if($orderInfo['pay_type'] != 'yue') return self::setErrorInfo('该订单不能使用余额支付!');
  630. $userInfo = User::getUserInfo($uid);
  631. if ($userInfo['now_money'] < $orderInfo['pay_price'])
  632. return self::setErrorInfo(['status' => 'pay_deficiency', 'msg' => '余额不足' . floatval($orderInfo['pay_price'])]);
  633. self::beginTrans();
  634. $res1 = false !== User::bcDec($uid, 'now_money', $orderInfo['pay_price'], 'uid');
  635. $res2 = UserBill::expend('购买商品', $uid, 'now_money', 'pay_product', $orderInfo['pay_price'], $orderInfo['id'], $userInfo['now_money'], '余额支付' . floatval($orderInfo['pay_price']) . '元购买商品');
  636. $res3 = self::paySuccess($order_id, 'yue', $formId);//余额支付成功
  637. try {
  638. PaymentRepositories::yuePayProduct($userInfo, $orderInfo);
  639. } catch (\Exception $e) {
  640. self::rollbackTrans();
  641. return self::setErrorInfo($e->getMessage());
  642. }
  643. $res = $res1 && $res2 && $res3;
  644. self::checkTrans($res);
  645. return $res;
  646. }
  647. /**
  648. * 微信支付 为 0元时
  649. * @param $order_id
  650. * @param $uid
  651. * @param string $formId
  652. * @return bool
  653. * @throws \think\Exception
  654. * @throws DataNotFoundException
  655. * @throws ModelNotFoundException
  656. * @throws \think\exception\DbException
  657. */
  658. public static function jsPayPrice($order_id, $uid, $formId = '')
  659. {
  660. $orderInfo = self::where('uid', $uid)->where('order_id', $order_id)->where('is_del', 0)->find();
  661. if (!$orderInfo) return self::setErrorInfo('订单不存在!');
  662. if ($orderInfo['paid']) return self::setErrorInfo('该订单已支付!');
  663. $userInfo = User::getUserInfo($uid);
  664. self::beginTrans();
  665. $res1 = UserBill::expend('购买商品', $uid, 'now_money', 'pay_product', $orderInfo['pay_price'], $orderInfo['id'], $userInfo['now_money'], '微信支付' . floatval($orderInfo['pay_price']) . '元购买商品');
  666. $res2 = self::paySuccess($order_id, 'weixin', $formId);//微信支付为0时
  667. $res = $res1 && $res2;
  668. self::checkTrans($res);
  669. return $res;
  670. }
  671. /**
  672. * 用户申请退款
  673. * @param $uni
  674. * @param $uid
  675. * @param string $refundReasonWap
  676. * @return bool
  677. */
  678. public static function orderApplyRefund($uni, $uid, $refundReasonWap = '', $refundReasonWapExplain = '', $refundReasonWapImg = [])
  679. {
  680. $order = self::getUserOrderDetail($uid, $uni);
  681. if (!$order) return self::setErrorInfo('支付订单不存在!');
  682. if ($order['refund_status'] == 2) return self::setErrorInfo('订单已退款!');
  683. if ($order['refund_status'] == 1) return self::setErrorInfo('正在申请退款中!');
  684. if ($order['status'] == 1) return self::setErrorInfo('订单当前无法退款!');
  685. self::beginTrans();
  686. $res1 = false !== StoreOrderStatus::status($order['id'], 'apply_refund', '用户申请退款,原因:' . $refundReasonWap);
  687. $res2 = false !== self::edit(['refund_status' => 1, 'refund_reason_time' => time(), 'refund_reason_wap' => $refundReasonWap, 'refund_reason_wap_explain' => $refundReasonWapExplain, 'refund_reason_wap_img' => json_encode($refundReasonWapImg)], $order['id'], 'id');
  688. $res = $res1 && $res2;
  689. self::checkTrans($res);
  690. if (!$res)
  691. return self::setErrorInfo('申请退款失败!');
  692. else {
  693. try {
  694. if (in_array($order['is_channel'], [0, 2])) {
  695. //公众号发送模板消息通知客服
  696. WechatTemplateService::sendAdminNoticeTemplate([
  697. 'first' => "亲,有个订单申请退款 \n订单号:{$order['order_id']}",
  698. 'keyword1' => '退款申请',
  699. 'keyword2' => '已支付',
  700. 'keyword3' => date('Y/m/d H:i', time()),
  701. 'remark' => '请及时处理'
  702. ]);
  703. }
  704. if (in_array($order['is_channel'], [1, 2])) {
  705. //小程序 发送模板消息
  706. RoutineTemplate::sendOrderRefundStatus($order, $refundReasonWap);
  707. }
  708. //通知后台消息提醒
  709. ChannelService::instance()->send('NEW_REFUND_ORDER', ['order_id' => $order['order_id']]);
  710. } catch (\Exception $e) {
  711. }
  712. //发送短信
  713. event('ShortMssageSend', [$order['order_id'], 'AdminRefund']);
  714. return true;
  715. }
  716. }
  717. /**
  718. * //TODO 支付成功后
  719. * @param $orderId
  720. * @param string $paytype
  721. * @param string $formId
  722. * @return bool
  723. * @throws DataNotFoundException
  724. * @throws DbException
  725. * @throws ModelNotFoundException
  726. */
  727. public static function paySuccess($orderId, $paytype = 'weixin', $formId = '')
  728. {
  729. $order = self::where('order_id', $orderId)->find();
  730. $resPink = true;
  731. $res1 = self::where('order_id', $orderId)->update(['paid' => 1, 'pay_type' => $paytype, 'pay_time' => time(), 'is_del' => 0, 'is_system_del' => 0, 'mark' => '']);//订单改为支付
  732. if ($order->combination_id && $res1 && !$order->refund_status) $resPink = StorePink::createPink($order);//创建拼团
  733. $oid = self::where('order_id', $orderId)->value('id');
  734. StoreOrderStatus::status($oid, 'pay_success', '用户付款成功');
  735. $now_money = User::where('uid', $order['uid'])->value('now_money');
  736. UserBill::expend('购买商品', $order['uid'], 'now_money', 'pay_money', $order['pay_price'], $order['id'], $now_money, '支付' . floatval($order['pay_price']) . '元购买商品');
  737. //支付成功后
  738. event('OrderPaySuccess', [$order, $formId]);
  739. self::push($order);
  740. $res = $res1 && $resPink && UserSpread::setSpreadSure($order['uid']) && User::backOrderBrokerage($order);
  741. return false !== $res;
  742. }
  743. /**
  744. * 直推奖励
  745. * @param $order
  746. * @return void
  747. */
  748. public static function push($order)
  749. {
  750. $user = User::where('uid', $order['uid'])->find();
  751. if ($user['spread_uid']){
  752. $spread = User::where('uid', $user['spread_uid'])->where('level', 2)->find();
  753. if ($spread){
  754. //直推上级是团队
  755. $group_purchase = sys_config('group_purchase');
  756. $jl = round($order['pay_price'] * ($group_purchase/100), 2);
  757. UserBill::income('佣金', $spread['uid'], 'now_money', 'brokerage', $jl, '', $spread['brokerage_price']+$jl, '直推佣金奖励');
  758. User::where('uid', $spread['uid'])->inc('brokerage_price', $jl)->update();
  759. }
  760. }
  761. }
  762. /*
  763. * 线下支付消息通知
  764. * 待完善
  765. *
  766. * */
  767. public static function createOrderTemplate($order)
  768. {
  769. //$goodsName = StoreOrderCartInfo::getProductNameList($order['id']);
  770. // RoutineTemplateService::sendTemplate(WechatUser::getOpenId($order['uid']),RoutineTemplateService::ORDER_CREATE, [
  771. // 'first'=>'亲,您购买的商品已支付成功',
  772. // 'keyword1'=>date('Y/m/d H:i',$order['add_time']),
  773. // 'keyword2'=>implode(',',$goodsName),
  774. // 'keyword3'=>$order['order_id'],
  775. // 'remark'=>'点击查看订单详情'
  776. // ],Url::build('/wap/My/order',['uni'=>$order['order_id']],true,true));
  777. // RoutineTemplateService::sendAdminNoticeTemplate([
  778. // 'first'=>"亲,您有一个新订单 \n订单号:{$order['order_id']}",
  779. // 'keyword1'=>'新订单',
  780. // 'keyword2'=>'线下支付',
  781. // 'keyword3'=>date('Y/m/d H:i',time()),
  782. // 'remark'=>'请及时处理'
  783. // ]);
  784. }
  785. /**
  786. * 获取订单详情
  787. * @param $uid
  788. * @param $key
  789. * @return array|\think\Model|null
  790. * @throws DataNotFoundException
  791. * @throws ModelNotFoundException
  792. * @throws \think\exception\DbException
  793. */
  794. public static function getUserOrderDetail($uid, $key)
  795. {
  796. return self::where('order_id|unique', $key)->where('uid', $uid)->where('is_del', 0)->find();
  797. }
  798. /**
  799. * TODO 订单发货
  800. * @param array $postageData 发货信息
  801. * @param string $oid orderID
  802. */
  803. public static function orderPostageAfter($postageData, $oid)
  804. {
  805. $order = self::where('id', $oid)->find();
  806. if ($postageData['delivery_type'] == 'send') {//送货
  807. RoutineTemplate::sendOrderPostage($order);
  808. } else if ($postageData['delivery_type'] == 'express') {//发货
  809. RoutineTemplate::sendOrderPostage($order, 1);
  810. }
  811. }
  812. /** 收货后发送模版消息
  813. * @param $order
  814. */
  815. public static function orderTakeAfter($order)
  816. {
  817. $title = self::getProductTitle($order['cart_id']);
  818. if ($order['is_channel'] == 1) {//小程序
  819. RoutineTemplate::sendOrderTakeOver($order, $title);
  820. } else {
  821. $openid = WechatUser::where('uid', $order['uid'])->value('openid');
  822. \crmeb\services\WechatTemplateService::sendTemplate($openid, \crmeb\services\WechatTemplateService::ORDER_TAKE_SUCCESS, [
  823. 'first' => '亲,您的订单已收货',
  824. 'keyword1' => $order['order_id'],
  825. 'keyword2' => '已收货',
  826. 'keyword3' => date('Y-m-d H:i:s', time()),
  827. 'keyword4' => $title,
  828. 'remark' => '感谢您的光临!'
  829. ]);
  830. }
  831. }
  832. /**
  833. * 删除订单
  834. * @param $uni
  835. * @param $uid
  836. * @return bool
  837. */
  838. public static function removeOrder($uni, $uid)
  839. {
  840. $order = self::getUserOrderDetail($uid, $uni);
  841. if (!$order) return self::setErrorInfo('订单不存在!');
  842. $order = self::tidyOrder($order);
  843. if ($order['_status']['_type'] != 0 && $order['_status']['_type'] != -2 && $order['_status']['_type'] != 4)
  844. return self::setErrorInfo('该订单无法删除!');
  845. if (false !== self::edit(['is_del' => 1], $order['id'], 'id') && false !== StoreOrderStatus::status($order['id'], 'remove_order', '删除订单')) {
  846. //未支付和已退款的状态下才可以退积分退库存退优惠券
  847. if ($order['_status']['_type'] == 0 || $order['_status']['_type'] == -2) {
  848. event('StoreOrderRegressionAllAfter', [$order]);
  849. }
  850. event('UserOrderRemoved', $uni);
  851. return true;
  852. } else
  853. return self::setErrorInfo('订单删除失败!');
  854. }
  855. /**
  856. * //TODO 用户确认收货
  857. * @param $uni
  858. * @param $uid
  859. */
  860. public static function takeOrder($uni, $uid)
  861. {
  862. $order = self::getUserOrderDetail($uid, $uni);
  863. if (!$order) return self::setErrorInfo('订单不存在!');
  864. $order = self::tidyOrder($order);
  865. if ($order['_status']['_type'] != 2) return self::setErrorInfo('订单状态错误!');
  866. self::beginTrans();
  867. if (false !== self::edit(['status' => 2], $order['id'], 'id') &&
  868. false !== StoreOrderStatus::status($order['id'], 'user_take_delivery', '用户已收货')) {
  869. try {
  870. OrderRepository::storeProductOrderUserTakeDelivery($order, $uid);
  871. UserBill::where('uid', $order['uid'])->where('link_id', $order['id'])->where('type', 'pay_money')->update(['take' => 1]);
  872. } catch (\Exception $e) {
  873. self::rollbackTrans();
  874. return self::setErrorInfo($e->getMessage());
  875. }
  876. self::cumulative($order);
  877. self::team($order);
  878. self::proxy($order);
  879. self::commitTrans();
  880. UserLevel::setLevelComplete($uid);
  881. event('UserLevelAfter', [User::get($uni)]);
  882. event('UserOrderTake', $uni);
  883. //短信通知
  884. event('ShortMssageSend', [$order['order_id'], ['Receiving', 'AdminConfirmTakeOver']]);
  885. return true;
  886. } else {
  887. self::rollbackTrans();
  888. return false;
  889. }
  890. }
  891. /**
  892. * 参与累计金额
  893. * @param $order
  894. * @return void
  895. */
  896. public static function cumulative($order)
  897. {
  898. User::where('uid', $order['uid'])->inc('pay_price', $order['pay_price'])->update();
  899. $user = User::where('uid', $order['uid'])->find();
  900. $partake = UserPartake::where('uid', $order['uid'])->where('status', 0)->find();
  901. if ($partake){
  902. $out = Out::where('id', $partake['out_id'])->find();
  903. if ($user['pay_price'] >= $out['number']){
  904. $user['pay_price'] -= $out['number'];
  905. $user['use_price'] += $out['number'];
  906. $user->save();
  907. $partake['status'] = 1;
  908. $partake['money'] = $out['number'];
  909. $partake->save();
  910. }
  911. }
  912. }
  913. /**
  914. * 发放团队奖励
  915. * @param $order
  916. * @return void
  917. */
  918. public static function team($order)
  919. {
  920. $user = User::where('uid', $order['uid'])->find();
  921. $uids = getParents($user['spread_uid'],User::select());
  922. if ($uids){
  923. $v1 = 0;//团队
  924. $v2 = 0;//联创
  925. $city = sys_config('city')/100;//城市比列
  926. $lianchuang = sys_config('lianchuang')/100;//联创比列
  927. foreach ($uids as $item)
  928. {
  929. $spread = User::where('uid', $item)->find();
  930. if ($spread['level'] == 3){
  931. if ($v1 == 0){
  932. $jl = $order['pay_price'] * $city;
  933. UserBill::income('佣金', $spread['uid'], 'now_money', 'brokerage', $jl, '', $spread['brokerage_price']+$jl, '下级消费'.$order['pay_price'].'城市合伙人团队佣金');
  934. User::where('uid', $spread['uid'])->inc('brokerage_price', $jl)->update();
  935. $v1++;
  936. }
  937. }
  938. if ($spread['level'] == 4){
  939. if ($v2 == 0){
  940. $jl = $order['pay_price'] * $lianchuang;
  941. UserBill::income('佣金', $spread['uid'], 'now_money', 'brokerage', $jl, '', $spread['brokerage_price']+$jl, '下级消费'.$order['pay_price'].'联创团队佣金');
  942. User::where('uid', $spread['uid'])->inc('brokerage_price', $jl)->update();
  943. $v2++;
  944. }
  945. }
  946. }
  947. }
  948. }
  949. /**
  950. * 发放落地奖励
  951. * @param $order
  952. * @param $uid
  953. * @return void
  954. */
  955. public static function proxy($order)
  956. {
  957. $address = explode(' ', $order['user_address']);
  958. $proxy = ProxyAddress::where(['province' => $address[0], 'city' => $address[1], 'district' => $address[2]])->select()->toArray();
  959. foreach ($proxy as $item)
  960. {
  961. $user = User::where('uid', $item['uid'])->find();
  962. if ($user['level'] == 3){
  963. $to_ground = sys_config('to_ground');
  964. $jl = $order['pay_price'] * ($to_ground/100);
  965. UserBill::income('佣金', $user['uid'], 'now_money', 'brokerage', $jl, '', $user['brokerage_price']+$jl, '落地奖励佣金');
  966. User::where('uid', $user['uid'])->inc('brokerage_price', $jl)->update();
  967. }
  968. }
  969. }
  970. /**
  971. * 获取订单状态购物车等信息
  972. * @param $order
  973. * @param bool $detail 是否获取订单购物车详情
  974. * @param bool $isPic 是否获取订单状态图片
  975. * @return mixed
  976. * @throws DataNotFoundException
  977. * @throws ModelNotFoundException
  978. * @throws \think\exception\DbException
  979. */
  980. public static function tidyOrder($order, $detail = false, $isPic = false)
  981. {
  982. if ($detail == true && isset($order['id'])) {
  983. $cartInfo = StoreOrderCartInfo::where('oid', $order['id'])->column('cart_info', 'unique') ?: [];
  984. $info = [];
  985. foreach ($cartInfo as $k => $cart) {
  986. $cart = json_decode($cart, true);
  987. $cart['unique'] = $k;
  988. //新增是否评价字段
  989. $cart['is_reply'] = StoreProductReply::where('unique', $k)->count();
  990. array_push($info, $cart);
  991. unset($cart);
  992. }
  993. $order['cartInfo'] = $info;
  994. }
  995. $status = [];
  996. if (!$order['paid'] && $order['pay_type'] == 'offline' && !$order['status'] >= 2) {
  997. $status['_type'] = 9;
  998. $status['_title'] = '线下付款';
  999. $status['_msg'] = '商家处理中,请耐心等待';
  1000. $status['_class'] = 'nobuy';
  1001. } else if (!$order['paid']) {
  1002. $status['_type'] = 0;
  1003. $status['_title'] = '未支付';
  1004. //系统预设取消订单时间段
  1005. $keyValue = ['order_cancel_time', 'order_activity_time', 'order_bargain_time', 'order_seckill_time', 'order_pink_time'];
  1006. //获取配置
  1007. $systemValue = SystemConfigService::more($keyValue);
  1008. //格式化数据
  1009. $systemValue = self::setValeTime($keyValue, is_array($systemValue) ? $systemValue : []);
  1010. if ($order['pink_id'] || $order['combination_id']) {
  1011. $order_pink_time = $systemValue['order_pink_time'] ? $systemValue['order_pink_time'] : $systemValue['order_activity_time'];
  1012. $time = bcadd($order['add_time'], $order_pink_time * 3600, 0);
  1013. $status['_msg'] = '请在' . date('m-d H:i:s', $time) . '前完成支付!';
  1014. } else if ($order['seckill_id']) {
  1015. $order_seckill_time = $systemValue['order_seckill_time'] ? $systemValue['order_seckill_time'] : $systemValue['order_activity_time'];
  1016. $time = bcadd($order['add_time'], $order_seckill_time * 3600, 0);
  1017. $status['_msg'] = '请在' . date('m-d H:i:s', $time) . '前完成支付!';
  1018. } else if ($order['bargain_id']) {
  1019. $order_bargain_time = $systemValue['order_bargain_time'] ? $systemValue['order_bargain_time'] : $systemValue['order_activity_time'];
  1020. $time = bcadd($order['add_time'], $order_bargain_time * 3600, 0);
  1021. $status['_msg'] = '请在' . date('m-d H:i:s', $time) . '前完成支付!';
  1022. } else {
  1023. $time = bcadd($order['add_time'], $systemValue['order_cancel_time'] * 3600, 0);
  1024. $status['_msg'] = '请在' . date('m-d H:i:s', $time) . '前完成支付!';
  1025. }
  1026. $status['_class'] = 'nobuy';
  1027. } else if ($order['refund_status'] == 1) {
  1028. $status['_type'] = -1;
  1029. $status['_title'] = '申请退款中';
  1030. $status['_msg'] = '商家审核中,请耐心等待';
  1031. $status['_class'] = 'state-sqtk';
  1032. } else if ($order['refund_status'] == 2) {
  1033. $status['_type'] = -2;
  1034. $status['_title'] = '已退款';
  1035. $status['_msg'] = '已为您退款,感谢您的支持';
  1036. $status['_class'] = 'state-sqtk';
  1037. } else if (!$order['status']) {
  1038. if ($order['pink_id']) {
  1039. if (StorePink::where('id', $order['pink_id'])->where('status', 1)->count()) {
  1040. $status['_type'] = 1;
  1041. $status['_title'] = '拼团中';
  1042. $status['_msg'] = '等待其他人参加拼团';
  1043. $status['_class'] = 'state-nfh';
  1044. } else {
  1045. $status['_type'] = 1;
  1046. $status['_title'] = '未发货';
  1047. $status['_msg'] = '商家未发货,请耐心等待';
  1048. $status['_class'] = 'state-nfh';
  1049. }
  1050. } else {
  1051. if ($order['shipping_type'] === 1) {
  1052. $status['_type'] = 1;
  1053. $status['_title'] = '未发货';
  1054. $status['_msg'] = '商家未发货,请耐心等待';
  1055. $status['_class'] = 'state-nfh';
  1056. } else {
  1057. $status['_type'] = 1;
  1058. $status['_title'] = '待核销';
  1059. $status['_msg'] = '待核销,请到核销点进行核销';
  1060. $status['_class'] = 'state-nfh';
  1061. }
  1062. }
  1063. } else if ($order['status'] == 1) {
  1064. if ($order['delivery_type'] == 'send') {//TODO 送货
  1065. $status['_type'] = 2;
  1066. $status['_title'] = '待收货';
  1067. $status['_msg'] = date('m月d日H时i分', StoreOrderStatus::getTime($order['id'], 'delivery')) . '服务商已送货';
  1068. $status['_class'] = 'state-ysh';
  1069. } else {//TODO 发货
  1070. $status['_type'] = 2;
  1071. $status['_title'] = '待收货';
  1072. if ($order['delivery_type'] == 'fictitious')
  1073. $_time = StoreOrderStatus::getTime($order['id'], 'delivery_fictitious');
  1074. else
  1075. $_time = StoreOrderStatus::getTime($order['id'], 'delivery_goods');
  1076. $status['_msg'] = date('m月d日H时i分', $_time) . '服务商已发货';
  1077. $status['_class'] = 'state-ysh';
  1078. }
  1079. } else if ($order['status'] == 2) {
  1080. $status['_type'] = 3;
  1081. $status['_title'] = '待评价';
  1082. $status['_msg'] = '已收货,快去评价一下吧';
  1083. $status['_class'] = 'state-ypj';
  1084. } else if ($order['status'] == 3) {
  1085. $status['_type'] = 4;
  1086. $status['_title'] = '交易完成';
  1087. $status['_msg'] = '交易完成,感谢您的支持';
  1088. $status['_class'] = 'state-ytk';
  1089. }
  1090. if (isset($order['pay_type']))
  1091. $status['_payType'] = isset(self::$payType[$order['pay_type']]) ? self::$payType[$order['pay_type']] : '其他方式';
  1092. if (isset($order['delivery_type']))
  1093. $status['_deliveryType'] = isset(self::$deliveryType[$order['delivery_type']]) ? self::$deliveryType[$order['delivery_type']] : '其他方式';
  1094. $order['_status'] = $status;
  1095. $order['_pay_time'] = isset($order['pay_time']) && $order['pay_time'] != null ? date('Y-m-d H:i:s', $order['pay_time']) : date('Y-m-d H:i:s', $order['add_time']);
  1096. $order['_add_time'] = isset($order['add_time']) ? (strstr($order['add_time'], '-') === false ? date('Y-m-d H:i:s', $order['add_time']) : $order['add_time']) : '';
  1097. $order['status_pic'] = '';
  1098. //获取产品状态图片
  1099. if ($isPic) {
  1100. $order_details_images = sys_data('order_details_images') ?: [];
  1101. foreach ($order_details_images as $image) {
  1102. if (isset($image['order_status']) && $image['order_status'] == $order['_status']['_type']) {
  1103. $order['status_pic'] = $image['pic'];
  1104. break;
  1105. }
  1106. }
  1107. }
  1108. $order['offlinePayStatus'] = (int)sys_config('offline_pay_status') ?? (int)2;
  1109. return $order;
  1110. }
  1111. /**
  1112. * 设置订单查询状态
  1113. * @param $status
  1114. * @param int $uid
  1115. * @param null $model
  1116. * @return StoreOrder|null
  1117. */
  1118. public static function statusByWhere($status, $uid = 0, $model = null)
  1119. {
  1120. // $orderId = StorePink::where('uid',$uid)->where('status',1)->column('order_id','id');//获取正在拼团的订单编号
  1121. if ($model == null) $model = new self;
  1122. if ('' === $status)
  1123. return $model;
  1124. else if ($status == 0)//未支付
  1125. return $model->where('paid', 0)->where('status', 0)->where('refund_status', 0);
  1126. else if ($status == 1)//待发货
  1127. return $model->where('paid', 1)->where('status', 0)->where('refund_status', 0);
  1128. else if ($status == 2)//待收货
  1129. return $model->where('paid', 1)->where('status', 1)->where('refund_status', 0);
  1130. else if ($status == 3)//待评价
  1131. return $model->where('paid', 1)->where('status', 2)->where('refund_status', 0);
  1132. else if ($status == 4)//已完成
  1133. return $model->where('paid', 1)->where('status', 3)->where('refund_status', 0);
  1134. else if ($status == -1)//退款中
  1135. return $model->where('paid', 1)->where('refund_status', 1);
  1136. else if ($status == -2)//已退款
  1137. return $model->where('paid', 1)->where('refund_status', 2);
  1138. else if ($status == -3)//退款
  1139. return $model->where('paid', 1)->where('refund_status', 'IN', '1,2');
  1140. // else if($status == 11){
  1141. // return $model->where('order_id','IN',implode(',',$orderId));
  1142. // }
  1143. else
  1144. return $model;
  1145. }
  1146. /**
  1147. * 获取订单并分页
  1148. * @param $uid
  1149. * @param string $status
  1150. * @param int $page
  1151. * @param int $limit
  1152. * @return mixed
  1153. * @throws DataNotFoundException
  1154. * @throws ModelNotFoundException
  1155. * @throws \think\exception\DbException
  1156. */
  1157. public static function getUserOrderList($uid, $status = '', $page = 0, $limit = 8)
  1158. {
  1159. if ($page) $list = self::statusByWhere($status, $uid)->where('is_del', 0)->where('uid', $uid)
  1160. ->field('add_time,seckill_id,bargain_id,combination_id,id,order_id,pay_price,total_num,total_price,pay_postage,total_postage,paid,status,refund_status,pay_type,coupon_price,deduction_price,pink_id,delivery_type,is_del,shipping_type')
  1161. ->order('add_time DESC')->page((int)$page, (int)$limit)->select()->toArray();
  1162. else $list = self::statusByWhere($status, $uid)->where('is_del', 0)->where('uid', $uid)
  1163. ->field('add_time,seckill_id,bargain_id,combination_id,id,order_id,pay_price,total_num,total_price,pay_postage,total_postage,paid,status,refund_status,pay_type,coupon_price,deduction_price,pink_id,delivery_type,is_del,shipping_type')
  1164. ->order('add_time DESC')->page((int)$page, (int)$limit)->select()->toArray();
  1165. foreach ($list as $k => $order) {
  1166. $list[$k] = self::tidyOrder($order, true);
  1167. }
  1168. return $list;
  1169. }
  1170. /**
  1171. * 获取推广人地下用户的订单金额
  1172. * @param string $uid
  1173. * @param string $status
  1174. * @return array
  1175. */
  1176. public static function getUserOrderCount($uid = '', $status = '')
  1177. {
  1178. $res = self::statusByWhere($status, $uid)->where('uid', 'IN', $uid)->column('pay_price');
  1179. return $res;
  1180. }
  1181. /**
  1182. * 搜索某个订单详细信息
  1183. * @param $uid
  1184. * @param $order_id
  1185. * @return bool|mixed
  1186. * @throws DataNotFoundException
  1187. * @throws ModelNotFoundException
  1188. * @throws \think\exception\DbException
  1189. */
  1190. public static function searchUserOrder($uid, $order_id)
  1191. {
  1192. $order = self::where('uid', $uid)->where('order_id', $order_id)->where('is_del', 0)->field('seckill_id,bargain_id,combination_id,id,order_id,pay_price,total_num,total_price,pay_postage,total_postage,paid,status,refund_status,pay_type,coupon_price,deduction_price,delivery_type,shipping_type')
  1193. ->order('add_time DESC')->find();
  1194. if (!$order)
  1195. return false;
  1196. else
  1197. return self::tidyOrder($order->toArray(), true);
  1198. }
  1199. /**
  1200. * 订单评价信息记录
  1201. * @param $oid
  1202. * @return StoreOrderStatus|\think\Model
  1203. * @throws \Exception
  1204. */
  1205. public static function orderOver($oid)
  1206. {
  1207. $res = self::edit(['status' => '3'], $oid, 'id');
  1208. if (!$res) exception('评价后置操作失败!');
  1209. return StoreOrderStatus::status($oid, 'check_order_over', '用户评价');
  1210. }
  1211. /**
  1212. * 设置订单产品评价完毕事件
  1213. * @param $oid
  1214. * @return StoreOrderStatus|\think\Model
  1215. * @throws \Exception
  1216. */
  1217. public static function checkOrderOver($oid)
  1218. {
  1219. $uniqueList = StoreOrderCartInfo::where('oid', $oid)->column('unique', 'unique');
  1220. //订单产品全部评价完成
  1221. if (StoreProductReply::where('unique', 'IN', $uniqueList)->where('oid', $oid)->count() == count($uniqueList)) {
  1222. event('StoreProductOrderOver', [$oid]);
  1223. return self::orderOver($oid);
  1224. }
  1225. }
  1226. public static function getOrderStatusNum($uid)
  1227. {
  1228. $noBuy = (int)self::where('uid', $uid)->where('paid', 0)->where('is_del', 0)->where('pay_type', '<>', 'offline')->count();
  1229. $noPostageNoPink = (int)self::where('o.uid', $uid)->alias('o')->where('o.paid', 1)->where('o.pink_id', 0)->where('o.is_del', 0)->where('o.status', 0)->where('o.pay_type', '<>', 'offline')->count();
  1230. $noPostageYesPink = (int)self::where('o.uid', $uid)->alias('o')->join('StorePink p', 'o.pink_id = p.id')->where('p.status', 2)->where('o.paid', 1)->where('o.is_del', 0)->where('o.status', 0)->where('o.pay_type', '<>', 'offline')->count();
  1231. $noPostage = (int)bcadd($noPostageNoPink, $noPostageYesPink, 0);
  1232. $noTake = (int)self::where('uid', $uid)->where('paid', 1)->where('is_del', 0)->where('status', 1)->where('pay_type', '<>', 'offline')->count();
  1233. $noReply = (int)self::where('uid', $uid)->where('paid', 1)->where('is_del', 0)->where('status', 2)->count();
  1234. $noPink = (int)self::where('o.uid', $uid)->alias('o')->join('StorePink p', 'o.pink_id = p.id')->where('p.status', 1)->where('o.paid', 1)->where('o.is_del', 0)->where('o.status', 0)->where('o.pay_type', '<>', 'offline')->count();
  1235. $noRefund = (int)self::where('uid', $uid)->where('paid', 1)->where('is_del', 0)->where('refund_status', 'IN', '1,2')->count();
  1236. return compact('noBuy', 'noPostage', 'noTake', 'noReply', 'noPink', 'noRefund');
  1237. }
  1238. /**
  1239. * 购买商品赠送积分
  1240. * @param $order
  1241. * @return bool
  1242. * @throws \think\Exception
  1243. * @throws DataNotFoundException
  1244. * @throws ModelNotFoundException
  1245. * @throws \think\exception\DbException
  1246. */
  1247. public static function gainUserIntegral($order)
  1248. {
  1249. if ($order['gain_integral'] > 0) {
  1250. $userInfo = User::getUserInfo($order['uid']);
  1251. BaseModel::beginTrans();
  1252. $res1 = false != User::where('uid', $userInfo['uid'])->update(['integral' => bcadd($userInfo['integral'], $order['gain_integral'], 2)]);
  1253. $res2 = false != UserBill::income('购买商品赠送积分', $order['uid'], 'integral', 'gain', $order['gain_integral'], $order['id'], $userInfo['integral'], '购买商品赠送' . floatval($order['gain_integral']) . '积分');
  1254. $res = $res1 && $res2;
  1255. BaseModel::checkTrans($res);
  1256. return $res;
  1257. }
  1258. return true;
  1259. }
  1260. /**
  1261. * 获取当前订单中有没有拼团存在
  1262. * @param $pid
  1263. * @return int|string
  1264. */
  1265. public static function getIsOrderPink($pid = 0, $uid = 0)
  1266. {
  1267. return self::where('uid', $uid)->where('pink_id', $pid)->where('refund_status', 0)->where('is_del', 0)->count();
  1268. }
  1269. /**
  1270. * 获取order_id
  1271. * @param $pid
  1272. * @return mixed
  1273. */
  1274. public static function getStoreIdPink($pid = 0, $uid = 0)
  1275. {
  1276. return self::where('uid', $uid)->where('pink_id', $pid)->where('is_del', 0)->value('order_id');
  1277. }
  1278. /**
  1279. * 删除当前用户拼团未支付的订单
  1280. */
  1281. public static function delCombination()
  1282. {
  1283. self::where('combination', '>', 0)->where('paid', 0)->where('uid', User::getActiveUid())->delete();
  1284. }
  1285. public static function getUserPrice($uid = 0)
  1286. {
  1287. if (!$uid) return 0;
  1288. $price = self::where('paid', 1)->where('uid', $uid)->where('status', 2)->where('refund_status', 0)->column('pay_price', 'id');
  1289. $count = 0;
  1290. if ($price) {
  1291. foreach ($price as $v) {
  1292. $count = bcadd($count, $v, 2);
  1293. }
  1294. }
  1295. return $count;
  1296. }
  1297. /**
  1298. * 个人中心获取个人订单列表和订单搜索
  1299. * @param int $uid 用户uid
  1300. * @param int | string 查找订单类型
  1301. * @param int $first 分页
  1302. * @param int 每页显示多少条
  1303. * @param string $search 订单号
  1304. * @return array
  1305. * */
  1306. public static function getUserOrderSearchList($uid, $type, $page, $limit, $search)
  1307. {
  1308. if ($search) {
  1309. $order = self::searchUserOrder($uid, $search) ?: [];
  1310. $list = $order == false ? [] : [$order];
  1311. } else {
  1312. $list = self::getUserOrderList($uid, $type, $page, $limit);
  1313. }
  1314. foreach ($list as $k => $order) {
  1315. $list[$k] = self::tidyOrder($order, true);
  1316. if ($list[$k]['_status']['_type'] == 3) {
  1317. foreach ($order['cartInfo'] ?: [] as $key => $product) {
  1318. $list[$k]['cartInfo'][$key]['is_reply'] = StoreProductReply::isReply($product['unique'], 'product');
  1319. $list[$k]['cartInfo'][$key]['add_time'] = isset($product['add_time']) ? date('Y-m-d H:i', $product['add_time']) : '时间错误';
  1320. }
  1321. }
  1322. }
  1323. return $list;
  1324. }
  1325. /**
  1326. * 获取用户下级的订单
  1327. * @param int $xuid 下级用户用户uid
  1328. * @param int $uid 用户uid
  1329. * @param int $type 订单类型
  1330. * @param int $first 截取行数
  1331. * @param int $limit 展示条数
  1332. * @return array
  1333. * */
  1334. public static function getSubordinateOrderlist($xUid, $uid, $type, $first, $limit)
  1335. {
  1336. $list = [];
  1337. if (!$xUid) {
  1338. $arr = User::getOneSpreadUid($uid);
  1339. foreach ($arr as $v) $list = StoreOrder::getUserOrderList($v, $type, $first, $limit);
  1340. } else $list = self::getUserOrderList($xUid, $type, $first, $limit);
  1341. foreach ($list as $k => $order) {
  1342. $list[$k] = self::tidyOrder($order, true);
  1343. if ($list[$k]['_status']['_type'] == 3) {
  1344. foreach ($order['cartInfo'] ?: [] as $key => $product) {
  1345. $list[$k]['cartInfo'][$key]['is_reply'] = StoreProductReply::isReply($product['unique'], 'product');
  1346. }
  1347. }
  1348. }
  1349. return $list;
  1350. }
  1351. /**
  1352. * 获取 今日 昨日 本月 订单金额
  1353. * @return mixed
  1354. */
  1355. public static function getOrderTimeData()
  1356. {
  1357. $to_day = strtotime(date('Y-m-d'));//今日
  1358. $pre_day = strtotime(date('Y-m-d', strtotime('-1 day')));//昨日
  1359. $now_month = strtotime(date('Y-m'));//本月
  1360. //今日成交额
  1361. // $data['todayPrice'] = (float)number_format(self::where('is_del', 0)->where('pay_time', '>=', $to_day)->where('paid', 1)->where('refund_status', 0)->value('sum(pay_price)'), 2) ?? 0;
  1362. $data['todayPrice'] = number_format(self::where('is_del', 0)->where('pay_time', '>=', $to_day)->where('paid', 1)->where('refund_status', 0)->value('sum(pay_price)'), 2) ?? 0;
  1363. //今日订单数
  1364. $data['todayCount'] = self::where('is_del', 0)->where('pay_time', '>=', $to_day)->where('paid', 1)->where('refund_status', 0)->count();
  1365. //昨日成交额
  1366. $data['proPrice'] = number_format(self::where('is_del', 0)->where('pay_time', '<', $to_day)->where('pay_time', '>=', $pre_day)->where('paid', 1)->where('refund_status', 0)->value('sum(pay_price)'), 2) ?? 0;
  1367. //昨日订单数
  1368. $data['proCount'] = self::where('is_del', 0)->where('pay_time', '<', $to_day)->where('pay_time', '>=', $pre_day)->where('paid', 1)->where('refund_status', 0)->count();
  1369. //本月成交额
  1370. $data['monthPrice'] = number_format(self::where('is_del', 0)->where('pay_time', '>=', $now_month)->where('paid', 1)->where('refund_status', 0)->value('sum(pay_price)'), 2) ?? 0;
  1371. //本月订单数
  1372. $data['monthCount'] = self::where('is_del', 0)->where('pay_time', '>=', $now_month)->where('paid', 1)->where('refund_status', 0)->count();
  1373. return $data;
  1374. }
  1375. /**
  1376. * 获取某个用户的订单统计数据
  1377. * @param $uid
  1378. * @return mixed
  1379. */
  1380. public static function getOrderData($uid)
  1381. {
  1382. //订单支付没有退款 数量
  1383. $data['order_count'] = self::where('is_del', 0)->where('paid', 1)->where('uid', $uid)->where('refund_status', 0)->count();
  1384. //订单支付没有退款 支付总金额
  1385. $data['sum_price'] = self::where('is_del', 0)->where('paid', 1)->where('uid', $uid)->where('refund_status', 0)->sum('pay_price');
  1386. //订单待支付 数量
  1387. $data['unpaid_count'] = self::statusByWhere(0, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1388. //订单待发货 数量
  1389. $data['unshipped_count'] = self::statusByWhere(1, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1390. //订单待收货 数量
  1391. $data['received_count'] = self::statusByWhere(2, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1392. //订单待评价 数量
  1393. $data['evaluated_count'] = self::statusByWhere(3, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1394. //订单已完成 数量
  1395. $data['complete_count'] = self::statusByWhere(4, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1396. //订单退款
  1397. $data['refund_count'] = self::statusByWhere(-1, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1398. return $data;
  1399. }
  1400. /**
  1401. * 获取订单统计数据
  1402. * @param $uid
  1403. * @return mixed
  1404. */
  1405. public static function getOrderDataAdmin()
  1406. {
  1407. //订单支付没有退款 数量
  1408. $data['order_count'] = self::where('is_del', 0)->where('paid', 1)->where('refund_status', 0)->count();
  1409. //订单支付没有退款 支付总金额
  1410. $data['sum_price'] = self::where('is_del', 0)->where('paid', 1)->where('refund_status', 0)->sum('pay_price');
  1411. //订单待支付 数量
  1412. $data['unpaid_count'] = self::statusByWhere(0, 0)->where('is_del', 0)->count();
  1413. //订单待发货 数量
  1414. $data['unshipped_count'] = self::statusByWhere(1, 0)->where('is_del', 0)->count();
  1415. //订单待收货 数量
  1416. $data['received_count'] = self::statusByWhere(2, 0)->where('is_del', 0)->count();
  1417. //订单待评价 数量
  1418. $data['evaluated_count'] = self::statusByWhere(3, 0)->where('is_del', 0)->count();
  1419. //订单已完成 数量
  1420. $data['complete_count'] = self::statusByWhere(4, 0)->where('is_del', 0)->count();
  1421. //订单退款 数量
  1422. $data['refund_count'] = self::statusByWhere(-3, 0)->where('is_del', 0)->count();
  1423. return $data;
  1424. }
  1425. /**
  1426. * 累计消费
  1427. * @param $uid
  1428. * @return float
  1429. */
  1430. public static function getOrderStatusSum($uid)
  1431. {
  1432. return self::where('uid', $uid)->where('is_del', 0)->where('paid', 1)->sum('pay_price');
  1433. }
  1434. public static function getPinkOrderId($id)
  1435. {
  1436. return self::where('id', $id)->value('order_id');
  1437. }
  1438. /**
  1439. * 未支付订单自动取消
  1440. * @param int $limit 分页截取条数
  1441. * @param string $prefid 缓存名称
  1442. * @param int $expire 缓存时间
  1443. * @return string|null
  1444. * @throws \Psr\SimpleCache\InvalidArgumentException
  1445. */
  1446. public static function orderUnpaidCancel()
  1447. {
  1448. //系统预设取消订单时间段
  1449. $keyValue = ['order_cancel_time', 'order_activity_time', 'order_bargain_time', 'order_seckill_time', 'order_pink_time'];
  1450. //获取配置
  1451. $systemValue = SystemConfigService::more($keyValue);
  1452. //格式化数据
  1453. $systemValue = self::setValeTime($keyValue, is_array($systemValue) ? $systemValue : []);
  1454. //检查是否有未支付的订单 未支付查询条件
  1455. $unPidCount = self::where('paid', 0)->where('pay_type', '<>', 'offline')->where('is_del', 0)->where('status', 0)->where('refund_status', 0)->count();
  1456. if (!$unPidCount) return null;
  1457. try {
  1458. $res = true;
  1459. // 未支付查询条件
  1460. $orderList = self::where('paid', 0)->where('pay_type', '<>', 'offline')->where('is_del', 0)->where('status', 0)->where('refund_status', 0)->field('add_time,pink_id,order_id,seckill_id,bargain_id,combination_id,status,cart_id,use_integral,refund_status,uid,unique,back_integral,coupon_id,paid,is_del')->select();
  1461. foreach ($orderList as $order) {
  1462. if ($order['seckill_id']) {
  1463. //优先使用单独配置的过期时间
  1464. $order_seckill_time = $systemValue['order_seckill_time'] ? $systemValue['order_seckill_time'] : $systemValue['order_activity_time'];
  1465. $res = $res && self::RegressionAll($order_seckill_time, $order);
  1466. unset($order_seckill_time);
  1467. } else if ($order['bargain_id']) {
  1468. $order_bargain_time = $systemValue['order_bargain_time'] ? $systemValue['order_bargain_time'] : $systemValue['order_activity_time'];
  1469. $res = $res && self::RegressionAll($order_bargain_time, $order);
  1470. unset($order_bargain_time);
  1471. } else if ($order['pink_id'] || $order['combination_id']) {
  1472. $order_pink_time = $systemValue['order_pink_time'] ? $systemValue['order_pink_time'] : $systemValue['order_activity_time'];
  1473. $res = $res && self::RegressionAll($order_pink_time, $order);
  1474. unset($order_pink_time);
  1475. } else {
  1476. $res = $res && self::RegressionAll($systemValue['order_cancel_time'], $order);
  1477. }
  1478. }
  1479. if (!$res) throw new \Exception('更新错误');
  1480. unset($orderList, $res, $pages);
  1481. return null;
  1482. } catch (PDOException $e) {
  1483. Log::error('未支付自动取消时发生数据库查询错误,错误原因为:' . $e->getMessage());
  1484. throw new \Exception($e->getMessage());
  1485. } catch (\think\Exception $e) {
  1486. Log::error('未支付自动取消时发生系统错误,错误原因为:' . $e->getMessage());
  1487. throw new \Exception($e->getMessage());
  1488. }
  1489. }
  1490. /**
  1491. * 未支付订单超过预设时间回退所有,如果不设置未支付过期时间,将不取消订单
  1492. * @param $time 预设时间
  1493. * @param $order 订单详情
  1494. * @return bool
  1495. * @throws DataNotFoundException
  1496. * @throws ModelNotFoundException
  1497. * @throws \think\exception\DbException
  1498. */
  1499. protected static function RegressionAll($time, $order)
  1500. {
  1501. if ($time == 0) return true;
  1502. if (($order['add_time'] + bcmul($time, 3600, 0)) < time()) {
  1503. $res1 = self::RegressionStock($order);
  1504. $res2 = self::RegressionIntegral($order);
  1505. $res3 = self::RegressionCoupon($order);
  1506. $res = $res1 && $res2 && $res3;
  1507. if ($res) $res = false !== self::where('order_id', $order['order_id'])->update(['is_del' => 1, 'mark' => '订单未支付已超过系统预设时间']);
  1508. unset($res1, $res2, $res3);
  1509. return $res;
  1510. } else
  1511. return true;
  1512. }
  1513. /**
  1514. * 格式化数据
  1515. * @param array $array 原本数据键
  1516. * @param $value 需要格式化的数据
  1517. * @param int $default 默认值
  1518. * @return mixed
  1519. */
  1520. protected static function setValeTime(array $array, $value, $default = 0)
  1521. {
  1522. foreach ($array as $item) {
  1523. if (!isset($value[$item]))
  1524. $value[$item] = $default;
  1525. else if (is_string($value[$item]))
  1526. $value[$item] = (float)$value[$item];
  1527. }
  1528. return $value;
  1529. }
  1530. public static function getOrderTotalPrice($cartInfo)
  1531. {
  1532. $totalPrice = 0;
  1533. foreach ($cartInfo as $cart) {
  1534. $totalPrice = bcadd($totalPrice, bcmul($cart['cart_num'], $cart['truePrice'], 2), 2);
  1535. }
  1536. return $totalPrice;
  1537. }
  1538. public static function getOrderCostPrice($cartInfo)
  1539. {
  1540. $costPrice = 0;
  1541. foreach ($cartInfo as $cart) {
  1542. $costPrice = bcadd($costPrice, bcmul($cart['cart_num'], $cart['costPrice'], 2), 2);
  1543. }
  1544. return $costPrice;
  1545. }
  1546. public static function getCombinationOrderCostPrice($cartInfo)
  1547. {
  1548. $costPrice = 0;
  1549. foreach ($cartInfo as $cart) {
  1550. if ($cart['combination_id']) {
  1551. $costPrice = bcadd($costPrice, bcmul($cart['cart_num'], StoreCombination::where('id', $cart['combination_id'])->value('price'), 2), 2);
  1552. }
  1553. }
  1554. return (float)$costPrice;
  1555. }
  1556. public static function yueRefundAfter($order)
  1557. {
  1558. }
  1559. /**
  1560. * 获取余额支付的金额
  1561. * @param $uid
  1562. * @return float|int
  1563. */
  1564. public static function getOrderStatusYueSum($uid)
  1565. {
  1566. return self::where('uid', $uid)->where('is_del', 0)->where('is_del', 0)->where('pay_type', 'yue')->where('paid', 1)->sum('pay_price');
  1567. }
  1568. /**
  1569. * 砍价支付成功订单数量
  1570. * @param $bargain
  1571. * @return int
  1572. */
  1573. public static function getBargainPayCount($bargain)
  1574. {
  1575. return self::where('bargain_id', $bargain)->where(['paid' => 1, 'refund_status' => 0])->count();
  1576. }
  1577. /**
  1578. * 7天自动收货
  1579. * @return bool
  1580. */
  1581. public static function startTakeOrder()
  1582. {
  1583. //7天前时间戳
  1584. $systemDeliveryTime = SystemConfigService::get('system_delivery_time') ?? 0;
  1585. //0为取消自动收货功能
  1586. if ($systemDeliveryTime == 0) return true;
  1587. $sevenDay = strtotime(date('Y-m-d H:i:s', strtotime('-' . $systemDeliveryTime . ' day')));
  1588. $model = new self;
  1589. $model = $model->alias('o');
  1590. $model = $model->join('StoreOrderStatus s', 's.oid=o.id');
  1591. $model = $model->where('o.paid', 1);
  1592. $model = $model->where('s.change_type', 'delivery_goods');
  1593. $model = $model->where('s.change_time', '<', $sevenDay);
  1594. $model = $model->where('o.status', 1);
  1595. $model = $model->where('o.refund_status', 0);
  1596. $model = $model->where('o.is_del', 0);
  1597. $orderInfo = $model->column('id', 'id');
  1598. if (!count($orderInfo)) return true;
  1599. $res = true;
  1600. foreach ($orderInfo as $key => &$item) {
  1601. $order = self::get($item);
  1602. if ($order['status'] == 2) continue;
  1603. if ($order['paid'] == 1 && $order['status'] == 1) $data['status'] = 2;
  1604. else if ($order['pay_type'] == 'offline') $data['status'] = 2;
  1605. else continue;
  1606. if (!self::edit($data, $item, 'id')) continue;
  1607. try {
  1608. OrderRepository::storeProductOrderTakeDeliveryAdmin($order, $item);
  1609. $res = $res && true;
  1610. } catch (\Exception $e) {
  1611. $res = $res && false;
  1612. }
  1613. $res = $res && StoreOrderStatus::status($item, 'take_delivery', '已收货[自动收货]');
  1614. }
  1615. if (!$res) {
  1616. throw new \Exception('');
  1617. }
  1618. }
  1619. /**
  1620. * 获取订单信息
  1621. * @param $id
  1622. * @param string $field
  1623. * @return array|null|\think\Model
  1624. * @throws DataNotFoundException
  1625. * @throws ModelNotFoundException
  1626. * @throws \think\exception\DbException
  1627. */
  1628. public static function getOrderInfo($id, $field = 'order_id')
  1629. {
  1630. return self::where('id', $id)->field($field)->find();
  1631. }
  1632. /**
  1633. * 订单每月统计数据
  1634. * @param $page
  1635. * @param $limit
  1636. * @return array
  1637. */
  1638. public static function getOrderDataPriceCount($page, $limit, $start, $stop)
  1639. {
  1640. if (!$limit) return [];
  1641. $model = new self;
  1642. if ($start != '' && $stop != '') $model = $model->where('pay_time', '>', $start)->where('pay_time', '<=', $stop);
  1643. $model = $model->field('sum(pay_price) as price,count(id) as count,FROM_UNIXTIME(pay_time, \'%m-%d\') as time');
  1644. $model = $model->where('is_del', 0);
  1645. $model = $model->where('paid', 1);
  1646. $model = $model->where('refund_status', 0);
  1647. $model = $model->group("FROM_UNIXTIME(pay_time, '%Y-%m-%d')");
  1648. $model = $model->order('pay_time DESC');
  1649. if ($page) $model = $model->page($page, $limit);
  1650. return $model->select();
  1651. }
  1652. /**
  1653. * 前台订单管理订单列表获取
  1654. * @param $where
  1655. * @return mixed
  1656. */
  1657. public static function orderList($where)
  1658. {
  1659. $model = self::getOrderWhere($where, self::alias('a')->join('user r', 'r.uid=a.uid', 'LEFT'), 'a.', 'r')->field('a.id,a.order_id,a.add_time,a.status,a.total_num,a.total_price,a.total_postage,a.pay_price,a.pay_postage,a.paid,a.refund_status,a.remark,a.pay_type');
  1660. if ($where['order'] != '') {
  1661. $model = $model->order(self::setOrder($where['order']));
  1662. } else {
  1663. $model = $model->order('a.id desc');
  1664. }
  1665. $data = ($data = $model->page((int)$where['page'], (int)$where['limit'])->select()) && count($data) ? $data->toArray() : [];
  1666. return self::tidyAdminOrder($data);
  1667. }
  1668. /**
  1669. * 前台订单管理 订单信息设置
  1670. * @param $data
  1671. * @param bool $status
  1672. * @return mixed
  1673. * @throws DataNotFoundException
  1674. * @throws ModelNotFoundException
  1675. * @throws \think\exception\DbException
  1676. */
  1677. public static function tidyAdminOrder($data, $status = false)
  1678. {
  1679. foreach ($data as &$item) {
  1680. $_info = StoreOrderCartInfo::where('oid', $item['id'])->field('cart_info')->select()->toArray();
  1681. foreach ($_info as $k => $v) {
  1682. if (!is_array($v['cart_info']))
  1683. $_info[$k]['cart_info'] = json_decode($v['cart_info'], true);
  1684. }
  1685. foreach ($_info as $k => $v) {
  1686. unset($_info[$k]['cart_info']['type'], $_info[$k]['cart_info']['product_id'], $_info[$k]['cart_info']['combination_id'], $_info[$k]['cart_info']['seckill_id'], $_info[$k]['cart_info']['bargain_id'], $_info[$k]['cart_info']['bargain_id'], $_info[$k]['cart_info']['truePrice'], $_info[$k]['cart_info']['vip_truePrice'], $_info[$k]['cart_info']['trueStock'], $_info[$k]['cart_info']['costPrice'], $_info[$k]['cart_info']['productInfo']['id'], $_info[$k]['cart_info']['productInfo']['vip_price'], $_info[$k]['cart_info']['productInfo']['postage'], $_info[$k]['cart_info']['productInfo']['give_integral'], $_info[$k]['cart_info']['productInfo']['sales'], $_info[$k]['cart_info']['productInfo']['stock'], $_info[$k]['cart_info']['productInfo']['unit_name'], $_info[$k]['cart_info']['productInfo']['is_postage'], $_info[$k]['cart_info']['productInfo']['slider_image'], $_info[$k]['cart_info']['productInfo']['cost'], $_info[$k]['cart_info']['productInfo']['mer_id'], $_info[$k]['cart_info']['productInfo']['cate_id'], $_info[$k]['cart_info']['productInfo']['is_show'], $_info[$k]['cart_info']['productInfo']['store_info'], $_info[$k]['cart_info']['productInfo']['is_del'], $_info[$k]['cart_info']['is_pay'], $_info[$k]['cart_info']['is_del'], $_info[$k]['cart_info']['is_new'], $_info[$k]['cart_info']['add_time'], $_info[$k]['cart_info']['id'], $_info[$k]['cart_info']['uid'], $_info[$k]['cart_info']['product_attr_unique']);
  1687. $_info[$k]['cart_info']['productInfo']['suk'] = '';
  1688. if (isset($v['cart_info']['productInfo']['attrInfo'])) {
  1689. $_info[$k]['cart_info']['productInfo']['image'] = $_info[$k]['cart_info']['productInfo']['attrInfo']['image'];
  1690. $_info[$k]['cart_info']['productInfo']['price'] = $_info[$k]['cart_info']['productInfo']['attrInfo']['price'];
  1691. $_info[$k]['cart_info']['productInfo']['suk'] = $_info[$k]['cart_info']['productInfo']['attrInfo']['suk'];
  1692. unset($_info[$k]['cart_info']['productInfo']['attrInfo']);
  1693. }
  1694. if (!isset($v['cart_info']['productInfo']['ot_price'])) {
  1695. $_info[$k]['cart_info']['productInfo']['ot_price'] = $v['cart_info']['productInfo']['price'];
  1696. }
  1697. }
  1698. $item['_info'] = $_info;
  1699. $item['add_time'] = date('Y-m-d H:i:s', $item['add_time']);
  1700. // if($item['pink_id'] || $item['combination_id']){
  1701. // $pinkStatus = StorePink::where('order_id_key',$item['id'])->value('status');
  1702. // switch ($pinkStatus){
  1703. // case 1:
  1704. // $item['pink_name'] = '[拼团订单]正在进行中';
  1705. // $item['color'] = '#f00';
  1706. // break;
  1707. // case 2:
  1708. // $item['pink_name'] = '[拼团订单]已完成';
  1709. // $item['color'] = '#00f';
  1710. // break;
  1711. // case 3:
  1712. // $item['pink_name'] = '[拼团订单]未完成';
  1713. // $item['color'] = '#f0f';
  1714. // break;
  1715. // default:
  1716. // $item['pink_name'] = '[拼团订单]历史订单';
  1717. // $item['color'] = '#457856';
  1718. // break;
  1719. // }
  1720. // }elseif ($item['seckill_id']){
  1721. // $item['pink_name'] = '[秒杀订单]';
  1722. // $item['color'] = '#32c5e9';
  1723. // }elseif ($item['bargain_id']){
  1724. // $item['pink_name'] = '[砍价订单]';
  1725. // $item['color'] = '#12c5e9';
  1726. // }else{
  1727. // $item['pink_name'] = '[普通订单]';
  1728. // $item['color'] = '#895612';
  1729. // }
  1730. // if($item['paid']==1){
  1731. // switch ($item['pay_type']){
  1732. // case 'weixin':
  1733. // $item['pay_type_name']='微信支付';
  1734. // break;
  1735. // case 'yue':
  1736. // $item['pay_type_name']='余额支付';
  1737. // break;
  1738. // case 'offline':
  1739. // $item['pay_type_name']='线下支付';
  1740. // break;
  1741. // default:
  1742. // $item['pay_type_name']='其他支付';
  1743. // break;
  1744. // }
  1745. // }else{
  1746. // switch ($item['pay_type']){
  1747. // default:
  1748. // $item['pay_type_name']='未支付';
  1749. // break;
  1750. // case 'offline':
  1751. // $item['pay_type_name']='线下支付';
  1752. // $item['pay_type_info']=1;
  1753. // break;
  1754. // }
  1755. // }
  1756. if ($status) {
  1757. $status = [];
  1758. if (!$item['paid'] && $item['pay_type'] == 'offline' && !$item['status'] >= 2) {
  1759. $status['_type'] = 9;
  1760. $status['_title'] = '线下付款';
  1761. $status['_msg'] = '商家处理中,请耐心等待';
  1762. $status['_class'] = 'nobuy';
  1763. } else if (!$item['paid']) {
  1764. $status['_type'] = 0;
  1765. $status['_title'] = '未支付';
  1766. //系统预设取消订单时间段
  1767. $keyValue = ['order_cancel_time', 'order_activity_time', 'order_bargain_time', 'order_seckill_time', 'order_pink_time'];
  1768. //获取配置
  1769. $systemValue = SystemConfigService::more($keyValue);
  1770. //格式化数据
  1771. $systemValue = self::setValeTime($keyValue, is_array($systemValue) ? $systemValue : []);
  1772. if ($item['pink_id'] || $item['combination_id']) {
  1773. $order_pink_time = $systemValue['order_pink_time'] ? $systemValue['order_pink_time'] : $systemValue['order_activity_time'];
  1774. $time = bcadd($item['add_time'], $order_pink_time * 3600, 0);
  1775. $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
  1776. } else if ($item['seckill_id']) {
  1777. $order_seckill_time = $systemValue['order_seckill_time'] ? $systemValue['order_seckill_time'] : $systemValue['order_activity_time'];
  1778. $time = bcadd($item['add_time'], $order_seckill_time * 3600, 0);
  1779. $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
  1780. } else if ($item['bargain_id']) {
  1781. $order_bargain_time = $systemValue['order_bargain_time'] ? $systemValue['order_bargain_time'] : $systemValue['order_activity_time'];
  1782. $time = bcadd($item['add_time'], $order_bargain_time * 3600, 0);
  1783. $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
  1784. } else {
  1785. $time = bcadd($item['add_time'], $systemValue['order_cancel_time'] * 3600, 0);
  1786. $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
  1787. }
  1788. $status['_class'] = 'nobuy';
  1789. } else if ($item['refund_status'] == 1) {
  1790. $status['_type'] = -1;
  1791. $status['_title'] = '申请退款中';
  1792. $status['_msg'] = '商家审核中,请耐心等待';
  1793. $status['_class'] = 'state-sqtk';
  1794. } else if ($item['refund_status'] == 2) {
  1795. $status['_type'] = -2;
  1796. $status['_title'] = '已退款';
  1797. $status['_msg'] = '已为您退款,感谢您的支持';
  1798. $status['_class'] = 'state-sqtk';
  1799. } else if (!$item['status']) {
  1800. if ($item['pink_id']) {
  1801. if (StorePink::where('id', $item['pink_id'])->where('status', 1)->count()) {
  1802. $status['_type'] = 11;
  1803. $status['_title'] = '拼团中';
  1804. $status['_msg'] = '等待其他人参加拼团';
  1805. $status['_class'] = 'state-nfh';
  1806. } else {
  1807. $status['_type'] = 1;
  1808. $status['_title'] = '未发货';
  1809. $status['_msg'] = '商家未发货,请耐心等待';
  1810. $status['_class'] = 'state-nfh';
  1811. }
  1812. } else {
  1813. $status['_type'] = 1;
  1814. $status['_title'] = '未发货';
  1815. $status['_msg'] = '商家未发货,请耐心等待';
  1816. $status['_class'] = 'state-nfh';
  1817. }
  1818. } else if ($item['status'] == 1) {
  1819. if ($item['delivery_type'] == 'send') {//TODO 送货
  1820. $status['_type'] = 2;
  1821. $status['_title'] = '待收货';
  1822. $status['_msg'] = date('m月d日H时i分', StoreOrderStatus::getTime($item['id'], 'delivery')) . '服务商已送货';
  1823. $status['_class'] = 'state-ysh';
  1824. } else {//TODO 发货
  1825. $status['_type'] = 2;
  1826. $status['_title'] = '待收货';
  1827. $status['_msg'] = date('m月d日H时i分', StoreOrderStatus::getTime($item['id'], 'delivery_goods')) . '服务商已发货';
  1828. $status['_class'] = 'state-ysh';
  1829. }
  1830. } else if ($item['status'] == 2) {
  1831. $status['_type'] = 3;
  1832. $status['_title'] = '待评价';
  1833. $status['_msg'] = '已收货,快去评价一下吧';
  1834. $status['_class'] = 'state-ypj';
  1835. } else if ($item['status'] == 3) {
  1836. $status['_type'] = 4;
  1837. $status['_title'] = '交易完成';
  1838. $status['_msg'] = '交易完成,感谢您的支持';
  1839. $status['_class'] = 'state-ytk';
  1840. }
  1841. if (isset($item['pay_type']))
  1842. $status['_payType'] = isset(self::$payType[$item['pay_type']]) ? self::$payType[$item['pay_type']] : '其他方式';
  1843. if (isset($item['delivery_type']))
  1844. $status['_deliveryType'] = isset(self::$deliveryType[$item['delivery_type']]) ? self::$deliveryType[$item['delivery_type']] : '其他方式';
  1845. $item['_status'] = $status;
  1846. } else {
  1847. if ($item['paid'] == 0 && $item['status'] == 0) {
  1848. $item['status_name'] = '未支付';
  1849. } else if ($item['paid'] == 1 && $item['status'] == 0 && $item['refund_status'] == 0) {
  1850. $item['status_name'] = '未发货';
  1851. } else if ($item['paid'] == 1 && $item['status'] == 1 && $item['refund_status'] == 0) {
  1852. $item['status_name'] = '待收货';
  1853. } else if ($item['paid'] == 1 && $item['status'] == 2 && $item['refund_status'] == 0) {
  1854. $item['status_name'] = '待评价';
  1855. } else if ($item['paid'] == 1 && $item['status'] == 3 && $item['refund_status'] == 0) {
  1856. $item['status_name'] = '已完成';
  1857. }
  1858. }
  1859. // unset($item['refund_status']);
  1860. // else if($item['paid']==1 && $item['refund_status']==1){
  1861. // $item['status_name']=<<<HTML
  1862. //<b style="color:#f124c7">申请退款</b><br/>
  1863. //<span>退款原因:{$item['refund_reason_wap']}</span>
  1864. //HTML;
  1865. // }else if($item['paid']==1 && $item['refund_status']==2){
  1866. // $item['status_name']='已退款';
  1867. // }
  1868. // if($item['paid']==0 && $item['status']==0 && $item['refund_status']==0){
  1869. // $item['_status']=1;
  1870. // }else if($item['paid']==1 && $item['status']==0 && $item['refund_status']==0){
  1871. // $item['_status']=2;
  1872. // }else if($item['paid']==1 && $item['refund_status']==1){
  1873. // $item['_status']=3;
  1874. // }else if($item['paid']==1 && $item['status']==1 && $item['refund_status']==0){
  1875. // $item['_status']=4;
  1876. // }else if($item['paid']==1 && $item['status']==2 && $item['refund_status']==0){
  1877. // $item['_status']=5;
  1878. // }else if($item['paid']==1 && $item['status']==3 && $item['refund_status']==0){
  1879. // $item['_status']=6;
  1880. // }else if($item['paid']==1 && $item['refund_status']==2){
  1881. // $item['_status']=7;
  1882. // }
  1883. }
  1884. return $data;
  1885. }
  1886. /**
  1887. * 处理where条件
  1888. * @param $where
  1889. * @param $model
  1890. * @param string $aler
  1891. * @param string $join
  1892. * @return StoreOrder|null
  1893. */
  1894. public static function getOrderWhere($where, $model, $aler = '', $join = '')
  1895. {
  1896. if (isset($where['status']) && $where['status'] != '') $model = self::statusWhere($where['status'], $model, $aler);
  1897. if (isset($where['is_del']) && $where['is_del'] != '' && $where['is_del'] != -1) $model = $model->where($aler . 'is_del', $where['is_del']);
  1898. if (isset($where['combination_id'])) {
  1899. if ($where['combination_id'] == '普通订单') {
  1900. $model = $model->where($aler . 'combination_id', 0)->where($aler . 'seckill_id', 0)->where($aler . 'bargain_id', 0);
  1901. }
  1902. if ($where['combination_id'] == '拼团订单') {
  1903. $model = $model->where($aler . 'combination_id', ">", 0)->where($aler . 'pink_id', ">", 0);
  1904. }
  1905. if ($where['combination_id'] == '秒杀订单') {
  1906. $model = $model->where($aler . 'seckill_id', ">", 0);
  1907. }
  1908. if ($where['combination_id'] == '砍价订单') {
  1909. $model = $model->where($aler . 'bargain_id', ">", 0);
  1910. }
  1911. }
  1912. if (isset($where['type'])) {
  1913. switch ($where['type']) {
  1914. case 1:
  1915. $model = $model->where($aler . 'combination_id', 0)->where($aler . 'seckill_id', 0)->where($aler . 'bargain_id', 0);
  1916. break;
  1917. case 2:
  1918. $model = $model->where($aler . 'combination_id', ">", 0);
  1919. break;
  1920. case 3:
  1921. $model = $model->where($aler . 'seckill_id', ">", 0);
  1922. break;
  1923. case 4:
  1924. $model = $model->where($aler . 'bargain_id', ">", 0);
  1925. break;
  1926. }
  1927. }
  1928. if (isset($where['real_name']) && $where['real_name'] != '')
  1929. $model = $model->where($aler . 'order_id|' . $aler . 'real_name|' . $aler . 'user_phone' . ($join ? '|' . $join . '.nickname|' . $join . '.uid' : ''), 'LIKE', "%$where[real_name]%");
  1930. if (isset($where['data']) && $where['data'] !== '')
  1931. $model = self::getModelTime($where, $model, $aler . 'add_time');
  1932. return $model;
  1933. }
  1934. /**
  1935. * 设置where条件
  1936. * @param $status
  1937. * @param null $model
  1938. * @param string $alert
  1939. * @return StoreOrder|null
  1940. */
  1941. public static function statusWhere($status, $model = null, $alert = '')
  1942. {
  1943. if ($model == null) $model = new self;
  1944. if ('' === $status)
  1945. return $model;
  1946. else if ($status == 0)//未支付
  1947. return $model->where($alert . 'paid', 0)->where($alert . 'status', 0)->where($alert . 'refund_status', 0);
  1948. else if ($status == 1)//已支付 未发货
  1949. return $model->where($alert . 'paid', 1)->where($alert . 'status', 0)->where($alert . 'refund_status', 0);
  1950. else if ($status == 2)//已支付 待收货
  1951. return $model->where($alert . 'paid', 1)->where($alert . 'status', 1)->where($alert . 'refund_status', 0);
  1952. else if ($status == 3)// 已支付 已收货 待评价
  1953. return $model->where($alert . 'paid', 1)->where($alert . 'status', 2)->where($alert . 'refund_status', 0);
  1954. else if ($status == 4)// 交易完成
  1955. return $model->where($alert . 'paid', 1)->where($alert . 'status', 3)->where($alert . 'refund_status', 0);
  1956. else if ($status == -1)//退款中
  1957. return $model->where($alert . 'paid', 1)->where($alert . 'refund_status', 1);
  1958. else if ($status == -2)//已退款
  1959. return $model->where($alert . 'paid', 1)->where($alert . 'refund_status', 2);
  1960. else if ($status == -3)//退款
  1961. return $model->where($alert . 'paid', 1)->where($alert . 'refund_status', 'in', '1,2');
  1962. else
  1963. return $model;
  1964. }
  1965. /**
  1966. * 订单详情 管理员
  1967. * @param $orderId
  1968. * @param string $field
  1969. * @return array|null|\think\Model
  1970. * @throws DataNotFoundException
  1971. * @throws ModelNotFoundException
  1972. * @throws \think\exception\DbException
  1973. */
  1974. public static function getAdminOrderDetail($orderId, $field = '*')
  1975. {
  1976. return self::where('order_id', $orderId)->field($field)->find();
  1977. }
  1978. /**
  1979. * 获取指定时间区间的支付金额 管理员
  1980. * @param $start
  1981. * @param $stop
  1982. * @return float
  1983. */
  1984. public static function getOrderTimeBusinessVolumePrice($start, $stop)
  1985. {
  1986. return self::where('is_del', 0)->where('paid', 1)->where('refund_status', 0)->where('add_time', '>=', $start)->where('add_time', '<', $stop)->sum('pay_price');
  1987. }
  1988. /**
  1989. * 获取指定时间区间的支付订单数量 管理员
  1990. * @param $start
  1991. * @param $stop
  1992. * @return float
  1993. */
  1994. public static function getOrderTimeBusinessVolumeNumber($start, $stop)
  1995. {
  1996. return self::where('is_del', 0)->where('paid', 1)->where('refund_status', 0)->where('add_time', '>=', $start)->where('add_time', '<', $stop)->count();
  1997. }
  1998. /**
  1999. * 获取当前时间到指定时间的支付金额 管理员
  2000. * @param $start 开始时间
  2001. * @param $stop 结束时间
  2002. * @return mixed
  2003. */
  2004. public static function chartTimePrice($start, $stop)
  2005. {
  2006. $model = new self;
  2007. $model = $model->field('sum(pay_price) as num,FROM_UNIXTIME(add_time, \'%Y-%m-%d\') as time');
  2008. $model = $model->where('is_del', 0);
  2009. $model = $model->where('paid', 1);
  2010. $model = $model->where('refund_status', 0);
  2011. $model = $model->where('add_time', '>=', $start);
  2012. $model = $model->where('add_time', '<', $stop);
  2013. $model = $model->group("FROM_UNIXTIME(add_time, '%Y-%m-%d')");
  2014. $model = $model->order('add_time ASC');
  2015. return $model->select();
  2016. }
  2017. /**
  2018. * 获取当前时间到指定时间的支付订单数 管理员
  2019. * @param $start 开始时间
  2020. * @param $stop 结束时间
  2021. * @return mixed
  2022. */
  2023. public static function chartTimeNumber($start, $stop)
  2024. {
  2025. $model = new self;
  2026. $model = $model->field('count(id) as num,FROM_UNIXTIME(add_time, \'%Y-%m-%d\') as time');
  2027. $model = $model->where('is_del', 0);
  2028. $model = $model->where('paid', 1);
  2029. $model = $model->where('refund_status', 0);
  2030. $model = $model->where('add_time', '>=', $start);
  2031. $model = $model->where('add_time', '<', $stop);
  2032. $model = $model->group("FROM_UNIXTIME(add_time, '%Y-%m-%d')");
  2033. $model = $model->order('add_time ASC');
  2034. return $model->select();
  2035. }
  2036. /**
  2037. * 修改支付方式为线下支付
  2038. * @param $orderId
  2039. * @return bool
  2040. */
  2041. public static function setOrderTypePayOffline($orderId)
  2042. {
  2043. return self::edit(['pay_type' => 'offline'], $orderId, 'order_id');
  2044. }
  2045. /**
  2046. * 线下付款
  2047. * @param $id
  2048. * @return $this
  2049. */
  2050. public static function updateOffline($id)
  2051. {
  2052. $count = self::where('id', $id)->count();
  2053. if (!$count) return self::setErrorInfo('订单不存在');
  2054. $count = self::where('id', $id)->where('paid', 0)->count();
  2055. if (!$count) return self::setErrorInfo('订单已支付');
  2056. $res = self::where('id', $id)->update(['paid' => 1, 'pay_time' => time()]);
  2057. return $res;
  2058. }
  2059. /**
  2060. * 向创建订单10分钟未付款的用户发送短信
  2061. */
  2062. public static function sendTen()
  2063. {
  2064. $list = self::where('paid', 0)->where('is_del', 0)->where('is_system_del', 0)->where('add_time', '>', time() - 900)->where('add_time', '<', time() - 600)->column('user_phone');
  2065. foreach ($list as $phone) {
  2066. ShortLetterRepositories::send(true, $phone, [], 'ORDER_PAY_FALSE');
  2067. }
  2068. }
  2069. public function productInfo()
  2070. {
  2071. return $this->hasMany(StoreProductReply::class, 'oid', 'id');
  2072. }
  2073. public static function setOrderProductReplyWhere($where)
  2074. {
  2075. $model = self::where('status', 3)->order('add_time desc')->whereIn('id', function ($query) {
  2076. $query->name('store_order')->alias('o')->join('store_product_reply a', 'a.oid = o.id')->group('o.id')->field('o.id')->select();
  2077. })->with('productInfo', function ($query) use ($where) {
  2078. $alias = '';
  2079. if (isset($where['title']) && $where['title'] != '')
  2080. $query->where("{$alias}comment", 'LIKE', "%$where[title]%");
  2081. if (isset($where['is_reply']) && $where['is_reply'] != '') {
  2082. if ($where['is_reply'] >= 0) {
  2083. $query->where("{$alias}is_reply", $where['is_reply']);
  2084. } else {
  2085. $query->where("{$alias}is_reply", '>', 0);
  2086. }
  2087. }
  2088. if (isset($where['producr_id']) && $where['producr_id'] != 0)
  2089. $query->where($alias . 'product_id', $where['producr_id']);
  2090. $query->where("{$alias}is_del", 0);
  2091. });
  2092. return $model;
  2093. }
  2094. public static function getOrderProductReplyList($where)
  2095. {
  2096. $list = self::setOrderProductReplyWhere($where)->page((int)$where['message_page'], (int)$where['limit'])->select();
  2097. $list = count($list) ? $list->toArray() : [];
  2098. foreach ($list as $key => $item) {
  2099. if (isset($item['productInfo']) && is_array($item['productInfo']) && count($item['productInfo'])) {
  2100. foreach ($item['productInfo'] as $k => $v) {
  2101. if (!$v['nickname'] && $v['uid']) {
  2102. $v['nickname'] = User::where('uid', $v['uid'])->value('nickname');
  2103. $v['avatar'] = User::where('uid', $v['uid'])->value('avatar');
  2104. }
  2105. $v['image'] = '';
  2106. $v['store_name'] = '';
  2107. if ($v['product_id']) {
  2108. $product = StoreProduct::where('id', $v['product_id'])->field(['image', 'store_name'])->find();
  2109. if ($product) {
  2110. $v['image'] = $product['image'];
  2111. $v['store_name'] = $product['store_name'];
  2112. }
  2113. }
  2114. $list[$key]['productInfo'][$k] = $v;
  2115. }
  2116. }
  2117. }
  2118. $count = self::setOrderProductReplyWhere($where)->count();
  2119. return compact('list', 'count');
  2120. }
  2121. =======
  2122. <?php
  2123. /**
  2124. *
  2125. * @author: xaboy<365615158@qq.com>
  2126. * @day: 2017/12/20
  2127. */
  2128. namespace app\models\store;
  2129. use app\admin\model\system\ShippingTemplatesFree;
  2130. use app\admin\model\system\ShippingTemplatesRegion;
  2131. use crmeb\basic\BaseModel;
  2132. use think\db\exception\DataNotFoundException;
  2133. use think\db\exception\DbException;
  2134. use think\db\exception\ModelNotFoundException;
  2135. use think\facade\Cache;
  2136. use crmeb\traits\ModelTrait;
  2137. use think\facade\Log;
  2138. use app\models\system\SystemStore;
  2139. use app\models\routine\RoutineTemplate;
  2140. use app\models\user\{Out, ProxyAddress, User, UserAddress, UserBill, UserLevel, UserPartake, UserSpread, WechatUser};
  2141. use crmeb\services\{
  2142. SystemConfigService, WechatTemplateService, workerman\ChannelService
  2143. };
  2144. use crmeb\repositories\{
  2145. GoodsRepository, PaymentRepositories, OrderRepository, ShortLetterRepositories, UserRepository
  2146. };
  2147. use app\admin\model\system\ShippingTemplates;
  2148. /**
  2149. * TODO 订单Model
  2150. * Class StoreOrder
  2151. * @package app\models\store
  2152. */
  2153. class StoreOrder extends BaseModel
  2154. {
  2155. /**
  2156. * 数据表主键
  2157. * @var string
  2158. */
  2159. protected $pk = 'id';
  2160. /**
  2161. * 模型名称
  2162. * @var string
  2163. */
  2164. protected $name = 'store_order';
  2165. use ModelTrait;
  2166. protected $insert = ['add_time'];
  2167. protected static $payType = ['weixin' => '微信支付', 'yue' => '余额支付', 'offline' => '线下支付', 'ali' => '支付宝支付'];
  2168. protected static $deliveryType = ['send' => '商家配送', 'express' => '快递配送'];
  2169. protected function setAddTimeAttr()
  2170. {
  2171. return time();
  2172. }
  2173. protected function setCartIdAttr($value)
  2174. {
  2175. return is_array($value) ? json_encode($value) : $value;
  2176. }
  2177. protected function getCartIdAttr($value)
  2178. {
  2179. return json_decode($value, true);
  2180. }
  2181. /**获取订单组信息
  2182. * @param $cartInfo
  2183. * @return array
  2184. */
  2185. public static function getOrderPriceGroup($cartInfo, $addr)
  2186. {
  2187. $storeFreePostage = floatval(sys_config('store_free_postage')) ?: 0;//满额包邮
  2188. $totalPrice = self::getOrderSumPrice($cartInfo, 'truePrice');//获取订单总金额
  2189. $totalIntegral = self::getOrderSumPrice($cartInfo, 'integral');//获取订单总积分
  2190. $costPrice = self::getOrderSumPrice($cartInfo, 'costPrice');//获取订单成本价
  2191. $vipPrice = self::getOrderSumPrice($cartInfo, 'vip_truePrice');//获取订单会员优惠金额
  2192. //如果满额包邮等于0
  2193. if (!$storeFreePostage) {
  2194. $storePostage = 0;
  2195. } else {
  2196. if ($addr) {
  2197. //按照运费模板计算每个运费模板下商品的件数/重量/体积以及总金额 按照首重倒序排列
  2198. $temp_num = [];
  2199. foreach ($cartInfo as $cart) {
  2200. $temp = ShippingTemplates::get($cart['productInfo']['temp_id']);
  2201. if (!$temp) $temp = ShippingTemplates::get(1);
  2202. if ($temp->getData('type') == 1) {
  2203. $num = $cart['cart_num'];
  2204. } elseif ($temp->getData('type') == 2) {
  2205. $num = $cart['cart_num'] * $cart['productInfo']['attrInfo']['weight'];
  2206. } else {
  2207. $num = $cart['cart_num'] * $cart['productInfo']['attrInfo']['volume'];
  2208. }
  2209. $region = ShippingTemplatesRegion::where('temp_id', $cart['productInfo']['temp_id'])->where('city_id', $addr['city_id'])->find();
  2210. if (!$region) $region = ShippingTemplatesRegion::where('temp_id', $cart['productInfo']['temp_id'])->where('city_id', 0)->find();
  2211. if (!$region) $region = ShippingTemplatesRegion::where('temp_id', 1)->where('city_id', 0)->find();
  2212. if (!$region) {
  2213. return self::setErrorInfo('运费模板不存在');
  2214. }
  2215. if (!isset($temp_num[$cart['productInfo']['temp_id']])) {
  2216. $temp_num[$cart['productInfo']['temp_id']]['number'] = $num;
  2217. $temp_num[$cart['productInfo']['temp_id']]['price'] = bcmul($cart['cart_num'], $cart['truePrice'], 2);
  2218. $temp_num[$cart['productInfo']['temp_id']]['first'] = $region['first'];
  2219. $temp_num[$cart['productInfo']['temp_id']]['first_price'] = $region['first_price'];
  2220. $temp_num[$cart['productInfo']['temp_id']]['continue'] = $region['continue'];
  2221. $temp_num[$cart['productInfo']['temp_id']]['continue_price'] = $region['continue_price'];
  2222. $temp_num[$cart['productInfo']['temp_id']]['temp_id'] = $cart['productInfo']['temp_id'];
  2223. $temp_num[$cart['productInfo']['temp_id']]['city_id'] = $addr['city_id'];
  2224. } else {
  2225. $temp_num[$cart['productInfo']['temp_id']]['number'] += $num;
  2226. $temp_num[$cart['productInfo']['temp_id']]['price'] += bcmul($cart['cart_num'], $cart['truePrice'], 2);
  2227. }
  2228. }
  2229. array_multisort(array_column($temp_num, 'first_price'), SORT_DESC, $temp_num);
  2230. $type = $storePostage = 0;
  2231. foreach ($temp_num as $k => $v) {
  2232. if (ShippingTemplatesFree::where('temp_id', $v['temp_id'])->where('city_id', $v['city_id'])->where('number', '<=', $v['number'])->where('price', '<=', $v['price'])->find()) {
  2233. unset($temp_num[$k]);
  2234. }
  2235. }
  2236. foreach ($temp_num as $v) {
  2237. if ($type == 0) {
  2238. if ($v['number'] <= $v['first']) {
  2239. $storePostage = bcadd($storePostage, $v['first_price'], 2);
  2240. } else {
  2241. if ($v['continue'] <= 0) {
  2242. $storePostage = $storePostage;
  2243. } else {
  2244. $storePostage = bcadd(bcadd($storePostage, $v['first_price'], 2), bcmul(ceil(bcdiv(bcsub($v['number'], $v['first']), $v['continue'] ?? 0, 2)), $v['continue_price']), 2);
  2245. }
  2246. }
  2247. $type = 1;
  2248. } else {
  2249. if ($v['continue'] <= 0) {
  2250. $storePostage = $storePostage;
  2251. } else {
  2252. $storePostage = bcadd($storePostage, bcmul(ceil(bcdiv($v['number'], $v['continue'] ?? 0, 2)), $v['continue_price']), 2);
  2253. }
  2254. }
  2255. }
  2256. } else {
  2257. $storePostage = 0;
  2258. }
  2259. if ($storeFreePostage <= $totalPrice) $storePostage = 0;//如果总价大于等于满额包邮 邮费等于0
  2260. }
  2261. return compact('storePostage', 'storeFreePostage', 'totalPrice', 'costPrice', 'vipPrice', 'totalIntegral');
  2262. }
  2263. /**获取某个字段总金额
  2264. * @param $cartInfo
  2265. * @param $key 键名
  2266. * @return int|string
  2267. */
  2268. public static function getOrderSumPrice($cartInfo, $key = 'truePrice')
  2269. {
  2270. $SumPrice = 0;
  2271. foreach ($cartInfo as $cart) {
  2272. $SumPrice = bcadd($SumPrice, bcmul($cart['cart_num'], $cart[$key], 2), 2);
  2273. }
  2274. return $SumPrice;
  2275. }
  2276. /**
  2277. * 拼团
  2278. * @param $cartInfo
  2279. * @return array
  2280. */
  2281. public static function getCombinationOrderPriceGroup($cartInfo)
  2282. {
  2283. $storePostage = floatval(sys_config('store_postage')) ?: 0;
  2284. $storeFreePostage = floatval(sys_config('store_free_postage')) ?: 0;
  2285. $totalPrice = self::getCombinationOrderTotalPrice($cartInfo);
  2286. $costPrice = self::getCombinationOrderTotalPrice($cartInfo);
  2287. if (!$storeFreePostage) {
  2288. $storePostage = 0;
  2289. } else {
  2290. foreach ($cartInfo as $cart) {
  2291. if (!StoreCombination::where('id', $cart['combination_id'])->value('is_postage'))
  2292. $storePostage = bcadd($storePostage, StoreCombination::where('id', $cart['combination_id'])->value('postage'), 2);
  2293. }
  2294. if ($storeFreePostage <= $totalPrice) $storePostage = 0;
  2295. }
  2296. return compact('storePostage', 'storeFreePostage', 'totalPrice', 'costPrice');
  2297. }
  2298. /**
  2299. * 拼团价格
  2300. * @param $cartInfo
  2301. * @return float
  2302. */
  2303. public static function getCombinationOrderTotalPrice($cartInfo)
  2304. {
  2305. $totalPrice = 0;
  2306. foreach ($cartInfo as $cart) {
  2307. if ($cart['combination_id']) {
  2308. $totalPrice = bcadd($totalPrice, bcmul($cart['cart_num'], StoreCombination::where('id', $cart['combination_id'])->value('price'), 2), 2);
  2309. }
  2310. }
  2311. return (float)$totalPrice;
  2312. }
  2313. /**
  2314. * 缓存订单信息
  2315. * @param $uid
  2316. * @param $cartInfo
  2317. * @param $priceGroup
  2318. * @param array $other
  2319. * @param int $cacheTime
  2320. * @return string
  2321. * @throws \Psr\SimpleCache\InvalidArgumentException
  2322. */
  2323. public static function cacheOrderInfo($uid, $cartInfo, $priceGroup, $other = [], $cacheTime = 600)
  2324. {
  2325. do {
  2326. $key = md5(time() . rand(100000, 999999));
  2327. } while (Cache::has('user_order_' . $uid . $key));
  2328. Cache::set('user_order_' . $uid . $key, compact('cartInfo', 'priceGroup', 'other'), $cacheTime);
  2329. return $key;
  2330. }
  2331. /**
  2332. * 获取订单缓存信息
  2333. * @param $uid
  2334. * @param $key
  2335. * @return mixed|null
  2336. * @throws \Psr\SimpleCache\InvalidArgumentException
  2337. */
  2338. public static function getCacheOrderInfo($uid, $key)
  2339. {
  2340. $cacheName = 'user_order_' . $uid . $key;
  2341. if (!Cache::has($cacheName)) return null;
  2342. return Cache::get($cacheName);
  2343. }
  2344. /**
  2345. * 删除订单缓存
  2346. * @param $uid
  2347. * @param $key
  2348. */
  2349. public static function clearCacheOrderInfo($uid, $key)
  2350. {
  2351. Cache::delete('user_order_' . $uid . $key);
  2352. }
  2353. /**
  2354. * 生成订单
  2355. * @param $uid
  2356. * @param $key
  2357. * @param $addressId
  2358. * @param $payType
  2359. * @param bool $useIntegral
  2360. * @param int $couponId
  2361. * @param string $mark
  2362. * @param int $combinationId
  2363. * @param int $pinkId
  2364. * @param int $seckill_id
  2365. * @param int $bargain_id
  2366. * @param bool $test
  2367. * @param int $isChannel
  2368. * @param int $shipping_type
  2369. * @param string $real_name
  2370. * @param string $phone
  2371. * @return StoreOrder|bool|\think\Model
  2372. * @throws \think\Exception
  2373. * @throws DataNotFoundException
  2374. * @throws ModelNotFoundException
  2375. * @throws \think\exception\DbException
  2376. */
  2377. public static function cacheKeyCreateOrder($uid, $key, $addressId, $payType, $useIntegral = false, $couponId = 0, $mark = '', $combinationId = 0, $pinkId = 0, $seckill_id = 0, $bargain_id = 0, $test = false, $isChannel = 0, $shipping_type = 1, $real_name = '', $phone = '', $storeId = 0)
  2378. {
  2379. self::beginTrans();
  2380. try {
  2381. $shipping_type = (int)$shipping_type;
  2382. $offlinePayStatus = (int)sys_config('offline_pay_status') ?? (int)2;
  2383. if ($offlinePayStatus == 2) unset(self::$payType['offline']);
  2384. if (!array_key_exists($payType, self::$payType)) return self::setErrorInfo('选择支付方式有误!', true);
  2385. if (self::be(['unique' => $key, 'uid' => $uid])) return self::setErrorInfo('请勿重复提交订单', true);
  2386. $userInfo = User::getUserInfo($uid);
  2387. if (!$userInfo) return self::setErrorInfo('用户不存在!', true);
  2388. $cartGroup = self::getCacheOrderInfo($uid, $key);
  2389. if (!$cartGroup) return self::setErrorInfo('订单已过期,请刷新当前页面!', true);
  2390. $cartInfo = $cartGroup['cartInfo'];
  2391. $priceGroup = $cartGroup['priceGroup'];
  2392. $other = $cartGroup['other'];
  2393. $payPrice = (float)$priceGroup['totalPrice'];
  2394. $payIntegral = (float)$priceGroup['totalIntegral'];
  2395. $addr = UserAddress::where('uid', $uid)->where('id', $addressId)->find();
  2396. if ($payType == 'offline' && sys_config('offline_postage') == 1) {
  2397. $payPostage = 0;
  2398. } else {
  2399. $payPostage = self::getOrderPriceGroup($cartInfo, $addr)['storePostage'];
  2400. }
  2401. if ($shipping_type === 1) {
  2402. if (!$test && !$addressId) return self::setErrorInfo('请选择收货地址!', true);
  2403. if (!$test && (!UserAddress::be(['uid' => $uid, 'id' => $addressId, 'is_del' => 0]) || !($addressInfo = UserAddress::find($addressId))))
  2404. return self::setErrorInfo('地址选择有误!', true);
  2405. } else {
  2406. if ((!$real_name || !$phone) && !$test) return self::setErrorInfo('请填写姓名和电话', true);
  2407. $addressInfo['real_name'] = $real_name;
  2408. $addressInfo['phone'] = $phone;
  2409. $addressInfo['province'] = '';
  2410. $addressInfo['city'] = '';
  2411. $addressInfo['district'] = '';
  2412. $addressInfo['detail'] = '';
  2413. }
  2414. $cartIds = [];
  2415. $totalNum = 0;
  2416. $gainIntegral = 0;
  2417. foreach ($cartInfo as $cart) {
  2418. $cartIds[] = $cart['id'];
  2419. $totalNum += $cart['cart_num'];
  2420. if (!$seckill_id) $seckill_id = $cart['seckill_id'];
  2421. if (!$bargain_id) $bargain_id = $cart['bargain_id'];
  2422. if (!$combinationId) $combinationId = $cart['combination_id'];
  2423. $cartInfoGainIntegral = isset($cart['productInfo']['give_integral']) ? bcmul($cart['cart_num'], $cart['productInfo']['give_integral'], 2) : 0;
  2424. $gainIntegral = bcadd($gainIntegral, $cartInfoGainIntegral, 2);
  2425. }
  2426. $deduction = $seckill_id || $bargain_id || $combinationId;
  2427. if ($deduction) {
  2428. $couponId = 0;
  2429. $useIntegral = false;
  2430. if (!$test) {
  2431. unset(self::$payType['offline']);
  2432. if (!array_key_exists($payType, self::$payType)) return self::setErrorInfo('营销产品不能使用线下支付!', true);
  2433. }
  2434. }
  2435. //使用优惠劵
  2436. $res1 = true;
  2437. if ($couponId) {
  2438. $couponInfo = StoreCouponUser::validAddressWhere()->where('id', $couponId)->where('uid', $uid)->find();
  2439. if (!$couponInfo) return self::setErrorInfo('选择的优惠劵无效!', true);
  2440. $coupons = StoreCouponUser::getUsableCouponList($uid, ['valid' => $cartInfo], $payPrice);
  2441. $flag = false;
  2442. foreach ($coupons as $coupon) {
  2443. if ($coupon['id'] == $couponId) {
  2444. $flag = true;
  2445. continue;
  2446. }
  2447. }
  2448. if (!$flag)
  2449. return self::setErrorInfo('不满足优惠劵的使用条件!', true);
  2450. $payPrice = (float)bcsub($payPrice, $couponInfo['coupon_price'], 2);
  2451. $res1 = StoreCouponUser::useCoupon($couponId);
  2452. $couponPrice = $couponInfo['coupon_price'];
  2453. } else {
  2454. $couponId = 0;
  2455. $couponPrice = 0;
  2456. }
  2457. if (!$res1) return self::setErrorInfo('使用优惠劵失败!', true);
  2458. //$shipping_type = 1 快递发货 $shipping_type = 2 门店自提
  2459. $store_self_mention = sys_config('store_self_mention') ?? 0;
  2460. if (!$store_self_mention) $shipping_type = 1;
  2461. if ($shipping_type === 1) {
  2462. //是否包邮
  2463. if ((isset($other['offlinePostage']) && $other['offlinePostage'] && $payType == 'offline')) $payPostage = 0;
  2464. $payPrice = (float)bcadd($payPrice, $payPostage, 2);
  2465. } else if ($shipping_type === 2) {
  2466. //门店自提没有邮费支付
  2467. $priceGroup['storePostage'] = 0;
  2468. $payPostage = 0;
  2469. if (!$storeId && !$test) {
  2470. return self::setErrorInfo('请选择门店', true);
  2471. }
  2472. }
  2473. //积分抵扣
  2474. $res2 = true;
  2475. $SurplusIntegral = $userInfo['integral'];
  2476. if ($payIntegral > 0) {
  2477. if ($userInfo['integral'] < $payIntegral) {
  2478. return self::setErrorInfo('积分不足', true);
  2479. } else {
  2480. $res2 = false !== User::bcDec($userInfo['uid'], 'integral', $payIntegral, 'uid');
  2481. }
  2482. $SurplusIntegral = bcsub($userInfo['integral'], $payIntegral, 2);
  2483. $res2 = $res2 && false != UserBill::expend('积分商品', $uid, 'integral', 'integral_product', $payIntegral, $key, $SurplusIntegral, '购买积分商品使用' . $payIntegral . '积分');
  2484. }
  2485. //积分抵扣
  2486. if ($useIntegral && $SurplusIntegral > 0) {
  2487. $deductionPrice = (float)bcmul($SurplusIntegral, $other['integralRatio'], 2);
  2488. if ($deductionPrice < $payPrice) {
  2489. $payPrice = bcsub($payPrice, $deductionPrice, 2);
  2490. $usedIntegral = $SurplusIntegral;
  2491. $SurplusIntegral = 0;
  2492. $res2 = false !== User::edit(['integral' => 0], $userInfo['uid'], 'uid');
  2493. } else {
  2494. $deductionPrice = $payPrice;
  2495. $usedIntegral = (float)bcdiv($payPrice, $other['integralRatio'], 2);
  2496. $SurplusIntegral = bcsub($SurplusIntegral, $usedIntegral, 2);
  2497. $res2 = false !== User::bcDec($userInfo['uid'], 'integral', $usedIntegral, 'uid');
  2498. $payPrice = 0;
  2499. }
  2500. $res2 = $res2 && false != UserBill::expend('积分抵扣', $uid, 'integral', 'deduction', $usedIntegral, $key, $SurplusIntegral, '购买商品使用' . floatval($usedIntegral) . '积分抵扣' . floatval($deductionPrice) . '元');
  2501. } else {
  2502. $deductionPrice = 0;
  2503. $usedIntegral = 0;
  2504. }
  2505. if (!$res2) return self::setErrorInfo('使用积分抵扣失败!', true);
  2506. if ($payPrice <= 0) $payPrice = 0;
  2507. if ($test) {
  2508. self::rollbackTrans();
  2509. return [
  2510. 'total_price' => $priceGroup['totalPrice'],
  2511. 'pay_price' => $payPrice,
  2512. 'pay_postage' => $payPostage,
  2513. 'coupon_price' => $couponPrice,
  2514. 'deduction_price' => $deductionPrice,
  2515. 'totalIntegral' => $payIntegral,
  2516. 'SurplusIntegral' => $SurplusIntegral,
  2517. ];
  2518. }
  2519. $orderInfo = [
  2520. 'uid' => $uid,
  2521. 'order_id' => $test ? 0 : self::getNewOrderId(),
  2522. 'real_name' => $addressInfo['real_name'],
  2523. 'user_phone' => $addressInfo['phone'],
  2524. 'user_address' => $addressInfo['province'] . ' ' . $addressInfo['city'] . ' ' . $addressInfo['district'] . ' ' . $addressInfo['detail'],
  2525. 'cart_id' => $cartIds,
  2526. 'total_num' => $totalNum,
  2527. 'total_price' => $priceGroup['totalPrice'],
  2528. 'total_postage' => $priceGroup['storePostage'],
  2529. 'coupon_id' => $couponId,
  2530. 'coupon_price' => $couponPrice,
  2531. 'pay_price' => $payPrice,
  2532. 'pay_postage' => $payPostage,
  2533. 'deduction_price' => $deductionPrice,
  2534. 'paid' => 0,
  2535. 'pay_type' => $payType,
  2536. 'use_integral' => $usedIntegral + $payIntegral,
  2537. 'gain_integral' => $gainIntegral,
  2538. 'mark' => htmlspecialchars($mark),
  2539. 'combination_id' => $combinationId,
  2540. 'pink_id' => $pinkId,
  2541. 'seckill_id' => $seckill_id,
  2542. 'bargain_id' => $bargain_id,
  2543. 'cost' => $priceGroup['costPrice'],
  2544. 'is_channel' => $isChannel,
  2545. 'add_time' => time(),
  2546. 'unique' => $key,
  2547. 'shipping_type' => $shipping_type,
  2548. ];
  2549. if ($shipping_type === 2) {
  2550. $orderInfo['verify_code'] = self::getStoreCode();
  2551. $orderInfo['store_id'] = SystemStore::getStoreDispose($storeId, 'id');
  2552. if (!$orderInfo['store_id']) return self::setErrorInfo('暂无门店无法选择门店自提!', true);
  2553. }
  2554. $order = self::create($orderInfo);
  2555. if (!$order) return self::setErrorInfo('订单生成失败!', true);
  2556. $res5 = true;
  2557. foreach ($cartInfo as $cart) {
  2558. //减库存加销量
  2559. if ($combinationId) $res5 = $res5 && StoreCombination::decCombinationStock($cart['cart_num'], $combinationId, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  2560. else if ($seckill_id) $res5 = $res5 && StoreSeckill::decSeckillStock($cart['cart_num'], $seckill_id, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  2561. else if ($bargain_id) $res5 = $res5 && StoreBargain::decBargainStock($cart['cart_num'], $bargain_id, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  2562. else $res5 = $res5 && StoreProduct::decProductStock($cart['cart_num'], $cart['productInfo']['id'], isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  2563. }
  2564. //保存购物车商品信息
  2565. $res4 = false !== StoreOrderCartInfo::setCartInfo($order['id'], $cartInfo);
  2566. //购物车状态修改
  2567. $res6 = false !== StoreCart::where('id', 'IN', $cartIds)->update(['is_pay' => 1]);
  2568. if (!$res4 || !$res5 || !$res6) return self::setErrorInfo('订单生成失败!', true);
  2569. //自动设置默认地址
  2570. UserRepository::storeProductOrderCreateEbApi($order, compact('cartInfo', 'addressId'));
  2571. self::clearCacheOrderInfo($uid, $key);
  2572. self::commitTrans();
  2573. StoreOrderStatus::status($order['id'], 'cache_key_create_order', '订单生成');
  2574. return $order;
  2575. } catch (\PDOException $e) {
  2576. self::rollbackTrans();
  2577. return self::setErrorInfo('生成订单时SQL执行错误错误原因:' . $e->getMessage());
  2578. } catch (\Exception $e) {
  2579. self::rollbackTrans();
  2580. return self::setErrorInfo('生成订单时系统错误错误原因:' . $e->getMessage());
  2581. }
  2582. }
  2583. /**
  2584. * 回退积分
  2585. * @param $order 订单信息
  2586. * @return bool
  2587. */
  2588. public static function RegressionIntegral($order)
  2589. {
  2590. if ($order['paid'] || $order['status'] == -2 || $order['is_del']) return true;
  2591. if ($order['use_integral'] <= 0) return true;
  2592. if ((int)$order['status'] != -2 && (int)$order['refund_status'] != 2 && $order['back_integral'] >= $order['use_integral']) return true;
  2593. $res = User::bcInc($order['uid'], 'integral', $order['use_integral']);
  2594. if (!$res) return self::setErrorInfo('回退积分增加失败');
  2595. UserBill::income('积分回退', $order['uid'], 'integral', 'deduction', $order['use_integral'], $order['unique'], User::where('uid', $order['uid'])->value('integral'), '购买商品失败,回退积分' . floatval($order['use_integral']));
  2596. return false !== self::where('order_id', $order['order_id'])->update(['back_integral' => $order['use_integral']]);
  2597. }
  2598. /**
  2599. * 回退库存和销量
  2600. * @param $order 订单信息
  2601. * @return bool
  2602. * @throws DataNotFoundException
  2603. * @throws ModelNotFoundException
  2604. * @throws \think\exception\DbException
  2605. */
  2606. public static function RegressionStock($order)
  2607. {
  2608. if ($order['paid'] || $order['status'] == -2 || $order['is_del']) return true;
  2609. $combinationId = $order['combination_id'];
  2610. $seckill_id = $order['seckill_id'];
  2611. $bargain_id = $order['bargain_id'];
  2612. $res5 = true;
  2613. $cartInfo = StoreOrderCartInfo::where('cart_id', 'in', $order['cart_id'])->select();
  2614. foreach ($cartInfo as $cart) {
  2615. //增库存减销量
  2616. if ($combinationId) $res5 = $res5 && StoreCombination::incCombinationStock($cart['cart_info']['cart_num'], $combinationId);
  2617. else if ($seckill_id) $res5 = $res5 && StoreSeckill::incSeckillStock($cart['cart_info']['cart_num'], $seckill_id);
  2618. else if ($bargain_id) $res5 = $res5 && StoreBargain::incBargainStock($cart['cart_info']['cart_num'], $bargain_id);
  2619. else $res5 = $res5 && StoreProduct::incProductStock($cart['cart_info']['cart_num'], $cart['cart_info']['productInfo']['id'], isset($cart['cart_info']['productInfo']['attrInfo']) ? $cart['cart_info']['productInfo']['attrInfo']['unique'] : '');
  2620. }
  2621. return $res5;
  2622. }
  2623. /**
  2624. * 回退优惠卷
  2625. * @param $order 订单信息
  2626. * @return bool
  2627. */
  2628. public static function RegressionCoupon($order)
  2629. {
  2630. if ($order['paid'] || $order['status'] == -2 || $order['is_del']) return true;
  2631. $res = true;
  2632. if ($order['coupon_id'] && StoreCouponUser::be(['id' => $order['coupon_id'], 'uid' => $order['uid'], 'status' => 1])) {
  2633. $res = $res && false !== StoreCouponUser::where('id', $order['coupon_id'])->where('uid', $order['uid'])->update(['status' => 0, 'use_time' => 0]);
  2634. }
  2635. return $res;
  2636. }
  2637. /**
  2638. * 取消订单
  2639. * @param string order_id 订单id
  2640. * @param $uid
  2641. * @return bool
  2642. * @throws DataNotFoundException
  2643. * @throws ModelNotFoundException
  2644. * @throws \think\exception\DbException
  2645. */
  2646. public static function cancelOrder($order_id, $uid)
  2647. {
  2648. $order = self::where('order_id', $order_id)->where('uid', $uid)->find();
  2649. if (!$order) return self::setErrorInfo('没有查到此订单');
  2650. self::beginTrans();
  2651. try {
  2652. $res = self::RegressionIntegral($order) && self::RegressionStock($order) && self::RegressionCoupon($order);
  2653. $order->is_del = 1;
  2654. if ($res && $order->save()) {
  2655. self::commitTrans();
  2656. return true;
  2657. } else
  2658. return false;
  2659. } catch (\Exception $e) {
  2660. self::rollbackTrans();
  2661. return self::setErrorInfo(['line' => $e->getLine(), 'message' => $e->getMessage()]);
  2662. }
  2663. }
  2664. /**
  2665. * 生成订单唯一id
  2666. * @param $uid 用户uid
  2667. * @return string
  2668. */
  2669. public static function getNewOrderId()
  2670. {
  2671. do {
  2672. list($msec, $sec) = explode(' ', microtime());
  2673. $msectime = number_format((floatval($msec) + floatval($sec)) * 1000, 0, '', '');
  2674. $orderId = 'wx' . $msectime . mt_rand(10000, 99999);
  2675. } while (self::be(['order_id' => $orderId]));// $orderId = 'wx' . $msectime . mt_rand(10000, 99999);
  2676. return $orderId;
  2677. }
  2678. /**
  2679. * 修改订单号
  2680. * @param $orderId
  2681. * @return string
  2682. */
  2683. public static function changeOrderId($orderId)
  2684. {
  2685. $ymd = substr($orderId, 2, 8);
  2686. $key = substr($orderId, 16);
  2687. return 'wx' . $ymd . date('His') . $key;
  2688. }
  2689. /**
  2690. * 查找购物车里的所有产品标题
  2691. * @param $cartId 购物车id
  2692. * @return bool|string
  2693. */
  2694. public static function getProductTitle($cartId)
  2695. {
  2696. $title = '';
  2697. try {
  2698. $orderCart = StoreOrderCartInfo::where('cart_id', 'in', $cartId)->field('cart_info')->select();
  2699. foreach ($orderCart as $item) {
  2700. if (isset($item['cart_info']['productInfo']['store_name'])) {
  2701. $title .= $item['cart_info']['productInfo']['store_name'] . '|';
  2702. }
  2703. }
  2704. unset($item);
  2705. if (!$title) {
  2706. $productIds = StoreCart::where('id', 'in', $cartId)->column('product_id');
  2707. $productlist = ($productlist = StoreProduct::getProductField($productIds, 'store_name')) ? $productlist->toArray() : [];
  2708. foreach ($productlist as $item) {
  2709. if (isset($item['store_name'])) $title .= $item['store_name'] . '|';
  2710. }
  2711. }
  2712. if ($title) $title = substr($title, 0, strlen($title) - 1);
  2713. unset($item);
  2714. } catch (\Exception $e) {
  2715. }
  2716. return $title;
  2717. }
  2718. /**
  2719. * 获取门店自提唯一核销码
  2720. * @return bool|string
  2721. */
  2722. public static function getStoreCode()
  2723. {
  2724. list($msec, $sec) = explode(' ', microtime());
  2725. $num = bcadd(time(), mt_rand(10, 999999), 0) . '' . substr($msec, 2, 3);//生成随机数
  2726. if (strlen($num) < 12)
  2727. $num = str_pad((string)$num, 12, 0, STR_PAD_RIGHT);
  2728. else
  2729. $num = substr($num, 0, 12);
  2730. if (self::be(['verify_code' => $num])) return self::getStoreCode();
  2731. return $num;
  2732. }
  2733. /**
  2734. * 余额支付
  2735. * @param $order_id
  2736. * @param $uid
  2737. * @param string $formId
  2738. * @return bool
  2739. * @throws \think\Exception
  2740. * @throws DataNotFoundException
  2741. * @throws ModelNotFoundException
  2742. * @throws \think\exception\DbException
  2743. */
  2744. public static function yuePay($order_id, $uid, $formId = '')
  2745. {
  2746. $orderInfo = self::where('uid', $uid)->where('order_id', $order_id)->where('is_del', 0)->find();
  2747. if (!$orderInfo) return self::setErrorInfo('订单不存在!');
  2748. if ($orderInfo['paid']) return self::setErrorInfo('该订单已支付!');
  2749. // if($orderInfo['pay_type'] != 'yue') return self::setErrorInfo('该订单不能使用余额支付!');
  2750. $userInfo = User::getUserInfo($uid);
  2751. if ($userInfo['now_money'] < $orderInfo['pay_price'])
  2752. return self::setErrorInfo(['status' => 'pay_deficiency', 'msg' => '余额不足' . floatval($orderInfo['pay_price'])]);
  2753. self::beginTrans();
  2754. $res1 = false !== User::bcDec($uid, 'now_money', $orderInfo['pay_price'], 'uid');
  2755. $res2 = UserBill::expend('购买商品', $uid, 'now_money', 'pay_product', $orderInfo['pay_price'], $orderInfo['id'], $userInfo['now_money'], '余额支付' . floatval($orderInfo['pay_price']) . '元购买商品');
  2756. $res3 = self::paySuccess($order_id, 'yue', $formId);//余额支付成功
  2757. try {
  2758. PaymentRepositories::yuePayProduct($userInfo, $orderInfo);
  2759. } catch (\Exception $e) {
  2760. self::rollbackTrans();
  2761. return self::setErrorInfo($e->getMessage());
  2762. }
  2763. $res = $res1 && $res2 && $res3;
  2764. self::checkTrans($res);
  2765. return $res;
  2766. }
  2767. /**
  2768. * 微信支付 为 0元时
  2769. * @param $order_id
  2770. * @param $uid
  2771. * @param string $formId
  2772. * @return bool
  2773. * @throws \think\Exception
  2774. * @throws DataNotFoundException
  2775. * @throws ModelNotFoundException
  2776. * @throws \think\exception\DbException
  2777. */
  2778. public static function jsPayPrice($order_id, $uid, $formId = '')
  2779. {
  2780. $orderInfo = self::where('uid', $uid)->where('order_id', $order_id)->where('is_del', 0)->find();
  2781. if (!$orderInfo) return self::setErrorInfo('订单不存在!');
  2782. if ($orderInfo['paid']) return self::setErrorInfo('该订单已支付!');
  2783. $userInfo = User::getUserInfo($uid);
  2784. self::beginTrans();
  2785. $res1 = UserBill::expend('购买商品', $uid, 'now_money', 'pay_product', $orderInfo['pay_price'], $orderInfo['id'], $userInfo['now_money'], '微信支付' . floatval($orderInfo['pay_price']) . '元购买商品');
  2786. $res2 = self::paySuccess($order_id, 'weixin', $formId);//微信支付为0时
  2787. $res = $res1 && $res2;
  2788. self::checkTrans($res);
  2789. return $res;
  2790. }
  2791. /**
  2792. * 用户申请退款
  2793. * @param $uni
  2794. * @param $uid
  2795. * @param string $refundReasonWap
  2796. * @return bool
  2797. */
  2798. public static function orderApplyRefund($uni, $uid, $refundReasonWap = '', $refundReasonWapExplain = '', $refundReasonWapImg = [])
  2799. {
  2800. $order = self::getUserOrderDetail($uid, $uni);
  2801. if (!$order) return self::setErrorInfo('支付订单不存在!');
  2802. if ($order['refund_status'] == 2) return self::setErrorInfo('订单已退款!');
  2803. if ($order['refund_status'] == 1) return self::setErrorInfo('正在申请退款中!');
  2804. if ($order['status'] == 1) return self::setErrorInfo('订单当前无法退款!');
  2805. self::beginTrans();
  2806. $res1 = false !== StoreOrderStatus::status($order['id'], 'apply_refund', '用户申请退款,原因:' . $refundReasonWap);
  2807. $res2 = false !== self::edit(['refund_status' => 1, 'refund_reason_time' => time(), 'refund_reason_wap' => $refundReasonWap, 'refund_reason_wap_explain' => $refundReasonWapExplain, 'refund_reason_wap_img' => json_encode($refundReasonWapImg)], $order['id'], 'id');
  2808. $res = $res1 && $res2;
  2809. self::checkTrans($res);
  2810. if (!$res)
  2811. return self::setErrorInfo('申请退款失败!');
  2812. else {
  2813. try {
  2814. if (in_array($order['is_channel'], [0, 2])) {
  2815. //公众号发送模板消息通知客服
  2816. WechatTemplateService::sendAdminNoticeTemplate([
  2817. 'first' => "亲,有个订单申请退款 \n订单号:{$order['order_id']}",
  2818. 'keyword1' => '退款申请',
  2819. 'keyword2' => '已支付',
  2820. 'keyword3' => date('Y/m/d H:i', time()),
  2821. 'remark' => '请及时处理'
  2822. ]);
  2823. }
  2824. if (in_array($order['is_channel'], [1, 2])) {
  2825. //小程序 发送模板消息
  2826. RoutineTemplate::sendOrderRefundStatus($order, $refundReasonWap);
  2827. }
  2828. //通知后台消息提醒
  2829. ChannelService::instance()->send('NEW_REFUND_ORDER', ['order_id' => $order['order_id']]);
  2830. } catch (\Exception $e) {
  2831. }
  2832. //发送短信
  2833. event('ShortMssageSend', [$order['order_id'], 'AdminRefund']);
  2834. return true;
  2835. }
  2836. }
  2837. /**
  2838. * //TODO 支付成功后
  2839. * @param $orderId
  2840. * @param string $paytype
  2841. * @param string $formId
  2842. * @return bool
  2843. * @throws DataNotFoundException
  2844. * @throws DbException
  2845. * @throws ModelNotFoundException
  2846. */
  2847. public static function paySuccess($orderId, $paytype = 'weixin', $formId = '')
  2848. {
  2849. $order = self::where('order_id', $orderId)->find();
  2850. $resPink = true;
  2851. $res1 = self::where('order_id', $orderId)->update(['paid' => 1, 'pay_type' => $paytype, 'pay_time' => time(), 'is_del' => 0, 'is_system_del' => 0, 'mark' => '']);//订单改为支付
  2852. if ($order->combination_id && $res1 && !$order->refund_status) $resPink = StorePink::createPink($order);//创建拼团
  2853. $oid = self::where('order_id', $orderId)->value('id');
  2854. StoreOrderStatus::status($oid, 'pay_success', '用户付款成功');
  2855. $now_money = User::where('uid', $order['uid'])->value('now_money');
  2856. UserBill::expend('购买商品', $order['uid'], 'now_money', 'pay_money', $order['pay_price'], $order['id'], $now_money, '支付' . floatval($order['pay_price']) . '元购买商品');
  2857. //支付成功后
  2858. event('OrderPaySuccess', [$order, $formId]);
  2859. self::push($order);
  2860. $res = $res1 && $resPink && UserSpread::setSpreadSure($order['uid']) && User::backOrderBrokerage($order);
  2861. return false !== $res;
  2862. }
  2863. /**
  2864. * 直推奖励
  2865. * @param $order
  2866. * @return void
  2867. */
  2868. public static function push($order)
  2869. {
  2870. $user = User::where('uid', $order['uid'])->find();
  2871. if ($user['spread_uid']){
  2872. $spread = User::where('uid', $user['spread_uid'])->where('level', 2)->find();
  2873. if ($spread){
  2874. //直推上级是团队
  2875. $group_purchase = sys_config('group_purchase');
  2876. $jl = round($order['pay_price'] * ($group_purchase/100), 2);
  2877. UserBill::income('佣金', $spread['uid'], 'now_money', 'brokerage', $jl, '', $spread['brokerage_price']+$jl, '直推佣金奖励');
  2878. User::where('uid', $spread['uid'])->inc('brokerage_price', $jl)->update();
  2879. }
  2880. }
  2881. }
  2882. /*
  2883. * 线下支付消息通知
  2884. * 待完善
  2885. *
  2886. * */
  2887. public static function createOrderTemplate($order)
  2888. {
  2889. //$goodsName = StoreOrderCartInfo::getProductNameList($order['id']);
  2890. // RoutineTemplateService::sendTemplate(WechatUser::getOpenId($order['uid']),RoutineTemplateService::ORDER_CREATE, [
  2891. // 'first'=>'亲,您购买的商品已支付成功',
  2892. // 'keyword1'=>date('Y/m/d H:i',$order['add_time']),
  2893. // 'keyword2'=>implode(',',$goodsName),
  2894. // 'keyword3'=>$order['order_id'],
  2895. // 'remark'=>'点击查看订单详情'
  2896. // ],Url::build('/wap/My/order',['uni'=>$order['order_id']],true,true));
  2897. // RoutineTemplateService::sendAdminNoticeTemplate([
  2898. // 'first'=>"亲,您有一个新订单 \n订单号:{$order['order_id']}",
  2899. // 'keyword1'=>'新订单',
  2900. // 'keyword2'=>'线下支付',
  2901. // 'keyword3'=>date('Y/m/d H:i',time()),
  2902. // 'remark'=>'请及时处理'
  2903. // ]);
  2904. }
  2905. /**
  2906. * 获取订单详情
  2907. * @param $uid
  2908. * @param $key
  2909. * @return array|\think\Model|null
  2910. * @throws DataNotFoundException
  2911. * @throws ModelNotFoundException
  2912. * @throws \think\exception\DbException
  2913. */
  2914. public static function getUserOrderDetail($uid, $key)
  2915. {
  2916. return self::where('order_id|unique', $key)->where('uid', $uid)->where('is_del', 0)->find();
  2917. }
  2918. /**
  2919. * TODO 订单发货
  2920. * @param array $postageData 发货信息
  2921. * @param string $oid orderID
  2922. */
  2923. public static function orderPostageAfter($postageData, $oid)
  2924. {
  2925. $order = self::where('id', $oid)->find();
  2926. if ($postageData['delivery_type'] == 'send') {//送货
  2927. RoutineTemplate::sendOrderPostage($order);
  2928. } else if ($postageData['delivery_type'] == 'express') {//发货
  2929. RoutineTemplate::sendOrderPostage($order, 1);
  2930. }
  2931. }
  2932. /** 收货后发送模版消息
  2933. * @param $order
  2934. */
  2935. public static function orderTakeAfter($order)
  2936. {
  2937. $title = self::getProductTitle($order['cart_id']);
  2938. if ($order['is_channel'] == 1) {//小程序
  2939. RoutineTemplate::sendOrderTakeOver($order, $title);
  2940. } else {
  2941. $openid = WechatUser::where('uid', $order['uid'])->value('openid');
  2942. \crmeb\services\WechatTemplateService::sendTemplate($openid, \crmeb\services\WechatTemplateService::ORDER_TAKE_SUCCESS, [
  2943. 'first' => '亲,您的订单已收货',
  2944. 'keyword1' => $order['order_id'],
  2945. 'keyword2' => '已收货',
  2946. 'keyword3' => date('Y-m-d H:i:s', time()),
  2947. 'keyword4' => $title,
  2948. 'remark' => '感谢您的光临!'
  2949. ]);
  2950. }
  2951. }
  2952. /**
  2953. * 删除订单
  2954. * @param $uni
  2955. * @param $uid
  2956. * @return bool
  2957. */
  2958. public static function removeOrder($uni, $uid)
  2959. {
  2960. $order = self::getUserOrderDetail($uid, $uni);
  2961. if (!$order) return self::setErrorInfo('订单不存在!');
  2962. $order = self::tidyOrder($order);
  2963. if ($order['_status']['_type'] != 0 && $order['_status']['_type'] != -2 && $order['_status']['_type'] != 4)
  2964. return self::setErrorInfo('该订单无法删除!');
  2965. if (false !== self::edit(['is_del' => 1], $order['id'], 'id') && false !== StoreOrderStatus::status($order['id'], 'remove_order', '删除订单')) {
  2966. //未支付和已退款的状态下才可以退积分退库存退优惠券
  2967. if ($order['_status']['_type'] == 0 || $order['_status']['_type'] == -2) {
  2968. event('StoreOrderRegressionAllAfter', [$order]);
  2969. }
  2970. event('UserOrderRemoved', $uni);
  2971. return true;
  2972. } else
  2973. return self::setErrorInfo('订单删除失败!');
  2974. }
  2975. /**
  2976. * //TODO 用户确认收货
  2977. * @param $uni
  2978. * @param $uid
  2979. */
  2980. public static function takeOrder($uni, $uid)
  2981. {
  2982. $order = self::getUserOrderDetail($uid, $uni);
  2983. if (!$order) return self::setErrorInfo('订单不存在!');
  2984. $order = self::tidyOrder($order);
  2985. if ($order['_status']['_type'] != 2) return self::setErrorInfo('订单状态错误!');
  2986. self::beginTrans();
  2987. if (false !== self::edit(['status' => 2], $order['id'], 'id') &&
  2988. false !== StoreOrderStatus::status($order['id'], 'user_take_delivery', '用户已收货')) {
  2989. try {
  2990. OrderRepository::storeProductOrderUserTakeDelivery($order, $uid);
  2991. UserBill::where('uid', $order['uid'])->where('link_id', $order['id'])->where('type', 'pay_money')->update(['take' => 1]);
  2992. } catch (\Exception $e) {
  2993. self::rollbackTrans();
  2994. return self::setErrorInfo($e->getMessage());
  2995. }
  2996. self::cumulative($order);
  2997. self::team($order);
  2998. self::proxy($order);
  2999. self::commitTrans();
  3000. UserLevel::setLevelComplete($uid);
  3001. event('UserLevelAfter', [User::get($uni)]);
  3002. event('UserOrderTake', $uni);
  3003. //短信通知
  3004. event('ShortMssageSend', [$order['order_id'], ['Receiving', 'AdminConfirmTakeOver']]);
  3005. return true;
  3006. } else {
  3007. self::rollbackTrans();
  3008. return false;
  3009. }
  3010. }
  3011. /**
  3012. * 参与累计金额
  3013. * @param $order
  3014. * @return void
  3015. */
  3016. public static function cumulative($order)
  3017. {
  3018. User::where('uid', $order['uid'])->inc('pay_price', $order['pay_price'])->update();
  3019. $user = User::where('uid', $order['uid'])->find();
  3020. $partake = UserPartake::where('uid', $order['uid'])->where('status', 0)->find();
  3021. if ($partake){
  3022. $out = Out::where('id', $partake['out_id'])->find();
  3023. if ($user['pay_price'] >= $out['number']){
  3024. $user['pay_price'] -= $out['number'];
  3025. $user['use_price'] += $out['number'];
  3026. $user->save();
  3027. $partake['status'] = 1;
  3028. $partake['money'] = $out['number'];
  3029. $partake->save();
  3030. }
  3031. }
  3032. }
  3033. /**
  3034. * 发放团队奖励
  3035. * @param $order
  3036. * @return void
  3037. */
  3038. public static function team($order)
  3039. {
  3040. $user = User::where('uid', $order['uid'])->find();
  3041. $uids = getParents($user['spread_uid'],User::select());
  3042. if ($uids){
  3043. $v1 = 0;//团队
  3044. $v2 = 0;//联创
  3045. $city = sys_config('city')/100;//城市比列
  3046. $lianchuang = sys_config('lianchuang')/100;//联创比列
  3047. foreach ($uids as $item)
  3048. {
  3049. $spread = User::where('uid', $item)->find();
  3050. if ($spread['level'] == 3){
  3051. if ($v1 == 0){
  3052. $jl = $order['pay_price'] * $city;
  3053. UserBill::income('佣金', $spread['uid'], 'now_money', 'brokerage', $jl, '', $spread['brokerage_price']+$jl, '下级消费'.$order['pay_price'].'城市合伙人团队佣金');
  3054. User::where('uid', $spread['uid'])->inc('brokerage_price', $jl)->update();
  3055. $v1++;
  3056. }
  3057. }
  3058. if ($spread['level'] == 4){
  3059. if ($v2 == 0){
  3060. $jl = $order['pay_price'] * $lianchuang;
  3061. UserBill::income('佣金', $spread['uid'], 'now_money', 'brokerage', $jl, '', $spread['brokerage_price']+$jl, '下级消费'.$order['pay_price'].'联创团队佣金');
  3062. User::where('uid', $spread['uid'])->inc('brokerage_price', $jl)->update();
  3063. $v2++;
  3064. }
  3065. }
  3066. }
  3067. }
  3068. }
  3069. /**
  3070. * 发放落地奖励
  3071. * @param $order
  3072. * @param $uid
  3073. * @return void
  3074. */
  3075. public static function proxy($order)
  3076. {
  3077. $address = explode(' ', $order['user_address']);
  3078. $proxy = ProxyAddress::where(['province' => $address[0], 'city' => $address[1], 'district' => $address[2]])->select()->toArray();
  3079. foreach ($proxy as $item)
  3080. {
  3081. $user = User::where('uid', $item['uid'])->find();
  3082. if ($user['level'] == 3){
  3083. $to_ground = sys_config('to_ground');
  3084. $jl = $order['pay_price'] * ($to_ground/100);
  3085. UserBill::income('佣金', $user['uid'], 'now_money', 'brokerage', $jl, '', $user['brokerage_price']+$jl, '落地奖励佣金');
  3086. User::where('uid', $user['uid'])->inc('brokerage_price', $jl)->update();
  3087. }
  3088. }
  3089. }
  3090. /**
  3091. * 获取订单状态购物车等信息
  3092. * @param $order
  3093. * @param bool $detail 是否获取订单购物车详情
  3094. * @param bool $isPic 是否获取订单状态图片
  3095. * @return mixed
  3096. * @throws DataNotFoundException
  3097. * @throws ModelNotFoundException
  3098. * @throws \think\exception\DbException
  3099. */
  3100. public static function tidyOrder($order, $detail = false, $isPic = false)
  3101. {
  3102. if ($detail == true && isset($order['id'])) {
  3103. $cartInfo = StoreOrderCartInfo::where('oid', $order['id'])->column('cart_info', 'unique') ?: [];
  3104. $info = [];
  3105. foreach ($cartInfo as $k => $cart) {
  3106. $cart = json_decode($cart, true);
  3107. $cart['unique'] = $k;
  3108. //新增是否评价字段
  3109. $cart['is_reply'] = StoreProductReply::where('unique', $k)->count();
  3110. array_push($info, $cart);
  3111. unset($cart);
  3112. }
  3113. $order['cartInfo'] = $info;
  3114. }
  3115. $status = [];
  3116. if (!$order['paid'] && $order['pay_type'] == 'offline' && !$order['status'] >= 2) {
  3117. $status['_type'] = 9;
  3118. $status['_title'] = '线下付款';
  3119. $status['_msg'] = '商家处理中,请耐心等待';
  3120. $status['_class'] = 'nobuy';
  3121. } else if (!$order['paid']) {
  3122. $status['_type'] = 0;
  3123. $status['_title'] = '未支付';
  3124. //系统预设取消订单时间段
  3125. $keyValue = ['order_cancel_time', 'order_activity_time', 'order_bargain_time', 'order_seckill_time', 'order_pink_time'];
  3126. //获取配置
  3127. $systemValue = SystemConfigService::more($keyValue);
  3128. //格式化数据
  3129. $systemValue = self::setValeTime($keyValue, is_array($systemValue) ? $systemValue : []);
  3130. if ($order['pink_id'] || $order['combination_id']) {
  3131. $order_pink_time = $systemValue['order_pink_time'] ? $systemValue['order_pink_time'] : $systemValue['order_activity_time'];
  3132. $time = bcadd($order['add_time'], $order_pink_time * 3600, 0);
  3133. $status['_msg'] = '请在' . date('m-d H:i:s', $time) . '前完成支付!';
  3134. } else if ($order['seckill_id']) {
  3135. $order_seckill_time = $systemValue['order_seckill_time'] ? $systemValue['order_seckill_time'] : $systemValue['order_activity_time'];
  3136. $time = bcadd($order['add_time'], $order_seckill_time * 3600, 0);
  3137. $status['_msg'] = '请在' . date('m-d H:i:s', $time) . '前完成支付!';
  3138. } else if ($order['bargain_id']) {
  3139. $order_bargain_time = $systemValue['order_bargain_time'] ? $systemValue['order_bargain_time'] : $systemValue['order_activity_time'];
  3140. $time = bcadd($order['add_time'], $order_bargain_time * 3600, 0);
  3141. $status['_msg'] = '请在' . date('m-d H:i:s', $time) . '前完成支付!';
  3142. } else {
  3143. $time = bcadd($order['add_time'], $systemValue['order_cancel_time'] * 3600, 0);
  3144. $status['_msg'] = '请在' . date('m-d H:i:s', $time) . '前完成支付!';
  3145. }
  3146. $status['_class'] = 'nobuy';
  3147. } else if ($order['refund_status'] == 1) {
  3148. $status['_type'] = -1;
  3149. $status['_title'] = '申请退款中';
  3150. $status['_msg'] = '商家审核中,请耐心等待';
  3151. $status['_class'] = 'state-sqtk';
  3152. } else if ($order['refund_status'] == 2) {
  3153. $status['_type'] = -2;
  3154. $status['_title'] = '已退款';
  3155. $status['_msg'] = '已为您退款,感谢您的支持';
  3156. $status['_class'] = 'state-sqtk';
  3157. } else if (!$order['status']) {
  3158. if ($order['pink_id']) {
  3159. if (StorePink::where('id', $order['pink_id'])->where('status', 1)->count()) {
  3160. $status['_type'] = 1;
  3161. $status['_title'] = '拼团中';
  3162. $status['_msg'] = '等待其他人参加拼团';
  3163. $status['_class'] = 'state-nfh';
  3164. } else {
  3165. $status['_type'] = 1;
  3166. $status['_title'] = '未发货';
  3167. $status['_msg'] = '商家未发货,请耐心等待';
  3168. $status['_class'] = 'state-nfh';
  3169. }
  3170. } else {
  3171. if ($order['shipping_type'] === 1) {
  3172. $status['_type'] = 1;
  3173. $status['_title'] = '未发货';
  3174. $status['_msg'] = '商家未发货,请耐心等待';
  3175. $status['_class'] = 'state-nfh';
  3176. } else {
  3177. $status['_type'] = 1;
  3178. $status['_title'] = '待核销';
  3179. $status['_msg'] = '待核销,请到核销点进行核销';
  3180. $status['_class'] = 'state-nfh';
  3181. }
  3182. }
  3183. } else if ($order['status'] == 1) {
  3184. if ($order['delivery_type'] == 'send') {//TODO 送货
  3185. $status['_type'] = 2;
  3186. $status['_title'] = '待收货';
  3187. $status['_msg'] = date('m月d日H时i分', StoreOrderStatus::getTime($order['id'], 'delivery')) . '服务商已送货';
  3188. $status['_class'] = 'state-ysh';
  3189. } else {//TODO 发货
  3190. $status['_type'] = 2;
  3191. $status['_title'] = '待收货';
  3192. if ($order['delivery_type'] == 'fictitious')
  3193. $_time = StoreOrderStatus::getTime($order['id'], 'delivery_fictitious');
  3194. else
  3195. $_time = StoreOrderStatus::getTime($order['id'], 'delivery_goods');
  3196. $status['_msg'] = date('m月d日H时i分', $_time) . '服务商已发货';
  3197. $status['_class'] = 'state-ysh';
  3198. }
  3199. } else if ($order['status'] == 2) {
  3200. $status['_type'] = 3;
  3201. $status['_title'] = '待评价';
  3202. $status['_msg'] = '已收货,快去评价一下吧';
  3203. $status['_class'] = 'state-ypj';
  3204. } else if ($order['status'] == 3) {
  3205. $status['_type'] = 4;
  3206. $status['_title'] = '交易完成';
  3207. $status['_msg'] = '交易完成,感谢您的支持';
  3208. $status['_class'] = 'state-ytk';
  3209. }
  3210. if (isset($order['pay_type']))
  3211. $status['_payType'] = isset(self::$payType[$order['pay_type']]) ? self::$payType[$order['pay_type']] : '其他方式';
  3212. if (isset($order['delivery_type']))
  3213. $status['_deliveryType'] = isset(self::$deliveryType[$order['delivery_type']]) ? self::$deliveryType[$order['delivery_type']] : '其他方式';
  3214. $order['_status'] = $status;
  3215. $order['_pay_time'] = isset($order['pay_time']) && $order['pay_time'] != null ? date('Y-m-d H:i:s', $order['pay_time']) : date('Y-m-d H:i:s', $order['add_time']);
  3216. $order['_add_time'] = isset($order['add_time']) ? (strstr($order['add_time'], '-') === false ? date('Y-m-d H:i:s', $order['add_time']) : $order['add_time']) : '';
  3217. $order['status_pic'] = '';
  3218. //获取产品状态图片
  3219. if ($isPic) {
  3220. $order_details_images = sys_data('order_details_images') ?: [];
  3221. foreach ($order_details_images as $image) {
  3222. if (isset($image['order_status']) && $image['order_status'] == $order['_status']['_type']) {
  3223. $order['status_pic'] = $image['pic'];
  3224. break;
  3225. }
  3226. }
  3227. }
  3228. $order['offlinePayStatus'] = (int)sys_config('offline_pay_status') ?? (int)2;
  3229. return $order;
  3230. }
  3231. /**
  3232. * 设置订单查询状态
  3233. * @param $status
  3234. * @param int $uid
  3235. * @param null $model
  3236. * @return StoreOrder|null
  3237. */
  3238. public static function statusByWhere($status, $uid = 0, $model = null)
  3239. {
  3240. // $orderId = StorePink::where('uid',$uid)->where('status',1)->column('order_id','id');//获取正在拼团的订单编号
  3241. if ($model == null) $model = new self;
  3242. if ('' === $status)
  3243. return $model;
  3244. else if ($status == 0)//未支付
  3245. return $model->where('paid', 0)->where('status', 0)->where('refund_status', 0);
  3246. else if ($status == 1)//待发货
  3247. return $model->where('paid', 1)->where('status', 0)->where('refund_status', 0);
  3248. else if ($status == 2)//待收货
  3249. return $model->where('paid', 1)->where('status', 1)->where('refund_status', 0);
  3250. else if ($status == 3)//待评价
  3251. return $model->where('paid', 1)->where('status', 2)->where('refund_status', 0);
  3252. else if ($status == 4)//已完成
  3253. return $model->where('paid', 1)->where('status', 3)->where('refund_status', 0);
  3254. else if ($status == -1)//退款中
  3255. return $model->where('paid', 1)->where('refund_status', 1);
  3256. else if ($status == -2)//已退款
  3257. return $model->where('paid', 1)->where('refund_status', 2);
  3258. else if ($status == -3)//退款
  3259. return $model->where('paid', 1)->where('refund_status', 'IN', '1,2');
  3260. // else if($status == 11){
  3261. // return $model->where('order_id','IN',implode(',',$orderId));
  3262. // }
  3263. else
  3264. return $model;
  3265. }
  3266. /**
  3267. * 获取订单并分页
  3268. * @param $uid
  3269. * @param string $status
  3270. * @param int $page
  3271. * @param int $limit
  3272. * @return mixed
  3273. * @throws DataNotFoundException
  3274. * @throws ModelNotFoundException
  3275. * @throws \think\exception\DbException
  3276. */
  3277. public static function getUserOrderList($uid, $status = '', $page = 0, $limit = 8)
  3278. {
  3279. if ($page) $list = self::statusByWhere($status, $uid)->where('is_del', 0)->where('uid', $uid)
  3280. ->field('add_time,seckill_id,bargain_id,combination_id,id,order_id,pay_price,total_num,total_price,pay_postage,total_postage,paid,status,refund_status,pay_type,coupon_price,deduction_price,pink_id,delivery_type,is_del,shipping_type')
  3281. ->order('add_time DESC')->page((int)$page, (int)$limit)->select()->toArray();
  3282. else $list = self::statusByWhere($status, $uid)->where('is_del', 0)->where('uid', $uid)
  3283. ->field('add_time,seckill_id,bargain_id,combination_id,id,order_id,pay_price,total_num,total_price,pay_postage,total_postage,paid,status,refund_status,pay_type,coupon_price,deduction_price,pink_id,delivery_type,is_del,shipping_type')
  3284. ->order('add_time DESC')->page((int)$page, (int)$limit)->select()->toArray();
  3285. foreach ($list as $k => $order) {
  3286. $list[$k] = self::tidyOrder($order, true);
  3287. }
  3288. return $list;
  3289. }
  3290. /**
  3291. * 获取推广人地下用户的订单金额
  3292. * @param string $uid
  3293. * @param string $status
  3294. * @return array
  3295. */
  3296. public static function getUserOrderCount($uid = '', $status = '')
  3297. {
  3298. $res = self::statusByWhere($status, $uid)->where('uid', 'IN', $uid)->column('pay_price');
  3299. return $res;
  3300. }
  3301. /**
  3302. * 搜索某个订单详细信息
  3303. * @param $uid
  3304. * @param $order_id
  3305. * @return bool|mixed
  3306. * @throws DataNotFoundException
  3307. * @throws ModelNotFoundException
  3308. * @throws \think\exception\DbException
  3309. */
  3310. public static function searchUserOrder($uid, $order_id)
  3311. {
  3312. $order = self::where('uid', $uid)->where('order_id', $order_id)->where('is_del', 0)->field('seckill_id,bargain_id,combination_id,id,order_id,pay_price,total_num,total_price,pay_postage,total_postage,paid,status,refund_status,pay_type,coupon_price,deduction_price,delivery_type,shipping_type')
  3313. ->order('add_time DESC')->find();
  3314. if (!$order)
  3315. return false;
  3316. else
  3317. return self::tidyOrder($order->toArray(), true);
  3318. }
  3319. /**
  3320. * 订单评价信息记录
  3321. * @param $oid
  3322. * @return StoreOrderStatus|\think\Model
  3323. * @throws \Exception
  3324. */
  3325. public static function orderOver($oid)
  3326. {
  3327. $res = self::edit(['status' => '3'], $oid, 'id');
  3328. if (!$res) exception('评价后置操作失败!');
  3329. return StoreOrderStatus::status($oid, 'check_order_over', '用户评价');
  3330. }
  3331. /**
  3332. * 设置订单产品评价完毕事件
  3333. * @param $oid
  3334. * @return StoreOrderStatus|\think\Model
  3335. * @throws \Exception
  3336. */
  3337. public static function checkOrderOver($oid)
  3338. {
  3339. $uniqueList = StoreOrderCartInfo::where('oid', $oid)->column('unique', 'unique');
  3340. //订单产品全部评价完成
  3341. if (StoreProductReply::where('unique', 'IN', $uniqueList)->where('oid', $oid)->count() == count($uniqueList)) {
  3342. event('StoreProductOrderOver', [$oid]);
  3343. return self::orderOver($oid);
  3344. }
  3345. }
  3346. public static function getOrderStatusNum($uid)
  3347. {
  3348. $noBuy = (int)self::where('uid', $uid)->where('paid', 0)->where('is_del', 0)->where('pay_type', '<>', 'offline')->count();
  3349. $noPostageNoPink = (int)self::where('o.uid', $uid)->alias('o')->where('o.paid', 1)->where('o.pink_id', 0)->where('o.is_del', 0)->where('o.status', 0)->where('o.pay_type', '<>', 'offline')->count();
  3350. $noPostageYesPink = (int)self::where('o.uid', $uid)->alias('o')->join('StorePink p', 'o.pink_id = p.id')->where('p.status', 2)->where('o.paid', 1)->where('o.is_del', 0)->where('o.status', 0)->where('o.pay_type', '<>', 'offline')->count();
  3351. $noPostage = (int)bcadd($noPostageNoPink, $noPostageYesPink, 0);
  3352. $noTake = (int)self::where('uid', $uid)->where('paid', 1)->where('is_del', 0)->where('status', 1)->where('pay_type', '<>', 'offline')->count();
  3353. $noReply = (int)self::where('uid', $uid)->where('paid', 1)->where('is_del', 0)->where('status', 2)->count();
  3354. $noPink = (int)self::where('o.uid', $uid)->alias('o')->join('StorePink p', 'o.pink_id = p.id')->where('p.status', 1)->where('o.paid', 1)->where('o.is_del', 0)->where('o.status', 0)->where('o.pay_type', '<>', 'offline')->count();
  3355. $noRefund = (int)self::where('uid', $uid)->where('paid', 1)->where('is_del', 0)->where('refund_status', 'IN', '1,2')->count();
  3356. return compact('noBuy', 'noPostage', 'noTake', 'noReply', 'noPink', 'noRefund');
  3357. }
  3358. /**
  3359. * 购买商品赠送积分
  3360. * @param $order
  3361. * @return bool
  3362. * @throws \think\Exception
  3363. * @throws DataNotFoundException
  3364. * @throws ModelNotFoundException
  3365. * @throws \think\exception\DbException
  3366. */
  3367. public static function gainUserIntegral($order)
  3368. {
  3369. if ($order['gain_integral'] > 0) {
  3370. $userInfo = User::getUserInfo($order['uid']);
  3371. BaseModel::beginTrans();
  3372. $res1 = false != User::where('uid', $userInfo['uid'])->update(['integral' => bcadd($userInfo['integral'], $order['gain_integral'], 2)]);
  3373. $res2 = false != UserBill::income('购买商品赠送积分', $order['uid'], 'integral', 'gain', $order['gain_integral'], $order['id'], $userInfo['integral'], '购买商品赠送' . floatval($order['gain_integral']) . '积分');
  3374. $res = $res1 && $res2;
  3375. BaseModel::checkTrans($res);
  3376. return $res;
  3377. }
  3378. return true;
  3379. }
  3380. /**
  3381. * 获取当前订单中有没有拼团存在
  3382. * @param $pid
  3383. * @return int|string
  3384. */
  3385. public static function getIsOrderPink($pid = 0, $uid = 0)
  3386. {
  3387. return self::where('uid', $uid)->where('pink_id', $pid)->where('refund_status', 0)->where('is_del', 0)->count();
  3388. }
  3389. /**
  3390. * 获取order_id
  3391. * @param $pid
  3392. * @return mixed
  3393. */
  3394. public static function getStoreIdPink($pid = 0, $uid = 0)
  3395. {
  3396. return self::where('uid', $uid)->where('pink_id', $pid)->where('is_del', 0)->value('order_id');
  3397. }
  3398. /**
  3399. * 删除当前用户拼团未支付的订单
  3400. */
  3401. public static function delCombination()
  3402. {
  3403. self::where('combination', '>', 0)->where('paid', 0)->where('uid', User::getActiveUid())->delete();
  3404. }
  3405. public static function getUserPrice($uid = 0)
  3406. {
  3407. if (!$uid) return 0;
  3408. $price = self::where('paid', 1)->where('uid', $uid)->where('status', 2)->where('refund_status', 0)->column('pay_price', 'id');
  3409. $count = 0;
  3410. if ($price) {
  3411. foreach ($price as $v) {
  3412. $count = bcadd($count, $v, 2);
  3413. }
  3414. }
  3415. return $count;
  3416. }
  3417. /**
  3418. * 个人中心获取个人订单列表和订单搜索
  3419. * @param int $uid 用户uid
  3420. * @param int | string 查找订单类型
  3421. * @param int $first 分页
  3422. * @param int 每页显示多少条
  3423. * @param string $search 订单号
  3424. * @return array
  3425. * */
  3426. public static function getUserOrderSearchList($uid, $type, $page, $limit, $search)
  3427. {
  3428. if ($search) {
  3429. $order = self::searchUserOrder($uid, $search) ?: [];
  3430. $list = $order == false ? [] : [$order];
  3431. } else {
  3432. $list = self::getUserOrderList($uid, $type, $page, $limit);
  3433. }
  3434. foreach ($list as $k => $order) {
  3435. $list[$k] = self::tidyOrder($order, true);
  3436. if ($list[$k]['_status']['_type'] == 3) {
  3437. foreach ($order['cartInfo'] ?: [] as $key => $product) {
  3438. $list[$k]['cartInfo'][$key]['is_reply'] = StoreProductReply::isReply($product['unique'], 'product');
  3439. $list[$k]['cartInfo'][$key]['add_time'] = isset($product['add_time']) ? date('Y-m-d H:i', $product['add_time']) : '时间错误';
  3440. }
  3441. }
  3442. }
  3443. return $list;
  3444. }
  3445. /**
  3446. * 获取用户下级的订单
  3447. * @param int $xuid 下级用户用户uid
  3448. * @param int $uid 用户uid
  3449. * @param int $type 订单类型
  3450. * @param int $first 截取行数
  3451. * @param int $limit 展示条数
  3452. * @return array
  3453. * */
  3454. public static function getSubordinateOrderlist($xUid, $uid, $type, $first, $limit)
  3455. {
  3456. $list = [];
  3457. if (!$xUid) {
  3458. $arr = User::getOneSpreadUid($uid);
  3459. foreach ($arr as $v) $list = StoreOrder::getUserOrderList($v, $type, $first, $limit);
  3460. } else $list = self::getUserOrderList($xUid, $type, $first, $limit);
  3461. foreach ($list as $k => $order) {
  3462. $list[$k] = self::tidyOrder($order, true);
  3463. if ($list[$k]['_status']['_type'] == 3) {
  3464. foreach ($order['cartInfo'] ?: [] as $key => $product) {
  3465. $list[$k]['cartInfo'][$key]['is_reply'] = StoreProductReply::isReply($product['unique'], 'product');
  3466. }
  3467. }
  3468. }
  3469. return $list;
  3470. }
  3471. /**
  3472. * 获取 今日 昨日 本月 订单金额
  3473. * @return mixed
  3474. */
  3475. public static function getOrderTimeData()
  3476. {
  3477. $to_day = strtotime(date('Y-m-d'));//今日
  3478. $pre_day = strtotime(date('Y-m-d', strtotime('-1 day')));//昨日
  3479. $now_month = strtotime(date('Y-m'));//本月
  3480. //今日成交额
  3481. // $data['todayPrice'] = (float)number_format(self::where('is_del', 0)->where('pay_time', '>=', $to_day)->where('paid', 1)->where('refund_status', 0)->value('sum(pay_price)'), 2) ?? 0;
  3482. $data['todayPrice'] = number_format(self::where('is_del', 0)->where('pay_time', '>=', $to_day)->where('paid', 1)->where('refund_status', 0)->value('sum(pay_price)'), 2) ?? 0;
  3483. //今日订单数
  3484. $data['todayCount'] = self::where('is_del', 0)->where('pay_time', '>=', $to_day)->where('paid', 1)->where('refund_status', 0)->count();
  3485. //昨日成交额
  3486. $data['proPrice'] = number_format(self::where('is_del', 0)->where('pay_time', '<', $to_day)->where('pay_time', '>=', $pre_day)->where('paid', 1)->where('refund_status', 0)->value('sum(pay_price)'), 2) ?? 0;
  3487. //昨日订单数
  3488. $data['proCount'] = self::where('is_del', 0)->where('pay_time', '<', $to_day)->where('pay_time', '>=', $pre_day)->where('paid', 1)->where('refund_status', 0)->count();
  3489. //本月成交额
  3490. $data['monthPrice'] = number_format(self::where('is_del', 0)->where('pay_time', '>=', $now_month)->where('paid', 1)->where('refund_status', 0)->value('sum(pay_price)'), 2) ?? 0;
  3491. //本月订单数
  3492. $data['monthCount'] = self::where('is_del', 0)->where('pay_time', '>=', $now_month)->where('paid', 1)->where('refund_status', 0)->count();
  3493. return $data;
  3494. }
  3495. /**
  3496. * 获取某个用户的订单统计数据
  3497. * @param $uid
  3498. * @return mixed
  3499. */
  3500. public static function getOrderData($uid)
  3501. {
  3502. //订单支付没有退款 数量
  3503. $data['order_count'] = self::where('is_del', 0)->where('paid', 1)->where('uid', $uid)->where('refund_status', 0)->count();
  3504. //订单支付没有退款 支付总金额
  3505. $data['sum_price'] = self::where('is_del', 0)->where('paid', 1)->where('uid', $uid)->where('refund_status', 0)->sum('pay_price');
  3506. //订单待支付 数量
  3507. $data['unpaid_count'] = self::statusByWhere(0, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  3508. //订单待发货 数量
  3509. $data['unshipped_count'] = self::statusByWhere(1, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  3510. //订单待收货 数量
  3511. $data['received_count'] = self::statusByWhere(2, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  3512. //订单待评价 数量
  3513. $data['evaluated_count'] = self::statusByWhere(3, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  3514. //订单已完成 数量
  3515. $data['complete_count'] = self::statusByWhere(4, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  3516. //订单退款
  3517. $data['refund_count'] = self::statusByWhere(-1, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  3518. return $data;
  3519. }
  3520. /**
  3521. * 获取订单统计数据
  3522. * @param $uid
  3523. * @return mixed
  3524. */
  3525. public static function getOrderDataAdmin()
  3526. {
  3527. //订单支付没有退款 数量
  3528. $data['order_count'] = self::where('is_del', 0)->where('paid', 1)->where('refund_status', 0)->count();
  3529. //订单支付没有退款 支付总金额
  3530. $data['sum_price'] = self::where('is_del', 0)->where('paid', 1)->where('refund_status', 0)->sum('pay_price');
  3531. //订单待支付 数量
  3532. $data['unpaid_count'] = self::statusByWhere(0, 0)->where('is_del', 0)->count();
  3533. //订单待发货 数量
  3534. $data['unshipped_count'] = self::statusByWhere(1, 0)->where('is_del', 0)->count();
  3535. //订单待收货 数量
  3536. $data['received_count'] = self::statusByWhere(2, 0)->where('is_del', 0)->count();
  3537. //订单待评价 数量
  3538. $data['evaluated_count'] = self::statusByWhere(3, 0)->where('is_del', 0)->count();
  3539. //订单已完成 数量
  3540. $data['complete_count'] = self::statusByWhere(4, 0)->where('is_del', 0)->count();
  3541. //订单退款 数量
  3542. $data['refund_count'] = self::statusByWhere(-3, 0)->where('is_del', 0)->count();
  3543. return $data;
  3544. }
  3545. /**
  3546. * 累计消费
  3547. * @param $uid
  3548. * @return float
  3549. */
  3550. public static function getOrderStatusSum($uid)
  3551. {
  3552. return self::where('uid', $uid)->where('is_del', 0)->where('paid', 1)->sum('pay_price');
  3553. }
  3554. public static function getPinkOrderId($id)
  3555. {
  3556. return self::where('id', $id)->value('order_id');
  3557. }
  3558. /**
  3559. * 未支付订单自动取消
  3560. * @param int $limit 分页截取条数
  3561. * @param string $prefid 缓存名称
  3562. * @param int $expire 缓存时间
  3563. * @return string|null
  3564. * @throws \Psr\SimpleCache\InvalidArgumentException
  3565. */
  3566. public static function orderUnpaidCancel()
  3567. {
  3568. //系统预设取消订单时间段
  3569. $keyValue = ['order_cancel_time', 'order_activity_time', 'order_bargain_time', 'order_seckill_time', 'order_pink_time'];
  3570. //获取配置
  3571. $systemValue = SystemConfigService::more($keyValue);
  3572. //格式化数据
  3573. $systemValue = self::setValeTime($keyValue, is_array($systemValue) ? $systemValue : []);
  3574. //检查是否有未支付的订单 未支付查询条件
  3575. $unPidCount = self::where('paid', 0)->where('pay_type', '<>', 'offline')->where('is_del', 0)->where('status', 0)->where('refund_status', 0)->count();
  3576. if (!$unPidCount) return null;
  3577. try {
  3578. $res = true;
  3579. // 未支付查询条件
  3580. $orderList = self::where('paid', 0)->where('pay_type', '<>', 'offline')->where('is_del', 0)->where('status', 0)->where('refund_status', 0)->field('add_time,pink_id,order_id,seckill_id,bargain_id,combination_id,status,cart_id,use_integral,refund_status,uid,unique,back_integral,coupon_id,paid,is_del')->select();
  3581. foreach ($orderList as $order) {
  3582. if ($order['seckill_id']) {
  3583. //优先使用单独配置的过期时间
  3584. $order_seckill_time = $systemValue['order_seckill_time'] ? $systemValue['order_seckill_time'] : $systemValue['order_activity_time'];
  3585. $res = $res && self::RegressionAll($order_seckill_time, $order);
  3586. unset($order_seckill_time);
  3587. } else if ($order['bargain_id']) {
  3588. $order_bargain_time = $systemValue['order_bargain_time'] ? $systemValue['order_bargain_time'] : $systemValue['order_activity_time'];
  3589. $res = $res && self::RegressionAll($order_bargain_time, $order);
  3590. unset($order_bargain_time);
  3591. } else if ($order['pink_id'] || $order['combination_id']) {
  3592. $order_pink_time = $systemValue['order_pink_time'] ? $systemValue['order_pink_time'] : $systemValue['order_activity_time'];
  3593. $res = $res && self::RegressionAll($order_pink_time, $order);
  3594. unset($order_pink_time);
  3595. } else {
  3596. $res = $res && self::RegressionAll($systemValue['order_cancel_time'], $order);
  3597. }
  3598. }
  3599. if (!$res) throw new \Exception('更新错误');
  3600. unset($orderList, $res, $pages);
  3601. return null;
  3602. } catch (PDOException $e) {
  3603. Log::error('未支付自动取消时发生数据库查询错误,错误原因为:' . $e->getMessage());
  3604. throw new \Exception($e->getMessage());
  3605. } catch (\think\Exception $e) {
  3606. Log::error('未支付自动取消时发生系统错误,错误原因为:' . $e->getMessage());
  3607. throw new \Exception($e->getMessage());
  3608. }
  3609. }
  3610. /**
  3611. * 未支付订单超过预设时间回退所有,如果不设置未支付过期时间,将不取消订单
  3612. * @param $time 预设时间
  3613. * @param $order 订单详情
  3614. * @return bool
  3615. * @throws DataNotFoundException
  3616. * @throws ModelNotFoundException
  3617. * @throws \think\exception\DbException
  3618. */
  3619. protected static function RegressionAll($time, $order)
  3620. {
  3621. if ($time == 0) return true;
  3622. if (($order['add_time'] + bcmul($time, 3600, 0)) < time()) {
  3623. $res1 = self::RegressionStock($order);
  3624. $res2 = self::RegressionIntegral($order);
  3625. $res3 = self::RegressionCoupon($order);
  3626. $res = $res1 && $res2 && $res3;
  3627. if ($res) $res = false !== self::where('order_id', $order['order_id'])->update(['is_del' => 1, 'mark' => '订单未支付已超过系统预设时间']);
  3628. unset($res1, $res2, $res3);
  3629. return $res;
  3630. } else
  3631. return true;
  3632. }
  3633. /**
  3634. * 格式化数据
  3635. * @param array $array 原本数据键
  3636. * @param $value 需要格式化的数据
  3637. * @param int $default 默认值
  3638. * @return mixed
  3639. */
  3640. protected static function setValeTime(array $array, $value, $default = 0)
  3641. {
  3642. foreach ($array as $item) {
  3643. if (!isset($value[$item]))
  3644. $value[$item] = $default;
  3645. else if (is_string($value[$item]))
  3646. $value[$item] = (float)$value[$item];
  3647. }
  3648. return $value;
  3649. }
  3650. public static function getOrderTotalPrice($cartInfo)
  3651. {
  3652. $totalPrice = 0;
  3653. foreach ($cartInfo as $cart) {
  3654. $totalPrice = bcadd($totalPrice, bcmul($cart['cart_num'], $cart['truePrice'], 2), 2);
  3655. }
  3656. return $totalPrice;
  3657. }
  3658. public static function getOrderCostPrice($cartInfo)
  3659. {
  3660. $costPrice = 0;
  3661. foreach ($cartInfo as $cart) {
  3662. $costPrice = bcadd($costPrice, bcmul($cart['cart_num'], $cart['costPrice'], 2), 2);
  3663. }
  3664. return $costPrice;
  3665. }
  3666. public static function getCombinationOrderCostPrice($cartInfo)
  3667. {
  3668. $costPrice = 0;
  3669. foreach ($cartInfo as $cart) {
  3670. if ($cart['combination_id']) {
  3671. $costPrice = bcadd($costPrice, bcmul($cart['cart_num'], StoreCombination::where('id', $cart['combination_id'])->value('price'), 2), 2);
  3672. }
  3673. }
  3674. return (float)$costPrice;
  3675. }
  3676. public static function yueRefundAfter($order)
  3677. {
  3678. }
  3679. /**
  3680. * 获取余额支付的金额
  3681. * @param $uid
  3682. * @return float|int
  3683. */
  3684. public static function getOrderStatusYueSum($uid)
  3685. {
  3686. return self::where('uid', $uid)->where('is_del', 0)->where('is_del', 0)->where('pay_type', 'yue')->where('paid', 1)->sum('pay_price');
  3687. }
  3688. /**
  3689. * 砍价支付成功订单数量
  3690. * @param $bargain
  3691. * @return int
  3692. */
  3693. public static function getBargainPayCount($bargain)
  3694. {
  3695. return self::where('bargain_id', $bargain)->where(['paid' => 1, 'refund_status' => 0])->count();
  3696. }
  3697. /**
  3698. * 7天自动收货
  3699. * @return bool
  3700. */
  3701. public static function startTakeOrder()
  3702. {
  3703. //7天前时间戳
  3704. $systemDeliveryTime = SystemConfigService::get('system_delivery_time') ?? 0;
  3705. //0为取消自动收货功能
  3706. if ($systemDeliveryTime == 0) return true;
  3707. $sevenDay = strtotime(date('Y-m-d H:i:s', strtotime('-' . $systemDeliveryTime . ' day')));
  3708. $model = new self;
  3709. $model = $model->alias('o');
  3710. $model = $model->join('StoreOrderStatus s', 's.oid=o.id');
  3711. $model = $model->where('o.paid', 1);
  3712. $model = $model->where('s.change_type', 'delivery_goods');
  3713. $model = $model->where('s.change_time', '<', $sevenDay);
  3714. $model = $model->where('o.status', 1);
  3715. $model = $model->where('o.refund_status', 0);
  3716. $model = $model->where('o.is_del', 0);
  3717. $orderInfo = $model->column('id', 'id');
  3718. if (!count($orderInfo)) return true;
  3719. $res = true;
  3720. foreach ($orderInfo as $key => &$item) {
  3721. $order = self::get($item);
  3722. if ($order['status'] == 2) continue;
  3723. if ($order['paid'] == 1 && $order['status'] == 1) $data['status'] = 2;
  3724. else if ($order['pay_type'] == 'offline') $data['status'] = 2;
  3725. else continue;
  3726. if (!self::edit($data, $item, 'id')) continue;
  3727. try {
  3728. OrderRepository::storeProductOrderTakeDeliveryAdmin($order, $item);
  3729. $res = $res && true;
  3730. } catch (\Exception $e) {
  3731. $res = $res && false;
  3732. }
  3733. $res = $res && StoreOrderStatus::status($item, 'take_delivery', '已收货[自动收货]');
  3734. }
  3735. if (!$res) {
  3736. throw new \Exception('');
  3737. }
  3738. }
  3739. /**
  3740. * 获取订单信息
  3741. * @param $id
  3742. * @param string $field
  3743. * @return array|null|\think\Model
  3744. * @throws DataNotFoundException
  3745. * @throws ModelNotFoundException
  3746. * @throws \think\exception\DbException
  3747. */
  3748. public static function getOrderInfo($id, $field = 'order_id')
  3749. {
  3750. return self::where('id', $id)->field($field)->find();
  3751. }
  3752. /**
  3753. * 订单每月统计数据
  3754. * @param $page
  3755. * @param $limit
  3756. * @return array
  3757. */
  3758. public static function getOrderDataPriceCount($page, $limit, $start, $stop)
  3759. {
  3760. if (!$limit) return [];
  3761. $model = new self;
  3762. if ($start != '' && $stop != '') $model = $model->where('pay_time', '>', $start)->where('pay_time', '<=', $stop);
  3763. $model = $model->field('sum(pay_price) as price,count(id) as count,FROM_UNIXTIME(pay_time, \'%m-%d\') as time');
  3764. $model = $model->where('is_del', 0);
  3765. $model = $model->where('paid', 1);
  3766. $model = $model->where('refund_status', 0);
  3767. $model = $model->group("FROM_UNIXTIME(pay_time, '%Y-%m-%d')");
  3768. $model = $model->order('pay_time DESC');
  3769. if ($page) $model = $model->page($page, $limit);
  3770. return $model->select();
  3771. }
  3772. /**
  3773. * 前台订单管理订单列表获取
  3774. * @param $where
  3775. * @return mixed
  3776. */
  3777. public static function orderList($where)
  3778. {
  3779. $model = self::getOrderWhere($where, self::alias('a')->join('user r', 'r.uid=a.uid', 'LEFT'), 'a.', 'r')->field('a.id,a.order_id,a.add_time,a.status,a.total_num,a.total_price,a.total_postage,a.pay_price,a.pay_postage,a.paid,a.refund_status,a.remark,a.pay_type');
  3780. if ($where['order'] != '') {
  3781. $model = $model->order(self::setOrder($where['order']));
  3782. } else {
  3783. $model = $model->order('a.id desc');
  3784. }
  3785. $data = ($data = $model->page((int)$where['page'], (int)$where['limit'])->select()) && count($data) ? $data->toArray() : [];
  3786. return self::tidyAdminOrder($data);
  3787. }
  3788. /**
  3789. * 前台订单管理 订单信息设置
  3790. * @param $data
  3791. * @param bool $status
  3792. * @return mixed
  3793. * @throws DataNotFoundException
  3794. * @throws ModelNotFoundException
  3795. * @throws \think\exception\DbException
  3796. */
  3797. public static function tidyAdminOrder($data, $status = false)
  3798. {
  3799. foreach ($data as &$item) {
  3800. $_info = StoreOrderCartInfo::where('oid', $item['id'])->field('cart_info')->select()->toArray();
  3801. foreach ($_info as $k => $v) {
  3802. if (!is_array($v['cart_info']))
  3803. $_info[$k]['cart_info'] = json_decode($v['cart_info'], true);
  3804. }
  3805. foreach ($_info as $k => $v) {
  3806. unset($_info[$k]['cart_info']['type'], $_info[$k]['cart_info']['product_id'], $_info[$k]['cart_info']['combination_id'], $_info[$k]['cart_info']['seckill_id'], $_info[$k]['cart_info']['bargain_id'], $_info[$k]['cart_info']['bargain_id'], $_info[$k]['cart_info']['truePrice'], $_info[$k]['cart_info']['vip_truePrice'], $_info[$k]['cart_info']['trueStock'], $_info[$k]['cart_info']['costPrice'], $_info[$k]['cart_info']['productInfo']['id'], $_info[$k]['cart_info']['productInfo']['vip_price'], $_info[$k]['cart_info']['productInfo']['postage'], $_info[$k]['cart_info']['productInfo']['give_integral'], $_info[$k]['cart_info']['productInfo']['sales'], $_info[$k]['cart_info']['productInfo']['stock'], $_info[$k]['cart_info']['productInfo']['unit_name'], $_info[$k]['cart_info']['productInfo']['is_postage'], $_info[$k]['cart_info']['productInfo']['slider_image'], $_info[$k]['cart_info']['productInfo']['cost'], $_info[$k]['cart_info']['productInfo']['mer_id'], $_info[$k]['cart_info']['productInfo']['cate_id'], $_info[$k]['cart_info']['productInfo']['is_show'], $_info[$k]['cart_info']['productInfo']['store_info'], $_info[$k]['cart_info']['productInfo']['is_del'], $_info[$k]['cart_info']['is_pay'], $_info[$k]['cart_info']['is_del'], $_info[$k]['cart_info']['is_new'], $_info[$k]['cart_info']['add_time'], $_info[$k]['cart_info']['id'], $_info[$k]['cart_info']['uid'], $_info[$k]['cart_info']['product_attr_unique']);
  3807. $_info[$k]['cart_info']['productInfo']['suk'] = '';
  3808. if (isset($v['cart_info']['productInfo']['attrInfo'])) {
  3809. $_info[$k]['cart_info']['productInfo']['image'] = $_info[$k]['cart_info']['productInfo']['attrInfo']['image'];
  3810. $_info[$k]['cart_info']['productInfo']['price'] = $_info[$k]['cart_info']['productInfo']['attrInfo']['price'];
  3811. $_info[$k]['cart_info']['productInfo']['suk'] = $_info[$k]['cart_info']['productInfo']['attrInfo']['suk'];
  3812. unset($_info[$k]['cart_info']['productInfo']['attrInfo']);
  3813. }
  3814. if (!isset($v['cart_info']['productInfo']['ot_price'])) {
  3815. $_info[$k]['cart_info']['productInfo']['ot_price'] = $v['cart_info']['productInfo']['price'];
  3816. }
  3817. }
  3818. $item['_info'] = $_info;
  3819. $item['add_time'] = date('Y-m-d H:i:s', $item['add_time']);
  3820. // if($item['pink_id'] || $item['combination_id']){
  3821. // $pinkStatus = StorePink::where('order_id_key',$item['id'])->value('status');
  3822. // switch ($pinkStatus){
  3823. // case 1:
  3824. // $item['pink_name'] = '[拼团订单]正在进行中';
  3825. // $item['color'] = '#f00';
  3826. // break;
  3827. // case 2:
  3828. // $item['pink_name'] = '[拼团订单]已完成';
  3829. // $item['color'] = '#00f';
  3830. // break;
  3831. // case 3:
  3832. // $item['pink_name'] = '[拼团订单]未完成';
  3833. // $item['color'] = '#f0f';
  3834. // break;
  3835. // default:
  3836. // $item['pink_name'] = '[拼团订单]历史订单';
  3837. // $item['color'] = '#457856';
  3838. // break;
  3839. // }
  3840. // }elseif ($item['seckill_id']){
  3841. // $item['pink_name'] = '[秒杀订单]';
  3842. // $item['color'] = '#32c5e9';
  3843. // }elseif ($item['bargain_id']){
  3844. // $item['pink_name'] = '[砍价订单]';
  3845. // $item['color'] = '#12c5e9';
  3846. // }else{
  3847. // $item['pink_name'] = '[普通订单]';
  3848. // $item['color'] = '#895612';
  3849. // }
  3850. // if($item['paid']==1){
  3851. // switch ($item['pay_type']){
  3852. // case 'weixin':
  3853. // $item['pay_type_name']='微信支付';
  3854. // break;
  3855. // case 'yue':
  3856. // $item['pay_type_name']='余额支付';
  3857. // break;
  3858. // case 'offline':
  3859. // $item['pay_type_name']='线下支付';
  3860. // break;
  3861. // default:
  3862. // $item['pay_type_name']='其他支付';
  3863. // break;
  3864. // }
  3865. // }else{
  3866. // switch ($item['pay_type']){
  3867. // default:
  3868. // $item['pay_type_name']='未支付';
  3869. // break;
  3870. // case 'offline':
  3871. // $item['pay_type_name']='线下支付';
  3872. // $item['pay_type_info']=1;
  3873. // break;
  3874. // }
  3875. // }
  3876. if ($status) {
  3877. $status = [];
  3878. if (!$item['paid'] && $item['pay_type'] == 'offline' && !$item['status'] >= 2) {
  3879. $status['_type'] = 9;
  3880. $status['_title'] = '线下付款';
  3881. $status['_msg'] = '商家处理中,请耐心等待';
  3882. $status['_class'] = 'nobuy';
  3883. } else if (!$item['paid']) {
  3884. $status['_type'] = 0;
  3885. $status['_title'] = '未支付';
  3886. //系统预设取消订单时间段
  3887. $keyValue = ['order_cancel_time', 'order_activity_time', 'order_bargain_time', 'order_seckill_time', 'order_pink_time'];
  3888. //获取配置
  3889. $systemValue = SystemConfigService::more($keyValue);
  3890. //格式化数据
  3891. $systemValue = self::setValeTime($keyValue, is_array($systemValue) ? $systemValue : []);
  3892. if ($item['pink_id'] || $item['combination_id']) {
  3893. $order_pink_time = $systemValue['order_pink_time'] ? $systemValue['order_pink_time'] : $systemValue['order_activity_time'];
  3894. $time = bcadd($item['add_time'], $order_pink_time * 3600, 0);
  3895. $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
  3896. } else if ($item['seckill_id']) {
  3897. $order_seckill_time = $systemValue['order_seckill_time'] ? $systemValue['order_seckill_time'] : $systemValue['order_activity_time'];
  3898. $time = bcadd($item['add_time'], $order_seckill_time * 3600, 0);
  3899. $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
  3900. } else if ($item['bargain_id']) {
  3901. $order_bargain_time = $systemValue['order_bargain_time'] ? $systemValue['order_bargain_time'] : $systemValue['order_activity_time'];
  3902. $time = bcadd($item['add_time'], $order_bargain_time * 3600, 0);
  3903. $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
  3904. } else {
  3905. $time = bcadd($item['add_time'], $systemValue['order_cancel_time'] * 3600, 0);
  3906. $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
  3907. }
  3908. $status['_class'] = 'nobuy';
  3909. } else if ($item['refund_status'] == 1) {
  3910. $status['_type'] = -1;
  3911. $status['_title'] = '申请退款中';
  3912. $status['_msg'] = '商家审核中,请耐心等待';
  3913. $status['_class'] = 'state-sqtk';
  3914. } else if ($item['refund_status'] == 2) {
  3915. $status['_type'] = -2;
  3916. $status['_title'] = '已退款';
  3917. $status['_msg'] = '已为您退款,感谢您的支持';
  3918. $status['_class'] = 'state-sqtk';
  3919. } else if (!$item['status']) {
  3920. if ($item['pink_id']) {
  3921. if (StorePink::where('id', $item['pink_id'])->where('status', 1)->count()) {
  3922. $status['_type'] = 11;
  3923. $status['_title'] = '拼团中';
  3924. $status['_msg'] = '等待其他人参加拼团';
  3925. $status['_class'] = 'state-nfh';
  3926. } else {
  3927. $status['_type'] = 1;
  3928. $status['_title'] = '未发货';
  3929. $status['_msg'] = '商家未发货,请耐心等待';
  3930. $status['_class'] = 'state-nfh';
  3931. }
  3932. } else {
  3933. $status['_type'] = 1;
  3934. $status['_title'] = '未发货';
  3935. $status['_msg'] = '商家未发货,请耐心等待';
  3936. $status['_class'] = 'state-nfh';
  3937. }
  3938. } else if ($item['status'] == 1) {
  3939. if ($item['delivery_type'] == 'send') {//TODO 送货
  3940. $status['_type'] = 2;
  3941. $status['_title'] = '待收货';
  3942. $status['_msg'] = date('m月d日H时i分', StoreOrderStatus::getTime($item['id'], 'delivery')) . '服务商已送货';
  3943. $status['_class'] = 'state-ysh';
  3944. } else {//TODO 发货
  3945. $status['_type'] = 2;
  3946. $status['_title'] = '待收货';
  3947. $status['_msg'] = date('m月d日H时i分', StoreOrderStatus::getTime($item['id'], 'delivery_goods')) . '服务商已发货';
  3948. $status['_class'] = 'state-ysh';
  3949. }
  3950. } else if ($item['status'] == 2) {
  3951. $status['_type'] = 3;
  3952. $status['_title'] = '待评价';
  3953. $status['_msg'] = '已收货,快去评价一下吧';
  3954. $status['_class'] = 'state-ypj';
  3955. } else if ($item['status'] == 3) {
  3956. $status['_type'] = 4;
  3957. $status['_title'] = '交易完成';
  3958. $status['_msg'] = '交易完成,感谢您的支持';
  3959. $status['_class'] = 'state-ytk';
  3960. }
  3961. if (isset($item['pay_type']))
  3962. $status['_payType'] = isset(self::$payType[$item['pay_type']]) ? self::$payType[$item['pay_type']] : '其他方式';
  3963. if (isset($item['delivery_type']))
  3964. $status['_deliveryType'] = isset(self::$deliveryType[$item['delivery_type']]) ? self::$deliveryType[$item['delivery_type']] : '其他方式';
  3965. $item['_status'] = $status;
  3966. } else {
  3967. if ($item['paid'] == 0 && $item['status'] == 0) {
  3968. $item['status_name'] = '未支付';
  3969. } else if ($item['paid'] == 1 && $item['status'] == 0 && $item['refund_status'] == 0) {
  3970. $item['status_name'] = '未发货';
  3971. } else if ($item['paid'] == 1 && $item['status'] == 1 && $item['refund_status'] == 0) {
  3972. $item['status_name'] = '待收货';
  3973. } else if ($item['paid'] == 1 && $item['status'] == 2 && $item['refund_status'] == 0) {
  3974. $item['status_name'] = '待评价';
  3975. } else if ($item['paid'] == 1 && $item['status'] == 3 && $item['refund_status'] == 0) {
  3976. $item['status_name'] = '已完成';
  3977. }
  3978. }
  3979. // unset($item['refund_status']);
  3980. // else if($item['paid']==1 && $item['refund_status']==1){
  3981. // $item['status_name']=<<<HTML
  3982. //<b style="color:#f124c7">申请退款</b><br/>
  3983. //<span>退款原因:{$item['refund_reason_wap']}</span>
  3984. //HTML;
  3985. // }else if($item['paid']==1 && $item['refund_status']==2){
  3986. // $item['status_name']='已退款';
  3987. // }
  3988. // if($item['paid']==0 && $item['status']==0 && $item['refund_status']==0){
  3989. // $item['_status']=1;
  3990. // }else if($item['paid']==1 && $item['status']==0 && $item['refund_status']==0){
  3991. // $item['_status']=2;
  3992. // }else if($item['paid']==1 && $item['refund_status']==1){
  3993. // $item['_status']=3;
  3994. // }else if($item['paid']==1 && $item['status']==1 && $item['refund_status']==0){
  3995. // $item['_status']=4;
  3996. // }else if($item['paid']==1 && $item['status']==2 && $item['refund_status']==0){
  3997. // $item['_status']=5;
  3998. // }else if($item['paid']==1 && $item['status']==3 && $item['refund_status']==0){
  3999. // $item['_status']=6;
  4000. // }else if($item['paid']==1 && $item['refund_status']==2){
  4001. // $item['_status']=7;
  4002. // }
  4003. }
  4004. return $data;
  4005. }
  4006. /**
  4007. * 处理where条件
  4008. * @param $where
  4009. * @param $model
  4010. * @param string $aler
  4011. * @param string $join
  4012. * @return StoreOrder|null
  4013. */
  4014. public static function getOrderWhere($where, $model, $aler = '', $join = '')
  4015. {
  4016. if (isset($where['status']) && $where['status'] != '') $model = self::statusWhere($where['status'], $model, $aler);
  4017. if (isset($where['is_del']) && $where['is_del'] != '' && $where['is_del'] != -1) $model = $model->where($aler . 'is_del', $where['is_del']);
  4018. if (isset($where['combination_id'])) {
  4019. if ($where['combination_id'] == '普通订单') {
  4020. $model = $model->where($aler . 'combination_id', 0)->where($aler . 'seckill_id', 0)->where($aler . 'bargain_id', 0);
  4021. }
  4022. if ($where['combination_id'] == '拼团订单') {
  4023. $model = $model->where($aler . 'combination_id', ">", 0)->where($aler . 'pink_id', ">", 0);
  4024. }
  4025. if ($where['combination_id'] == '秒杀订单') {
  4026. $model = $model->where($aler . 'seckill_id', ">", 0);
  4027. }
  4028. if ($where['combination_id'] == '砍价订单') {
  4029. $model = $model->where($aler . 'bargain_id', ">", 0);
  4030. }
  4031. }
  4032. if (isset($where['type'])) {
  4033. switch ($where['type']) {
  4034. case 1:
  4035. $model = $model->where($aler . 'combination_id', 0)->where($aler . 'seckill_id', 0)->where($aler . 'bargain_id', 0);
  4036. break;
  4037. case 2:
  4038. $model = $model->where($aler . 'combination_id', ">", 0);
  4039. break;
  4040. case 3:
  4041. $model = $model->where($aler . 'seckill_id', ">", 0);
  4042. break;
  4043. case 4:
  4044. $model = $model->where($aler . 'bargain_id', ">", 0);
  4045. break;
  4046. }
  4047. }
  4048. if (isset($where['real_name']) && $where['real_name'] != '')
  4049. $model = $model->where($aler . 'order_id|' . $aler . 'real_name|' . $aler . 'user_phone' . ($join ? '|' . $join . '.nickname|' . $join . '.uid' : ''), 'LIKE', "%$where[real_name]%");
  4050. if (isset($where['data']) && $where['data'] !== '')
  4051. $model = self::getModelTime($where, $model, $aler . 'add_time');
  4052. return $model;
  4053. }
  4054. /**
  4055. * 设置where条件
  4056. * @param $status
  4057. * @param null $model
  4058. * @param string $alert
  4059. * @return StoreOrder|null
  4060. */
  4061. public static function statusWhere($status, $model = null, $alert = '')
  4062. {
  4063. if ($model == null) $model = new self;
  4064. if ('' === $status)
  4065. return $model;
  4066. else if ($status == 0)//未支付
  4067. return $model->where($alert . 'paid', 0)->where($alert . 'status', 0)->where($alert . 'refund_status', 0);
  4068. else if ($status == 1)//已支付 未发货
  4069. return $model->where($alert . 'paid', 1)->where($alert . 'status', 0)->where($alert . 'refund_status', 0);
  4070. else if ($status == 2)//已支付 待收货
  4071. return $model->where($alert . 'paid', 1)->where($alert . 'status', 1)->where($alert . 'refund_status', 0);
  4072. else if ($status == 3)// 已支付 已收货 待评价
  4073. return $model->where($alert . 'paid', 1)->where($alert . 'status', 2)->where($alert . 'refund_status', 0);
  4074. else if ($status == 4)// 交易完成
  4075. return $model->where($alert . 'paid', 1)->where($alert . 'status', 3)->where($alert . 'refund_status', 0);
  4076. else if ($status == -1)//退款中
  4077. return $model->where($alert . 'paid', 1)->where($alert . 'refund_status', 1);
  4078. else if ($status == -2)//已退款
  4079. return $model->where($alert . 'paid', 1)->where($alert . 'refund_status', 2);
  4080. else if ($status == -3)//退款
  4081. return $model->where($alert . 'paid', 1)->where($alert . 'refund_status', 'in', '1,2');
  4082. else
  4083. return $model;
  4084. }
  4085. /**
  4086. * 订单详情 管理员
  4087. * @param $orderId
  4088. * @param string $field
  4089. * @return array|null|\think\Model
  4090. * @throws DataNotFoundException
  4091. * @throws ModelNotFoundException
  4092. * @throws \think\exception\DbException
  4093. */
  4094. public static function getAdminOrderDetail($orderId, $field = '*')
  4095. {
  4096. return self::where('order_id', $orderId)->field($field)->find();
  4097. }
  4098. /**
  4099. * 获取指定时间区间的支付金额 管理员
  4100. * @param $start
  4101. * @param $stop
  4102. * @return float
  4103. */
  4104. public static function getOrderTimeBusinessVolumePrice($start, $stop)
  4105. {
  4106. return self::where('is_del', 0)->where('paid', 1)->where('refund_status', 0)->where('add_time', '>=', $start)->where('add_time', '<', $stop)->sum('pay_price');
  4107. }
  4108. /**
  4109. * 获取指定时间区间的支付订单数量 管理员
  4110. * @param $start
  4111. * @param $stop
  4112. * @return float
  4113. */
  4114. public static function getOrderTimeBusinessVolumeNumber($start, $stop)
  4115. {
  4116. return self::where('is_del', 0)->where('paid', 1)->where('refund_status', 0)->where('add_time', '>=', $start)->where('add_time', '<', $stop)->count();
  4117. }
  4118. /**
  4119. * 获取当前时间到指定时间的支付金额 管理员
  4120. * @param $start 开始时间
  4121. * @param $stop 结束时间
  4122. * @return mixed
  4123. */
  4124. public static function chartTimePrice($start, $stop)
  4125. {
  4126. $model = new self;
  4127. $model = $model->field('sum(pay_price) as num,FROM_UNIXTIME(add_time, \'%Y-%m-%d\') as time');
  4128. $model = $model->where('is_del', 0);
  4129. $model = $model->where('paid', 1);
  4130. $model = $model->where('refund_status', 0);
  4131. $model = $model->where('add_time', '>=', $start);
  4132. $model = $model->where('add_time', '<', $stop);
  4133. $model = $model->group("FROM_UNIXTIME(add_time, '%Y-%m-%d')");
  4134. $model = $model->order('add_time ASC');
  4135. return $model->select();
  4136. }
  4137. /**
  4138. * 获取当前时间到指定时间的支付订单数 管理员
  4139. * @param $start 开始时间
  4140. * @param $stop 结束时间
  4141. * @return mixed
  4142. */
  4143. public static function chartTimeNumber($start, $stop)
  4144. {
  4145. $model = new self;
  4146. $model = $model->field('count(id) as num,FROM_UNIXTIME(add_time, \'%Y-%m-%d\') as time');
  4147. $model = $model->where('is_del', 0);
  4148. $model = $model->where('paid', 1);
  4149. $model = $model->where('refund_status', 0);
  4150. $model = $model->where('add_time', '>=', $start);
  4151. $model = $model->where('add_time', '<', $stop);
  4152. $model = $model->group("FROM_UNIXTIME(add_time, '%Y-%m-%d')");
  4153. $model = $model->order('add_time ASC');
  4154. return $model->select();
  4155. }
  4156. /**
  4157. * 修改支付方式为线下支付
  4158. * @param $orderId
  4159. * @return bool
  4160. */
  4161. public static function setOrderTypePayOffline($orderId)
  4162. {
  4163. return self::edit(['pay_type' => 'offline'], $orderId, 'order_id');
  4164. }
  4165. /**
  4166. * 线下付款
  4167. * @param $id
  4168. * @return $this
  4169. */
  4170. public static function updateOffline($id)
  4171. {
  4172. $count = self::where('id', $id)->count();
  4173. if (!$count) return self::setErrorInfo('订单不存在');
  4174. $count = self::where('id', $id)->where('paid', 0)->count();
  4175. if (!$count) return self::setErrorInfo('订单已支付');
  4176. $res = self::where('id', $id)->update(['paid' => 1, 'pay_time' => time()]);
  4177. return $res;
  4178. }
  4179. /**
  4180. * 向创建订单10分钟未付款的用户发送短信
  4181. */
  4182. public static function sendTen()
  4183. {
  4184. $list = self::where('paid', 0)->where('is_del', 0)->where('is_system_del', 0)->where('add_time', '>', time() - 900)->where('add_time', '<', time() - 600)->column('user_phone');
  4185. foreach ($list as $phone) {
  4186. ShortLetterRepositories::send(true, $phone, [], 'ORDER_PAY_FALSE');
  4187. }
  4188. }
  4189. public function productInfo()
  4190. {
  4191. return $this->hasMany(StoreProductReply::class, 'oid', 'id');
  4192. }
  4193. public static function setOrderProductReplyWhere($where)
  4194. {
  4195. $model = self::where('status', 3)->order('add_time desc')->whereIn('id', function ($query) {
  4196. $query->name('store_order')->alias('o')->join('store_product_reply a', 'a.oid = o.id')->group('o.id')->field('o.id')->select();
  4197. })->with('productInfo', function ($query) use ($where) {
  4198. $alias = '';
  4199. if (isset($where['title']) && $where['title'] != '')
  4200. $query->where("{$alias}comment", 'LIKE', "%$where[title]%");
  4201. if (isset($where['is_reply']) && $where['is_reply'] != '') {
  4202. if ($where['is_reply'] >= 0) {
  4203. $query->where("{$alias}is_reply", $where['is_reply']);
  4204. } else {
  4205. $query->where("{$alias}is_reply", '>', 0);
  4206. }
  4207. }
  4208. if (isset($where['producr_id']) && $where['producr_id'] != 0)
  4209. $query->where($alias . 'product_id', $where['producr_id']);
  4210. $query->where("{$alias}is_del", 0);
  4211. });
  4212. return $model;
  4213. }
  4214. public static function getOrderProductReplyList($where)
  4215. {
  4216. $list = self::setOrderProductReplyWhere($where)->page((int)$where['message_page'], (int)$where['limit'])->select();
  4217. $list = count($list) ? $list->toArray() : [];
  4218. foreach ($list as $key => $item) {
  4219. if (isset($item['productInfo']) && is_array($item['productInfo']) && count($item['productInfo'])) {
  4220. foreach ($item['productInfo'] as $k => $v) {
  4221. if (!$v['nickname'] && $v['uid']) {
  4222. $v['nickname'] = User::where('uid', $v['uid'])->value('nickname');
  4223. $v['avatar'] = User::where('uid', $v['uid'])->value('avatar');
  4224. }
  4225. $v['image'] = '';
  4226. $v['store_name'] = '';
  4227. if ($v['product_id']) {
  4228. $product = StoreProduct::where('id', $v['product_id'])->field(['image', 'store_name'])->find();
  4229. if ($product) {
  4230. $v['image'] = $product['image'];
  4231. $v['store_name'] = $product['store_name'];
  4232. }
  4233. }
  4234. $list[$key]['productInfo'][$k] = $v;
  4235. }
  4236. }
  4237. }
  4238. $count = self::setOrderProductReplyWhere($where)->count();
  4239. return compact('list', 'count');
  4240. }
  4241. >>>>>>> 386b37d33e5ba817cba00df29efaefbd692e4dd1
  4242. }