StoreOrder.php 148 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002
  1. <?php
  2. /**
  3. *
  4. * @author: xaboy<365615158@qq.com>
  5. * @day: 2017/12/20
  6. */
  7. namespace app\models\store;
  8. use app\admin\model\store\StoreProductAttrValue;
  9. use app\admin\model\system\ShippingTemplatesFree;
  10. use app\admin\model\system\ShippingTemplatesRegion;
  11. use app\models\system\SystemAwardLevel;
  12. use app\models\system\SystemGroupLevel;
  13. use app\models\system\SystemStoreMember;
  14. use app\models\system\SystemStoreStock;
  15. use app\models\system\SystemUserLevel;
  16. use crmeb\basic\BaseModel;
  17. use think\Exception;
  18. use think\facade\Cache;
  19. use crmeb\traits\ModelTrait;
  20. use think\facade\Log;
  21. use app\models\system\SystemStore;
  22. use app\models\routine\RoutineTemplate;
  23. use app\models\user\{User, UserAddress, UserBill, UserCode, UserLevel, WechatUser};
  24. use crmeb\services\{JiaLieService, SystemConfigService, UtilService, WechatTemplateService, workerman\ChannelService};
  25. use crmeb\repositories\{
  26. GoodsRepository, PaymentRepositories, OrderRepository, ShortLetterRepositories, UserRepository
  27. };
  28. use app\admin\model\system\ShippingTemplates;
  29. /**
  30. * TODO 订单Model
  31. * Class StoreOrder
  32. * @package app\models\store
  33. */
  34. class StoreOrder extends BaseModel
  35. {
  36. /**
  37. * 数据表主键
  38. * @var string
  39. */
  40. protected $pk = 'id';
  41. /**
  42. * 模型名称
  43. * @var string
  44. */
  45. protected $name = 'store_order';
  46. use ModelTrait;
  47. protected static $payType = ['weixin' => '微信支付', 'yue' => '余额支付', 'offline' => '线下支付', 'consumer' => '消费券支付', 'jialie' => '嘉联支付'];
  48. protected static $deliveryType = ['send' => '商家配送', 'express' => '快递配送'];
  49. protected function setCartIdAttr($value)
  50. {
  51. return is_array($value) ? json_encode($value) : $value;
  52. }
  53. protected function getCartIdAttr($value)
  54. {
  55. return json_decode($value, true);
  56. }
  57. /**获取订单组信息
  58. * @param $cartInfo
  59. * @return array
  60. */
  61. public static function getOrderPriceGroup($cartInfo, $addr)
  62. {
  63. $storeFreePostage = floatval(sys_config('store_free_postage')) ?: 0;//满额包邮
  64. $totalPrice = self::getOrderSumPrice($cartInfo, 'truePrice');//获取订单总金额
  65. $costPrice = self::getOrderSumPrice($cartInfo, 'costPrice');//获取订单成本价
  66. $vipPrice = self::getOrderSumPrice($cartInfo, 'vip_truePrice');//获取订单会员优惠金额
  67. $use_integral = self::getOrderSumPrice($cartInfo, 'use_integral');//获取订单会员优惠金额
  68. //如果满额包邮等于0
  69. if (!$storeFreePostage) {
  70. $storePostage = 0;
  71. } else {
  72. if ($addr) {
  73. //按照运费模板计算每个运费模板下商品的件数/重量/体积以及总金额 按照首重倒序排列
  74. $temp_num = [];
  75. foreach ($cartInfo as $cart) {
  76. $temp = ShippingTemplates::get($cart['productInfo']['temp_id']);
  77. if (!$temp) $temp = ShippingTemplates::get(1);
  78. if ($temp->getData('type') == 1) {
  79. $num = $cart['cart_num'];
  80. } elseif ($temp->getData('type') == 2) {
  81. $num = $cart['cart_num'] * $cart['productInfo']['attrInfo']['weight'];
  82. } else {
  83. $num = $cart['cart_num'] * $cart['productInfo']['attrInfo']['volume'];
  84. }
  85. $region = ShippingTemplatesRegion::where('temp_id', $cart['productInfo']['temp_id'])->where('city_id', $addr['city_id'])->find();
  86. if (!$region) $region = ShippingTemplatesRegion::where('temp_id', $cart['productInfo']['temp_id'])->where('city_id', 0)->find();
  87. if (!$region) $region = ShippingTemplatesRegion::where('temp_id', 1)->where('city_id', 0)->find();
  88. if (!$region) {
  89. return self::setErrorInfo('运费模板不存在');
  90. }
  91. if (!isset($temp_num[$cart['productInfo']['temp_id']])) {
  92. $temp_num[$cart['productInfo']['temp_id']]['number'] = $num;
  93. $temp_num[$cart['productInfo']['temp_id']]['price'] = bcmul($cart['cart_num'], $cart['truePrice'], 2);
  94. $temp_num[$cart['productInfo']['temp_id']]['first'] = $region['first'];
  95. $temp_num[$cart['productInfo']['temp_id']]['first_price'] = $region['first_price'];
  96. $temp_num[$cart['productInfo']['temp_id']]['continue'] = $region['continue'];
  97. $temp_num[$cart['productInfo']['temp_id']]['continue_price'] = $region['continue_price'];
  98. $temp_num[$cart['productInfo']['temp_id']]['temp_id'] = $cart['productInfo']['temp_id'];
  99. $temp_num[$cart['productInfo']['temp_id']]['city_id'] = $addr['city_id'];
  100. } else {
  101. $temp_num[$cart['productInfo']['temp_id']]['number'] += $num;
  102. $temp_num[$cart['productInfo']['temp_id']]['price'] += bcmul($cart['cart_num'], $cart['truePrice'], 2);
  103. }
  104. }
  105. array_multisort(array_column($temp_num, 'first_price'), SORT_DESC, $temp_num);
  106. $type = $storePostage = 0;
  107. foreach ($temp_num as $k => $v) {
  108. if (ShippingTemplatesFree::where('temp_id', $v['temp_id'])->where('city_id', $v['city_id'])->where('number', '<=', $v['number'])->where('price', '<=', $v['price'])->find()) {
  109. unset($temp_num[$k]);
  110. }
  111. }
  112. foreach ($temp_num as $v) {
  113. if ($type == 0) {
  114. if ($v['number'] <= (float)$v['first']) {
  115. $storePostage = bcadd($storePostage, $v['first_price'], 2);
  116. } else {
  117. if ($v['continue'] <= 0) {
  118. $storePostage = $storePostage;
  119. } else {
  120. $storePostage = bcadd(bcadd($storePostage, $v['first_price'], 2), bcmul(ceil(bcdiv(bcsub($v['number'], $v['first'], 2), $v['continue'] ?? 0, 2)), $v['continue_price']), 2);
  121. }
  122. }
  123. $type = 1;
  124. } else {
  125. if ($v['continue'] <= 0) {
  126. $storePostage = $storePostage;
  127. } else {
  128. $storePostage = bcadd($storePostage, bcmul(ceil(bcdiv($v['number'], $v['continue'] ?? 0, 2)), $v['continue_price']), 2);
  129. }
  130. }
  131. }
  132. } else {
  133. $storePostage = 0;
  134. }
  135. if ($storeFreePostage <= $totalPrice) $storePostage = 0;//如果总价大于等于满额包邮 邮费等于0
  136. }
  137. return compact('use_integral', 'storePostage', 'storeFreePostage', 'totalPrice', 'costPrice', 'vipPrice');
  138. }
  139. /**获取某个字段总金额
  140. * @param $cartInfo
  141. * @param $key 键名
  142. * @return int|string
  143. */
  144. public static function getOrderSumPrice($cartInfo, $key = 'truePrice')
  145. {
  146. $SumPrice = 0;
  147. foreach ($cartInfo as $cart) {
  148. $SumPrice = bcadd($SumPrice, bcmul($cart['cart_num'], $cart[$key], 2), 2);
  149. }
  150. return $SumPrice;
  151. }
  152. /**
  153. * 拼团
  154. * @param $cartInfo
  155. * @return array
  156. */
  157. public static function getCombinationOrderPriceGroup($cartInfo)
  158. {
  159. $storePostage = floatval(sys_config('store_postage')) ?: 0;
  160. $storeFreePostage = floatval(sys_config('store_free_postage')) ?: 0;
  161. $totalPrice = self::getCombinationOrderTotalPrice($cartInfo);
  162. $costPrice = self::getCombinationOrderTotalPrice($cartInfo);
  163. if (!$storeFreePostage) {
  164. $storePostage = 0;
  165. } else {
  166. foreach ($cartInfo as $cart) {
  167. if (!StoreCombination::where('id', $cart['combination_id'])->value('is_postage'))
  168. $storePostage = bcadd($storePostage, StoreCombination::where('id', $cart['combination_id'])->value('postage'), 2);
  169. }
  170. if ($storeFreePostage <= $totalPrice) $storePostage = 0;
  171. }
  172. return compact('storePostage', 'storeFreePostage', 'totalPrice', 'costPrice');
  173. }
  174. /**
  175. * 拼团价格
  176. * @param $cartInfo
  177. * @return float
  178. */
  179. public static function getCombinationOrderTotalPrice($cartInfo)
  180. {
  181. $totalPrice = 0;
  182. foreach ($cartInfo as $cart) {
  183. if ($cart['combination_id']) {
  184. $totalPrice = bcadd($totalPrice, bcmul($cart['cart_num'], StoreCombination::where('id', $cart['combination_id'])->value('price'), 2), 2);
  185. }
  186. }
  187. return (float)$totalPrice;
  188. }
  189. /**
  190. * 缓存订单信息
  191. * @param $uid
  192. * @param $cartInfo
  193. * @param $priceGroup
  194. * @param array $other
  195. * @param int $cacheTime
  196. * @return string
  197. * @throws \Psr\SimpleCache\InvalidArgumentException
  198. */
  199. public static function cacheOrderInfo($uid, $cartInfo, $priceGroup, $other = [], $cacheTime = 600)
  200. {
  201. $key = md5(time());
  202. Cache::set('user_order_' . $uid . $key, compact('cartInfo', 'priceGroup', 'other'), $cacheTime);
  203. return $key;
  204. }
  205. /**
  206. * 获取订单缓存信息
  207. * @param $uid
  208. * @param $key
  209. * @return mixed|null
  210. * @throws \Psr\SimpleCache\InvalidArgumentException
  211. */
  212. public static function getCacheOrderInfo($uid, $key)
  213. {
  214. $cacheName = 'user_order_' . $uid . $key;
  215. if (!Cache::has($cacheName)) return null;
  216. return Cache::get($cacheName);
  217. }
  218. /**
  219. * 删除订单缓存
  220. * @param $uid
  221. * @param $key
  222. */
  223. public static function clearCacheOrderInfo($uid, $key)
  224. {
  225. Cache::delete('user_order_' . $uid . $key);
  226. }
  227. /**
  228. * 生成订单
  229. * @param $uid
  230. * @param $key
  231. * @param $addressId
  232. * @param $payType
  233. * @param bool $useIntegral
  234. * @param int $couponId
  235. * @param string $mark
  236. * @param int $combinationId
  237. * @param int $pinkId
  238. * @param int $seckill_id
  239. * @param int $bargain_id
  240. * @param bool $test
  241. * @param int $isChannel
  242. * @param int $shipping_type
  243. * @param string $real_name
  244. * @param string $phone
  245. * @return StoreOrder|bool|\think\Model
  246. * @throws \think\Exception
  247. * @throws \think\db\exception\DataNotFoundException
  248. * @throws \think\db\exception\ModelNotFoundException
  249. * @throws \think\exception\DbException
  250. */
  251. 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, $is_consumer = 0, $offline_type = 0)
  252. {
  253. self::beginTrans();
  254. try {
  255. $shipping_type = (int)$shipping_type;
  256. $offlinePayStatus = (int)sys_config('offline_pay_status') ?? (int)2;
  257. if ($offlinePayStatus == 2) unset(self::$payType['offline']);
  258. if (!array_key_exists($payType, self::$payType)) return self::setErrorInfo('选择支付方式有误!', true);
  259. if (self::be(['unique' => $key, 'uid' => $uid])) return self::setErrorInfo('请勿重复提交订单', true);
  260. $userInfo = User::getUserInfo($uid);
  261. if (!$userInfo) return self::setErrorInfo('用户不存在!', true);
  262. $cartGroup = self::getCacheOrderInfo($uid, $key);
  263. if (!$cartGroup) return self::setErrorInfo('订单已过期,请刷新当前页面!', true);
  264. $cartInfo = $cartGroup['cartInfo'];
  265. $priceGroup = $cartGroup['priceGroup'];
  266. $other = $cartGroup['other'];
  267. $payPrice = (float)$priceGroup['totalPrice'];
  268. $useIntegrals = (float)$priceGroup['use_integral'];
  269. $addr = UserAddress::where('uid', $uid)->where('id', $addressId)->find();
  270. if ($payType == 'offline' && sys_config('offline_postage') == 1) {
  271. $payPostage = 0;
  272. } else {
  273. $payPostage = self::getOrderPriceGroup($cartInfo, $addr)['storePostage'];
  274. }
  275. if ($shipping_type === 1) {
  276. if (!$test && !$addressId) return self::setErrorInfo('请选择收货地址!', true);
  277. if (!$test && (!UserAddress::be(['uid' => $uid, 'id' => $addressId, 'is_del' => 0]) || !($addressInfo = UserAddress::find($addressId))))
  278. return self::setErrorInfo('地址选择有误!', true);
  279. $addressInfo = UserAddress::find($addressId);
  280. if (!$test && !($other['suit'] ?? 0)) {
  281. if (empty($addressInfo['longitude']) || empty($addressInfo['latitude'])) {
  282. return self::setErrorInfo('收货地址经纬度不能为空!', true);
  283. }
  284. $rs = SystemStore::lst('', $addressInfo['latitude'], $addressInfo['longitude'], 1, 1);
  285. if (!$rs) {
  286. return self::setErrorInfo('系统没设置门店!', true);
  287. }
  288. if ($rs[0]['distance'] > sys_config('store_distance')) {
  289. return self::setErrorInfo('该区域没有门店,请到店自提!', true);
  290. }
  291. $storeId = $rs[0]['id'];
  292. }
  293. } else {
  294. if ((!$real_name || !$phone) && !$test) return self::setErrorInfo('请填写姓名和电话', true);
  295. $addressInfo['real_name'] = $real_name;
  296. $addressInfo['phone'] = $phone;
  297. $addressInfo['province'] = '';
  298. $addressInfo['city'] = '';
  299. $addressInfo['district'] = '';
  300. $addressInfo['detail'] = '';
  301. }
  302. $cartIds = [];
  303. $totalNum = 0;
  304. $gainIntegral = 0;
  305. $maxUseIntegral = 0;
  306. foreach ($cartInfo as $cart) {
  307. if (!$test && !self::checkProductStock($uid, $cart['product_id'], $cart['cart_num'], $cart['product_attr_unique'], $cart['combination_id'], $cart['seckill_id'], $cart['bargain_id'])) {
  308. return false;
  309. }
  310. $cartIds[] = $cart['id'];
  311. $totalNum += $cart['cart_num'];
  312. if (!$seckill_id) $seckill_id = $cart['seckill_id'];
  313. if (!$bargain_id) $bargain_id = $cart['bargain_id'];
  314. if (!$combinationId) $combinationId = $cart['combination_id'];
  315. $cartInfoGainIntegral = isset($cart['productInfo']['give_integral']) ? bcmul($cart['cart_num'], $cart['productInfo']['give_integral'], 2) : 0;
  316. $cartInfoMaxUseIntegral = isset($cart['productInfo']['max_use_integral']) ? bcmul($cart['cart_num'], $cart['productInfo']['max_use_integral'], 2) : 0;
  317. $gainIntegral = bcadd($gainIntegral, $cartInfoGainIntegral, 2);
  318. $maxUseIntegral = bcadd($maxUseIntegral, $cartInfoMaxUseIntegral, 2);
  319. }
  320. $deduction = $seckill_id || $bargain_id || $combinationId;
  321. if ($deduction) {
  322. $couponId = 0;
  323. $useIntegral = false;
  324. if (!$test) {
  325. unset(self::$payType['offline']);
  326. if (!array_key_exists($payType, self::$payType)) return self::setErrorInfo('营销产品不能使用线下支付!', true);
  327. }
  328. }
  329. //使用优惠劵
  330. $res1 = true;
  331. if ($couponId) {
  332. $couponInfo = StoreCouponUser::validAddressWhere()->where('id', $couponId)->where('uid', $uid)->find();
  333. if (!$couponInfo) return self::setErrorInfo('选择的优惠劵无效!', true);
  334. $coupons = StoreCouponUser::getUsableCouponList($uid, ['valid' => $cartInfo], $payPrice);
  335. $flag = false;
  336. foreach ($coupons as $coupon) {
  337. if ($coupon['id'] == $couponId) {
  338. $flag = true;
  339. continue;
  340. }
  341. }
  342. if (!$flag)
  343. return self::setErrorInfo('不满足优惠劵的使用条件!', true);
  344. $payPrice = (float)bcsub($payPrice, $couponInfo['coupon_price'], 2);
  345. $res1 = StoreCouponUser::useCoupon($couponId);
  346. $couponPrice = $couponInfo['coupon_price'];
  347. } else {
  348. $couponId = 0;
  349. $couponPrice = 0;
  350. }
  351. if (!$res1) return self::setErrorInfo('使用优惠劵失败!', true);
  352. //$shipping_type = 1 快递发货 $shipping_type = 2 门店自提
  353. $store_self_mention = sys_config('store_self_mention') ?? 0;
  354. if (!$store_self_mention) $shipping_type = 1;
  355. if ($shipping_type === 1) {
  356. //是否包邮
  357. if ((isset($other['offlinePostage']) && $other['offlinePostage'] && $payType == 'offline')) $payPostage = 0;
  358. $payPrice = (float)bcadd($payPrice, $payPostage, 2);
  359. } else if ($shipping_type === 2) {
  360. //门店自提没有邮费支付
  361. $priceGroup['storePostage'] = 0;
  362. $payPostage = 0;
  363. if (!$storeId && !$test) {
  364. return self::setErrorInfo('请选择门店', true);
  365. }
  366. }
  367. // //积分抵扣
  368. // $res2 = true;
  369. // $SurplusIntegral = 0;
  370. // if ($useIntegral && $userInfo['integral'] > 0) {
  371. // if ($userInfo['integral'] > $maxUseIntegral) {
  372. // $useIntegral = $maxUseIntegral;
  373. // } else {
  374. // $useIntegral = $userInfo['integral'];
  375. // }
  376. // if ($useIntegral > 0) {
  377. // $deductionPrice = (float)bcmul($useIntegral, $other['integralRatio'], 2);
  378. // if ($deductionPrice < $payPrice) {
  379. // $payPrice = bcsub($payPrice, $deductionPrice, 2);
  380. // $usedIntegral = $useIntegral;
  381. // $SurplusIntegral = 0;
  382. // $res2 = false !== User::edit(['integral' => bcsub($userInfo['integral'], $usedIntegral, 2)], $userInfo['uid'], 'uid');
  383. // } else {
  384. // $deductionPrice = $payPrice;
  385. // $usedIntegral = (float)bcdiv($payPrice, $other['integralRatio'], 2);
  386. // $SurplusIntegral = bcsub($userInfo['integral'], $usedIntegral, 2);
  387. // $res2 = false !== User::bcDec($userInfo['uid'], 'integral', $usedIntegral, 'uid');
  388. // $payPrice = 0;
  389. // }
  390. // $res2 = $res2 && false != UserBill::expend('积分抵扣', $uid, 'integral', 'deduction', $usedIntegral, $key, $userInfo['integral'], '购买商品使用' . floatval($usedIntegral) . '积分抵扣' . floatval($deductionPrice) . '元');
  391. // } else {
  392. // $deductionPrice = 0;
  393. // $usedIntegral = 0;
  394. // }
  395. // } else {
  396. // $deductionPrice = 0;
  397. // $usedIntegral = 0;
  398. // }
  399. // if (!$res2) return self::setErrorInfo('使用积分抵扣失败!', true);
  400. //积分抵扣
  401. $deductionPrice = 0;
  402. $SurplusIntegral = 0;
  403. if ($useIntegrals > 0) {
  404. if ($userInfo['integral'] >= $useIntegrals) {
  405. $SurplusIntegral = bcsub($userInfo['integral'], $useIntegrals, 2);
  406. $res2 = false !== User::bcDec($userInfo['uid'], 'integral', $useIntegrals, 'uid');
  407. $res2 = $res2 && false != UserBill::expend('积分商品', $uid, 'integral', 'deduction', $useIntegrals, $key, $userInfo['integral'], '购买积分商品使用' . floatval($useIntegrals));
  408. } else {
  409. return self::setErrorInfo('积分不足' . $useIntegrals . '!', true);
  410. }
  411. if (!$res2) return self::setErrorInfo('使用积分抵扣失败!', true);
  412. }
  413. if ($payPrice <= 0) $payPrice = 0;
  414. if ($test) {
  415. self::rollbackTrans();
  416. return [
  417. 'total_price' => $priceGroup['totalPrice'],
  418. 'pay_price' => $payPrice,
  419. 'pay_postage' => $payPostage,
  420. 'coupon_price' => $couponPrice,
  421. 'deduction_price' => $deductionPrice,
  422. 'SurplusIntegral' => $SurplusIntegral,
  423. 'useIntegral' => $useIntegrals,
  424. ];
  425. }
  426. $id = self::getkeytoid('order_id');
  427. $orderInfo = [
  428. 'id' => $id,
  429. 'uid' => $uid,
  430. 'order_id' => $test ? 0 : self::getNewOrderId(),
  431. 'real_name' => $addressInfo['real_name'],
  432. 'user_phone' => $addressInfo['phone'],
  433. 'user_address' => $addressInfo['province'] . ' ' . $addressInfo['city'] . ' ' . $addressInfo['district'] . ' ' . $addressInfo['detail'],
  434. 'cart_id' => $cartIds,
  435. 'total_num' => $totalNum,
  436. 'total_price' => $priceGroup['totalPrice'],
  437. 'total_postage' => $priceGroup['storePostage'],
  438. 'coupon_id' => $couponId,
  439. 'coupon_price' => $couponPrice,
  440. 'pay_price' => $payPrice,
  441. 'pay_postage' => $payPostage,
  442. 'deduction_price' => $deductionPrice,
  443. 'paid' => 0,
  444. 'pay_type' => $payType,
  445. 'use_integral' => $useIntegrals,
  446. 'gain_integral' => $gainIntegral,
  447. 'mark' => htmlspecialchars($mark),
  448. 'combination_id' => $combinationId,
  449. 'pink_id' => $pinkId,
  450. 'seckill_id' => $seckill_id,
  451. 'bargain_id' => $bargain_id,
  452. 'cost' => $priceGroup['costPrice'],
  453. 'is_channel' => $isChannel,
  454. 'add_time' => date("Y-m-d H:i:s"),
  455. 'unique' => $key,
  456. 'shipping_type' => $shipping_type,
  457. 'is_consumer' => $is_consumer,
  458. 'reg_store_id' => $userInfo['reg_store_id'],
  459. 'suit' => $other['suit'] ?? 0,
  460. 'is_bind' => $other['is_bind'] ?? 0,
  461. 'store_bag' => $other['store_bag'] ?? 0,
  462. 'store_spread' => $other['store_spread'] ?? 0,
  463. 'offline_type' => $offline_type
  464. ];
  465. if ($shipping_type === 2) {
  466. $orderInfo['verify_code'] = self::getStoreCode();
  467. $orderInfo['store_id'] = SystemStore::getStoreDispose($storeId, 'id');
  468. if (!$orderInfo['store_id']) return self::setErrorInfo('暂无门店无法选择门店自提!', true);
  469. } else {
  470. $orderInfo['store_id'] = $storeId;
  471. }
  472. $create_store_id = intval(SystemStoreMember::where('uid', $uid)->value('reg_store_id'));
  473. if ($create_store_id == 0 && $orderInfo['store_id'] > 0) {
  474. $orderInfo['create_store_id'] = $orderInfo['store_id'];
  475. }
  476. $order = self::create($orderInfo);
  477. if (!$order) return self::setErrorInfo('订单生成失败-0!' . self::getlastsql(), true);
  478. $res5 = true;
  479. foreach ($cartInfo as $cart) {
  480. //减库存加销量
  481. if ($combinationId) $res5 = $res5 && StoreCombination::decCombinationStock($cart['cart_num'], $combinationId, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  482. else if ($seckill_id) $res5 = $res5 && StoreSeckill::decSeckillStock($cart['cart_num'], $seckill_id, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  483. else if ($bargain_id) $res5 = $res5 && StoreBargain::decBargainStock($cart['cart_num'], $bargain_id, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  484. else $res5 = $res5 && StoreProduct::decProductStock($cart['cart_num'], $cart['productInfo']['id'], isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  485. }
  486. //保存购物车商品信息
  487. $res4 = false !== StoreOrderCartInfo::setCartInfo($order['id'], $cartInfo);
  488. //购物车状态修改
  489. $res6 = false !== StoreCart::where('id', 'IN', $cartIds)->update(['is_pay' => 1]);
  490. if (!$res4 || !$res5 || !$res6) return self::setErrorInfo('订单生成失败-1!' . $res5 . '-' . $res4 . '-' . $res6, true);
  491. //自动设置默认地址
  492. UserRepository::storeProductOrderCreateEbApi($order, compact('cartInfo', 'addressId'));
  493. self::clearCacheOrderInfo($uid, $key);
  494. self::commitTrans();
  495. StoreOrderStatus::status($order['id'], 'cache_key_create_order', '订单生成');
  496. return $order;
  497. } catch (\PDOException $e) {
  498. self::rollbackTrans();
  499. return self::setErrorInfo('生成订单时SQL执行错误错误原因:' . $e->getMessage() . '--' . $e->getFile() . '--' . $e->getLine());
  500. } catch (\Exception $e) {
  501. self::rollbackTrans();
  502. return self::setErrorInfo('生成订单时系统错误错误原因:' . $e->getMessage() . '--' . $e->getFile() . '--' . $e->getLine());
  503. }
  504. }
  505. /**
  506. * 回退积分
  507. * @param $order 订单信息
  508. * @return bool
  509. */
  510. public static function RegressionIntegral($order)
  511. {
  512. if ($order['paid'] || $order['status'] == -2 || $order['is_del']) return true;
  513. if ($order['use_integral'] <= 0) return true;
  514. if ((int)$order['status'] != -2 && (int)$order['refund_status'] != 2 && $order['back_integral'] >= $order['use_integral']) return true;
  515. $res = User::bcInc($order['uid'], 'integral', $order['use_integral']);
  516. if (!$res) return self::setErrorInfo('回退积分增加失败');
  517. UserBill::income('积分回退', $order['uid'], 'integral', 'deduction', $order['use_integral'], $order['unique'], User::where('uid', $order['uid'])->value('integral'), '购买商品失败,回退积分' . floatval($order['use_integral']));
  518. return false !== self::where('order_id', $order['order_id'])->update(['back_integral' => $order['use_integral']]);
  519. }
  520. /**
  521. * 回退库存和销量
  522. * @param $order 订单信息
  523. * @return bool
  524. * @throws \think\db\exception\DataNotFoundException
  525. * @throws \think\db\exception\ModelNotFoundException
  526. * @throws \think\exception\DbException
  527. */
  528. public static function RegressionStock($order)
  529. {
  530. if ($order['status'] == -2 || $order['is_del']) return true;
  531. $combinationId = $order['combination_id'];
  532. $seckill_id = $order['seckill_id'];
  533. $bargain_id = $order['bargain_id'];
  534. $res5 = true;
  535. $cartInfo = StoreOrderCartInfo::where('cart_id', 'in', $order['cart_id'])->select()->toArray();
  536. foreach ($cartInfo as $cart) {
  537. //增库存减销量
  538. if ($combinationId) $res5 = $res5 && StoreCombination::incCombinationStock($cart['cart_info']['cart_num'], $combinationId, isset($cart['cart_info']['productInfo']['attrInfo']) ? $cart['cart_info']['productInfo']['attrInfo']['unique'] : '');
  539. else if ($seckill_id) $res5 = $res5 && StoreSeckill::incSeckillStock($cart['cart_info']['cart_num'], $seckill_id, isset($cart['cart_info']['productInfo']['attrInfo']) ? $cart['cart_info']['productInfo']['attrInfo']['unique'] : '');
  540. else if ($bargain_id) $res5 = $res5 && StoreBargain::incBargainStock($cart['cart_info']['cart_num'], $bargain_id, isset($cart['cart_info']['productInfo']['attrInfo']) ? $cart['cart_info']['productInfo']['attrInfo']['unique'] : '');
  541. else {
  542. $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'] : '');
  543. SystemStoreStock::Refund($order, $cart['cart_info']);
  544. }
  545. }
  546. return $res5;
  547. }
  548. /**
  549. * 回退优惠卷
  550. * @param $order 订单信息
  551. * @return bool
  552. */
  553. public static function RegressionCoupon($order)
  554. {
  555. if ($order['paid'] || $order['status'] == -2 || $order['is_del']) return true;
  556. $res = true;
  557. if ($order['coupon_id'] && StoreCouponUser::be(['id' => $order['coupon_id'], 'uid' => $order['uid'], 'status' => 1])) {
  558. $res = $res && false !== StoreCouponUser::where('id', $order['coupon_id'])->where('uid', $order['uid'])->update(['status' => 0, 'use_time' => 0]);
  559. }
  560. return $res;
  561. }
  562. /**
  563. * 取消订单
  564. * @param string order_id 订单id
  565. * @param $uid
  566. * @return bool
  567. * @throws \think\db\exception\DataNotFoundException
  568. * @throws \think\db\exception\ModelNotFoundException
  569. * @throws \think\exception\DbException
  570. */
  571. public static function cancelOrder($order_id, $uid)
  572. {
  573. $order = self::where('order_id', $order_id)->where('uid', $uid)->find();
  574. if (!$order) return self::setErrorInfo('没有查到此订单');
  575. self::beginTrans();
  576. try {
  577. $res = self::RegressionIntegral($order) && self::RegressionStock($order) && self::RegressionCoupon($order);
  578. $order->is_del = 1;
  579. if ($res && $order->save()) {
  580. self::commitTrans();
  581. return true;
  582. } else
  583. return false;
  584. } catch (\Exception $e) {
  585. self::rollbackTrans();
  586. return self::setErrorInfo(['line' => $e->getLine(), 'message' => $e->getMessage()]);
  587. }
  588. }
  589. /**
  590. * 生成订单唯一id
  591. * @param $uid 用户uid
  592. * @return string
  593. */
  594. public static function getNewOrderId()
  595. {
  596. list($msec, $sec) = explode(' ', microtime());
  597. $msectime = number_format((floatval($msec) + floatval($sec)) * 1000, 0, '', '');
  598. $orderId = 'wx' . $msectime . mt_rand(10000, 99999);
  599. if (self::be(['order_id' => $orderId])) $orderId = 'wx' . $msectime . mt_rand(10000, 99999);
  600. return $orderId;
  601. }
  602. /**
  603. * 修改订单号
  604. * @param $orderId
  605. * @return string
  606. */
  607. public static function changeOrderId($orderId)
  608. {
  609. $ymd = substr($orderId, 2, 8);
  610. $key = substr($orderId, 16);
  611. return 'wx' . $ymd . date('His') . $key;
  612. }
  613. /**
  614. * 查找购物车里的所有产品标题
  615. * @param $cartId 购物车id
  616. * @return bool|string
  617. */
  618. public static function getProductTitle($cartId)
  619. {
  620. $title = '';
  621. try {
  622. $orderCart = StoreOrderCartInfo::where('cart_id', 'in', $cartId)->field('cart_info')->select();
  623. foreach ($orderCart as $item) {
  624. if (isset($item['cart_info']['productInfo']['store_name'])) {
  625. $title .= $item['cart_info']['productInfo']['store_name'] . '|';
  626. }
  627. }
  628. unset($item);
  629. if (!$title) {
  630. $productIds = StoreCart::where('id', 'in', $cartId)->column('product_id');
  631. $productlist = ($productlist = StoreProduct::getProductField($productIds, 'store_name')) ? $productlist->toArray() : [];
  632. foreach ($productlist as $item) {
  633. if (isset($item['store_name'])) $title .= $item['store_name'] . '|';
  634. }
  635. }
  636. if ($title) $title = substr($title, 0, strlen($title) - 1);
  637. unset($item);
  638. } catch (\Exception $e) {
  639. }
  640. return $title;
  641. }
  642. /**
  643. * 获取门店自提唯一核销码
  644. * @return bool|string
  645. */
  646. public static function getStoreCode()
  647. {
  648. list($msec, $sec) = explode(' ', microtime());
  649. $num = bcadd(time(), mt_rand(10, 999999), 0) . '' . substr($msec, 2, 3);//生成随机数
  650. if (strlen($num) < 12)
  651. $num = str_pad((string)$num, 12, 0, STR_PAD_RIGHT);
  652. else
  653. $num = substr($num, 0, 12);
  654. if (self::be(['verify_code' => $num])) return self::getStoreCode();
  655. return $num;
  656. }
  657. /**
  658. * 余额支付
  659. * @param $order_id
  660. * @param $uid
  661. * @param string $formId
  662. * @return bool
  663. * @throws \think\Exception
  664. * @throws \think\db\exception\DataNotFoundException
  665. * @throws \think\db\exception\ModelNotFoundException
  666. * @throws \think\exception\DbException
  667. */
  668. public static function yuePay($order_id, $uid, $formId = '')
  669. {
  670. $orderInfo = self::where('uid', $uid)->where('order_id', $order_id)->where('is_del', 0)->find();
  671. if (!$orderInfo) return self::setErrorInfo('订单不存在!');
  672. if ($orderInfo['paid']) return self::setErrorInfo('该订单已支付!');
  673. // if($orderInfo['pay_type'] != 'yue') return self::setErrorInfo('该订单不能使用余额支付!');
  674. $userInfo = User::getUserInfo($uid);
  675. if ($userInfo['now_money'] < $orderInfo['pay_price'])
  676. return self::setErrorInfo(['status' => 'pay_deficiency', 'msg' => '余额不足' . floatval($orderInfo['pay_price'])]);
  677. self::beginTrans();
  678. $res1 = false !== User::bcDec($uid, 'now_money', $orderInfo['pay_price'], 'uid');
  679. $res2 = UserBill::expend('购买商品', $uid, 'now_money', 'pay_product', $orderInfo['pay_price'], $orderInfo['id'], $userInfo['now_money'], '余额支付' . floatval($orderInfo['pay_price']) . '元购买商品');
  680. // @file_put_contents('order.txt', '【4】' . time() . PHP_EOL, FILE_APPEND);
  681. $res3 = self::paySuccess($order_id, 'yue', $formId);//余额支付成功
  682. try {
  683. PaymentRepositories::yuePayProduct($userInfo, $orderInfo);
  684. } catch (\Exception $e) {
  685. self::rollbackTrans();
  686. return self::setErrorInfo($e->getMessage());
  687. }
  688. $res = $res1 && $res2 && $res3;
  689. self::checkTrans($res);
  690. return $res;
  691. }
  692. /**
  693. * 消费券支付
  694. * @param $order_id
  695. * @param $uid
  696. * @param string $formId
  697. * @return bool
  698. * @throws \think\Exception
  699. * @throws \think\db\exception\DataNotFoundException
  700. * @throws \think\db\exception\ModelNotFoundException
  701. * @throws \think\exception\DbException
  702. */
  703. public static function consumerPay($order_id, $uid, $formId = '')
  704. {
  705. $orderInfo = self::where('uid', $uid)->where('order_id', $order_id)->where('is_del', 0)->find();
  706. if (!$orderInfo) return self::setErrorInfo('订单不存在!');
  707. if ($orderInfo['paid']) return self::setErrorInfo('该订单已支付!');
  708. // if($orderInfo['pay_type'] != 'yue') return self::setErrorInfo('该订单不能使用余额支付!');
  709. $userInfo = User::getUserInfo($uid);
  710. if ($userInfo['consumer'] < $orderInfo['pay_price'])
  711. return self::setErrorInfo(['status' => 'pay_deficiency', 'msg' => '消费券不足' . floatval($orderInfo['pay_price'])]);
  712. self::beginTrans();
  713. $res1 = false !== User::bcDec($uid, 'consumer', $orderInfo['pay_price'], 'uid');
  714. $res2 = UserBill::expend('消费券商品', $uid, 'consumer', 'consumer_product', $orderInfo['pay_price'], $orderInfo['id'], $userInfo['consumer'], '消费券支付' . floatval($orderInfo['pay_price']) . '购买商品');
  715. $res3 = self::paySuccess($order_id, 'consumer', $formId);//银币支付成功
  716. try {
  717. PaymentRepositories::yuePayProduct($userInfo, $orderInfo);
  718. } catch (\Exception $e) {
  719. self::rollbackTrans();
  720. return self::setErrorInfo($e->getMessage());
  721. }
  722. $res = $res1 && $res2 && $res3;
  723. self::checkTrans($res);
  724. return $res;
  725. }
  726. /**
  727. * 微信支付 为 0元时
  728. * @param $order_id
  729. * @param $uid
  730. * @param string $formId
  731. * @return bool
  732. * @throws \think\Exception
  733. * @throws \think\db\exception\DataNotFoundException
  734. * @throws \think\db\exception\ModelNotFoundException
  735. * @throws \think\exception\DbException
  736. */
  737. public static function jsPayPrice($order_id, $uid, $formId = '')
  738. {
  739. $orderInfo = self::where('uid', $uid)->where('order_id', $order_id)->where('is_del', 0)->find();
  740. if (!$orderInfo) return self::setErrorInfo('订单不存在!');
  741. if ($orderInfo['paid']) return self::setErrorInfo('该订单已支付!');
  742. $userInfo = User::getUserInfo($uid);
  743. self::beginTrans();
  744. $res1 = UserBill::expend('购买商品', $uid, 'now_money', 'pay_product', $orderInfo['pay_price'], $orderInfo['id'], $userInfo['now_money'], '微信支付' . floatval($orderInfo['pay_price']) . '元购买商品');
  745. $res2 = self::paySuccess($order_id, 'weixin', $formId);//微信支付为0时
  746. $res = $res1 && $res2;
  747. self::checkTrans($res);
  748. return $res;
  749. }
  750. /**
  751. * 用户申请退款
  752. * @param $uni
  753. * @param $uid
  754. * @param string $refundReasonWap
  755. * @return bool
  756. */
  757. public static function orderApplyRefund($uni, $uid, $refundReasonWap = '', $refundReasonWapExplain = '', $refundReasonWapImg = [])
  758. {
  759. $order = self::getUserOrderDetail($uid, $uni);
  760. if (!$order) return self::setErrorInfo('支付订单不存在!');
  761. if ($order['refund_status'] == 2) return self::setErrorInfo('订单已退款!');
  762. if ($order['refund_status'] == 1) return self::setErrorInfo('正在申请退款中!');
  763. if ($order['status'] == 1) return self::setErrorInfo('订单当前无法退款!');
  764. self::beginTrans();
  765. $res1 = false !== StoreOrderStatus::status($order['id'], 'apply_refund', '用户申请退款,原因:' . $refundReasonWap);
  766. $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');
  767. $res = $res1 && $res2;
  768. self::checkTrans($res);
  769. if (!$res)
  770. return self::setErrorInfo('申请退款失败!');
  771. else {
  772. try {
  773. if (in_array($order['is_channel'], [0, 2])) {
  774. //公众号发送模板消息通知客服
  775. WechatTemplateService::sendAdminNoticeTemplate([
  776. 'first' => "亲,有个订单申请退款 \n订单号:{$order['order_id']}",
  777. 'keyword1' => '退款申请',
  778. 'keyword2' => '已支付',
  779. 'keyword3' => date('Y/m/d H:i', time()),
  780. 'remark' => '请及时处理'
  781. ]);
  782. }
  783. if (in_array($order['is_channel'], [1, 2])) {
  784. //小程序 发送模板消息
  785. RoutineTemplate::sendOrderRefundStatus($order, $refundReasonWap);
  786. }
  787. //通知后台消息提醒
  788. ChannelService::instance()->send('NEW_REFUND_ORDER', ['order_id' => $order['order_id']]);
  789. } catch (\Exception $e) {
  790. }
  791. //发送短信
  792. event('ShortMssageSend', [$order['order_id'], 'AdminRefund']);
  793. return true;
  794. }
  795. }
  796. /**
  797. * //TODO 支付成功后
  798. * @param $orderId
  799. * @param $paytype
  800. * @param $notify
  801. * @return bool
  802. */
  803. public static function paySuccess($orderId, $paytype = 'weixin', $formId = '')
  804. {
  805. $order = self::where('order_id', $orderId)->find();
  806. $resPink = true;
  807. $res1 = self::where('order_id', $orderId)->update(['paid' => 1, 'pay_type' => $paytype, 'pay_time' => date("Y-m-d H:i:s")]);//订单改为支付
  808. if ($order->combination_id && $res1 && !$order->refund_status) $resPink = StorePink::createPink($order);//创建拼团
  809. $oid = self::where('order_id', $orderId)->value('id');
  810. StoreOrderStatus::status($oid, 'pay_success', '用户付款成功');
  811. $now_money = User::where('uid', $order['uid'])->value('now_money');
  812. UserBill::expend('购买商品', $order['uid'], 'now_money', 'pay_money', $order['pay_price'], $order['id'], $now_money, '支付' . floatval($order['pay_price']) . '元购买商品');
  813. //支付成功后
  814. $res2 = true;
  815. $user = User::where('uid', $order['uid'])->find();
  816. if (($order['suit'] > 0 || $order['is_bind'] > 0) && !$user['lock_spread'] && $user['spread_uid']) User::where('uid', $order['uid'])->update(['lock_spread' => 1]);
  817. // @file_put_contents('order.txt', '【6】' . time() . PHP_EOL, FILE_APPEND);
  818. $res2 = $res2 && User::backMStoreBrokerage($order);
  819. $res2 = $res2 && self::addSuit($order);
  820. // @file_put_contents('order.txt', '【7】' . time() . PHP_EOL, FILE_APPEND);
  821. $res2 = $res2 && StoreOrder::sendSuit($order);
  822. @file_put_contents('order.txt', '【8】' . time() . PHP_EOL, FILE_APPEND);
  823. $res2 = $res2 && StoreOrder::sendGroupAward($order);
  824. @file_put_contents('order.txt', '【9】' . time() . PHP_EOL, FILE_APPEND);
  825. $res2 = $res2 && StoreOrder::sendAllSystemAward($order);
  826. @file_put_contents('order.txt', '【10】' . time() . PHP_EOL, FILE_APPEND);
  827. $res2 = $res2 && SystemGroupLevel::checkLevel($order['uid']);
  828. @file_put_contents('order.txt', '【11】' . time() . PHP_EOL, FILE_APPEND);
  829. $res2 = $res2 && SystemAwardLevel::checkLevel($order['uid']);
  830. @file_put_contents('order.txt', '【12】' . time() . PHP_EOL, FILE_APPEND);
  831. event('OrderPaySuccess', [$order, $formId]);
  832. @file_put_contents('order.txt', '【13】' . time() . PHP_EOL, FILE_APPEND);
  833. $res = $res1 && $resPink && $res2;
  834. return false !== $res;
  835. }
  836. public static function addSuit($order)
  837. {
  838. if ($order['suit'] <= 0) return true;
  839. $userInfo = User::getUserInfo($order['uid']);
  840. $spread = User::getUserInfo($userInfo['spread_uid']);
  841. if (StoreOrder::where('uid', $order['uid'])->where('paid', 1)->where('refund_status', 0)->where('is_del', 0)->where('is_system_del', 0)
  842. ->where('id', '<>', $order['id'])->where('suit', '>', 0)->find()) {
  843. $spread = $userInfo;
  844. }
  845. $re = true;
  846. $res = true;
  847. while ($spread) {
  848. if ($re) {
  849. $res = $res && User::where('uid', $spread['uid'])->inc('recommend_suit_num', $order['suit'])
  850. ->inc('group_suit_num', $order['suit'])->update();
  851. $re = false;
  852. } else {
  853. $res = $res && User::where('uid', $spread['uid'])->inc('group_suit_num', $order['suit'])->update();
  854. }
  855. $spread = User::getUserInfo($spread['spread_uid']);
  856. }
  857. return $res;
  858. }
  859. /*
  860. * 线下支付消息通知
  861. * 待完善
  862. *
  863. * */
  864. public static function createOrderTemplate($order)
  865. {
  866. //$goodsName = StoreOrderCartInfo::getProductNameList($order['id']);
  867. // RoutineTemplateService::sendTemplate(WechatUser::getOpenId($order['uid']),RoutineTemplateService::ORDER_CREATE, [
  868. // 'first'=>'亲,您购买的商品已支付成功',
  869. // 'keyword1'=>date('Y/m/d H:i',$order['add_time']),
  870. // 'keyword2'=>implode(',',$goodsName),
  871. // 'keyword3'=>$order['order_id'],
  872. // 'remark'=>'点击查看订单详情'
  873. // ],Url::build('/wap/My/order',['uni'=>$order['order_id']],true,true));
  874. // RoutineTemplateService::sendAdminNoticeTemplate([
  875. // 'first'=>"亲,您有一个新订单 \n订单号:{$order['order_id']}",
  876. // 'keyword1'=>'新订单',
  877. // 'keyword2'=>'线下支付',
  878. // 'keyword3'=>date('Y/m/d H:i',time()),
  879. // 'remark'=>'请及时处理'
  880. // ]);
  881. }
  882. /**
  883. * 获取订单详情
  884. * @param $uid
  885. * @param $key
  886. * @return array|\think\Model|null
  887. * @throws \think\db\exception\DataNotFoundException
  888. * @throws \think\db\exception\ModelNotFoundException
  889. * @throws \think\exception\DbException
  890. */
  891. public static function getUserOrderDetail($uid, $key)
  892. {
  893. return self::where('order_id|unique', $key)->where('uid', $uid)->where('is_del', 0)->find();
  894. }
  895. /**
  896. * TODO 订单发货
  897. * @param array $postageData 发货信息
  898. * @param string $oid orderID
  899. */
  900. public static function orderPostageAfter($postageData, $oid)
  901. {
  902. $order = self::where('id', $oid)->find();
  903. if ($postageData['delivery_type'] == 'send') {//送货
  904. RoutineTemplate::sendOrderPostage($order);
  905. } else if ($postageData['delivery_type'] == 'express') {//发货
  906. RoutineTemplate::sendOrderPostage($order, 1);
  907. }
  908. }
  909. /** 收货后发送模版消息
  910. * @param $order
  911. */
  912. public static function orderTakeAfter($order)
  913. {
  914. $title = self::getProductTitle($order['cart_id']);
  915. if ($order['is_channel'] == 1) {//小程序
  916. RoutineTemplate::sendOrderTakeOver($order, $title);
  917. } else {
  918. $openid = WechatUser::where('uid', $order['uid'])->value('openid');
  919. \crmeb\services\WechatTemplateService::sendTemplate($openid, \crmeb\services\WechatTemplateService::ORDER_TAKE_SUCCESS, [
  920. 'first' => '亲,您的订单已收货',
  921. 'keyword1' => $order['order_id'],
  922. 'keyword2' => '已收货',
  923. 'keyword3' => date('Y-m-d H:i:s', time()),
  924. 'keyword4' => $title,
  925. 'remark' => '感谢您的光临!'
  926. ]);
  927. }
  928. }
  929. /**
  930. * 删除订单
  931. * @param $uni
  932. * @param $uid
  933. * @return bool
  934. */
  935. public static function removeOrder($uni, $uid)
  936. {
  937. $order = self::getUserOrderDetail($uid, $uni);
  938. if (!$order) return self::setErrorInfo('订单不存在!');
  939. $order = self::tidyOrder($order);
  940. if ($order['_status']['_type'] != 0 && $order['_status']['_type'] != -2 && $order['_status']['_type'] != 4)
  941. return self::setErrorInfo('该订单无法删除!');
  942. if (false !== self::edit(['is_del' => 1], $order['id'], 'id') && false !== StoreOrderStatus::status($order['id'], 'remove_order', '删除订单')) {
  943. //未支付和已退款的状态下才可以退积分退库存退优惠券
  944. if ($order['_status']['_type'] == 0 || $order['_status']['_type'] == -2) {
  945. event('StoreOrderRegressionAllAfter', [$order]);
  946. }
  947. event('UserOrderRemoved', $uni);
  948. return true;
  949. } else
  950. return self::setErrorInfo('订单删除失败!');
  951. }
  952. /**
  953. * //TODO 用户确认收货
  954. * @param $uni
  955. * @param $uid
  956. */
  957. public static function takeOrder($uni, $uid)
  958. {
  959. $order = self::getUserOrderDetail($uid, $uni);
  960. if (!$order) return self::setErrorInfo('订单不存在!');
  961. $order = self::tidyOrder($order);
  962. if ($order['_status']['_type'] != 2) return self::setErrorInfo('订单状态错误!');
  963. self::beginTrans();
  964. if (false !== self::edit(['status' => 2], $order['id'], 'id') &&
  965. false !== StoreOrderStatus::status($order['id'], 'user_take_delivery', '用户已收货')) {
  966. try {
  967. OrderRepository::storeProductOrderUserTakeDelivery($order, $uid);
  968. UserBill::where('uid', $order['uid'])->where('link_id', $order['id'])->where('type', 'pay_money')->update(['take' => 1]);
  969. } catch (\Exception $e) {
  970. self::rollbackTrans();
  971. return self::setErrorInfo($e->getMessage());
  972. }
  973. self::commitTrans();
  974. event('UserLevelAfter', [User::get($uni)]);
  975. event('UserOrderTake', $uni);
  976. //短信通知
  977. event('ShortMssageSend', [$order['order_id'], ['Receiving', 'AdminConfirmTakeOver']]);
  978. return true;
  979. } else {
  980. self::rollbackTrans();
  981. return false;
  982. }
  983. }
  984. /**
  985. * 获取订单状态购物车等信息
  986. * @param $order
  987. * @param bool $detail 是否获取订单购物车详情
  988. * @param bool $isPic 是否获取订单状态图片
  989. * @return mixed
  990. * @throws \think\db\exception\DataNotFoundException
  991. * @throws \think\db\exception\ModelNotFoundException
  992. * @throws \think\exception\DbException
  993. */
  994. public static function tidyOrder($order, $detail = false, $isPic = false)
  995. {
  996. if ($detail == true && isset($order['id'])) {
  997. $cartInfo = StoreOrderCartInfo::where('oid', $order['id'])->column('cart_info', 'unique') ?: [];
  998. $info = [];
  999. foreach ($cartInfo as $k => $cart) {
  1000. $cart = json_decode($cart, true);
  1001. $cart['unique'] = $k;
  1002. //新增是否评价字段
  1003. $cart['is_reply'] = StoreProductReply::where('unique', $k)->count();
  1004. array_push($info, $cart);
  1005. unset($cart);
  1006. }
  1007. $order['cartInfo'] = $info;
  1008. }
  1009. $status = [];
  1010. if (!$order['paid'] && $order['pay_type'] == 'offline' && !$order['status'] >= 2) {
  1011. $status['_type'] = 9;
  1012. $status['_title'] = '线下付款';
  1013. $status['_msg'] = '商家处理中,请耐心等待';
  1014. $status['_class'] = 'nobuy';
  1015. } else if (!$order['paid']) {
  1016. $status['_type'] = 0;
  1017. $status['_title'] = '未支付';
  1018. //系统预设取消订单时间段
  1019. $keyValue = ['order_cancel_time', 'order_activity_time', 'order_bargain_time', 'order_seckill_time', 'order_pink_time'];
  1020. //获取配置
  1021. $systemValue = SystemConfigService::more($keyValue);
  1022. //格式化数据
  1023. $systemValue = self::setValeTime($keyValue, is_array($systemValue) ? $systemValue : []);
  1024. if ($order['pink_id'] || $order['combination_id']) {
  1025. $order_pink_time = $systemValue['order_pink_time'] ? $systemValue['order_pink_time'] : $systemValue['order_activity_time'];
  1026. $time = bcadd(strtotime($order['add_time']), $order_pink_time * 3600, 0);
  1027. $status['_msg'] = '请在' . date('m-d H:i:s', $time) . '前完成支付!';
  1028. } else if ($order['seckill_id']) {
  1029. $order_seckill_time = $systemValue['order_seckill_time'] ? $systemValue['order_seckill_time'] : $systemValue['order_activity_time'];
  1030. $time = bcadd(strtotime($order['add_time']), $order_seckill_time * 3600, 0);
  1031. $status['_msg'] = '请在' . date('m-d H:i:s', $time) . '前完成支付!';
  1032. } else if ($order['bargain_id']) {
  1033. $order_bargain_time = $systemValue['order_bargain_time'] ? $systemValue['order_bargain_time'] : $systemValue['order_activity_time'];
  1034. $time = bcadd(strtotime($order['add_time']), $order_bargain_time * 3600, 0);
  1035. $status['_msg'] = '请在' . date('m-d H:i:s', $time) . '前完成支付!';
  1036. } else {
  1037. $time = bcadd(strtotime($order['add_time']), $systemValue['order_cancel_time'] * 3600, 0);
  1038. $status['_msg'] = '请在' . date('m-d H:i:s', $time) . '前完成支付!';
  1039. }
  1040. $status['_class'] = 'nobuy';
  1041. } else if ($order['refund_status'] == 1) {
  1042. $status['_type'] = -1;
  1043. $status['_title'] = '申请退款中';
  1044. $status['_msg'] = '商家审核中,请耐心等待';
  1045. $status['_class'] = 'state-sqtk';
  1046. } else if ($order['refund_status'] == 2) {
  1047. $status['_type'] = -2;
  1048. $status['_title'] = '已退款';
  1049. $status['_msg'] = '已为您退款,感谢您的支持';
  1050. $status['_class'] = 'state-sqtk';
  1051. } else if (!$order['status']) {
  1052. if ($order['pink_id']) {
  1053. if (StorePink::where('id', $order['pink_id'])->where('status', 1)->count()) {
  1054. $status['_type'] = 1;
  1055. $status['_title'] = '拼团中';
  1056. $status['_msg'] = '等待其他人参加拼团';
  1057. $status['_class'] = 'state-nfh';
  1058. } else {
  1059. $status['_type'] = 1;
  1060. $status['_title'] = '未发货';
  1061. $status['_msg'] = '商家未发货,请耐心等待';
  1062. $status['_class'] = 'state-nfh';
  1063. }
  1064. } else {
  1065. if ($order['shipping_type'] === 1) {
  1066. $status['_type'] = 1;
  1067. $status['_title'] = '未发货';
  1068. $status['_msg'] = '商家未发货,请耐心等待';
  1069. $status['_class'] = 'state-nfh';
  1070. } else {
  1071. $status['_type'] = 1;
  1072. $status['_title'] = '待核销';
  1073. $status['_msg'] = '待核销,请到核销点进行核销';
  1074. $status['_class'] = 'state-nfh';
  1075. }
  1076. }
  1077. } else if ($order['status'] == 1) {
  1078. if ($order['delivery_type'] == 'send') {//TODO 送货
  1079. $status['_type'] = 2;
  1080. $status['_title'] = '待收货';
  1081. $status['_msg'] = date('m月d日H时i分', StoreOrderStatus::getTime($order['id'], 'delivery')) . '服务商已送货';
  1082. $status['_class'] = 'state-ysh';
  1083. } else {//TODO 发货
  1084. $status['_type'] = 2;
  1085. $status['_title'] = '待收货';
  1086. if ($order['delivery_type'] == 'fictitious')
  1087. $_time = StoreOrderStatus::getTime($order['id'], 'delivery_fictitious');
  1088. else
  1089. $_time = StoreOrderStatus::getTime($order['id'], 'delivery_goods');
  1090. $status['_msg'] = date('m月d日H时i分', $_time) . '服务商已发货';
  1091. $status['_class'] = 'state-ysh';
  1092. }
  1093. } else if ($order['status'] == 2) {
  1094. $status['_type'] = 3;
  1095. $status['_title'] = '待评价';
  1096. $status['_msg'] = '已收货,快去评价一下吧';
  1097. $status['_class'] = 'state-ypj';
  1098. } else if ($order['status'] == 3) {
  1099. $status['_type'] = 4;
  1100. $status['_title'] = '交易完成';
  1101. $status['_msg'] = '交易完成,感谢您的支持';
  1102. $status['_class'] = 'state-ytk';
  1103. }
  1104. if (isset($order['pay_type']))
  1105. $status['_payType'] = isset(self::$payType[$order['pay_type']]) ? self::$payType[$order['pay_type']] : '其他方式';
  1106. if (isset($order['delivery_type']))
  1107. $status['_deliveryType'] = isset(self::$deliveryType[$order['delivery_type']]) ? self::$deliveryType[$order['delivery_type']] : '其他方式';
  1108. $order['_status'] = $status;
  1109. $order['_pay_time'] = isset($order['pay_time']) && $order['pay_time'] != null ? $order['pay_time'] : $order['add_time'];
  1110. $order['_add_time'] = $order['add_time'];
  1111. $order['status_pic'] = '';
  1112. //获取产品状态图片
  1113. if ($isPic) {
  1114. $order_details_images = sys_data('order_details_images') ?: [];
  1115. foreach ($order_details_images as $image) {
  1116. if (isset($image['order_status']) && $image['order_status'] == $order['_status']['_type']) {
  1117. $order['status_pic'] = $image['pic'];
  1118. break;
  1119. }
  1120. }
  1121. }
  1122. $order['offlinePayStatus'] = (int)sys_config('offline_pay_status') ?? (int)2;
  1123. return $order;
  1124. }
  1125. /**
  1126. * 设置订单查询状态
  1127. * @param $status
  1128. * @param int $uid
  1129. * @param null $model
  1130. * @return StoreOrder|null
  1131. */
  1132. public static function statusByWhere($status, $uid = 0, $model = null)
  1133. {
  1134. // $orderId = StorePink::where('uid',$uid)->where('status',1)->column('order_id','id');//获取正在拼团的订单编号
  1135. if ($model == null) $model = new self;
  1136. if ('' === $status)
  1137. return $model;
  1138. else if ($status == 0)//未支付
  1139. return $model->where('paid', 0)->where('status', 0)->where('refund_status', 0);
  1140. else if ($status == 1)//待发货
  1141. return $model->where('paid', 1)->where('status', 0)->where('refund_status', 0);
  1142. else if ($status == 2)//待收货
  1143. return $model->where('paid', 1)->where('status', 1)->where('refund_status', 0);
  1144. else if ($status == 3)//待评价
  1145. return $model->where('paid', 1)->where('status', 2)->where('refund_status', 0);
  1146. else if ($status == 4)//已完成
  1147. return $model->where('paid', 1)->where('status', 3)->where('refund_status', 0);
  1148. else if ($status == -1)//退款中
  1149. return $model->where('paid', 1)->where('refund_status', 1);
  1150. else if ($status == -2)//已退款
  1151. return $model->where('paid', 1)->where('refund_status', 2);
  1152. else if ($status == -3)//退款
  1153. return $model->where('paid', 1)->where('refund_status', 'IN', '1,2');
  1154. // else if($status == 11){
  1155. // return $model->where('order_id','IN',implode(',',$orderId));
  1156. // }
  1157. else
  1158. return $model;
  1159. }
  1160. /**
  1161. * 获取订单并分页
  1162. * @param $uid
  1163. * @param string $status
  1164. * @param int $page
  1165. * @param int $limit
  1166. * @return mixed
  1167. * @throws \think\db\exception\DataNotFoundException
  1168. * @throws \think\db\exception\ModelNotFoundException
  1169. * @throws \think\exception\DbException
  1170. */
  1171. public static function getUserOrderList($uid, $status = '', $page = 0, $limit = 8)
  1172. {
  1173. if ($page) $list = self::statusByWhere($status, $uid)->where('is_del', 0)->where('uid', $uid)
  1174. ->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')
  1175. ->order('add_time DESC')->page((int)$page, (int)$limit)->select()->toArray();
  1176. else $list = self::statusByWhere($status, $uid)->where('is_del', 0)->where('uid', $uid)
  1177. ->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')
  1178. ->order('add_time DESC')->page((int)$page, (int)$limit)->select()->toArray();
  1179. foreach ($list as $k => $order) {
  1180. $list[$k] = self::tidyOrder($order, true);
  1181. }
  1182. return $list;
  1183. }
  1184. /**
  1185. * 获取推广人地下用户的订单金额
  1186. * @param string $uid
  1187. * @param string $status
  1188. * @return array
  1189. */
  1190. public static function getUserOrderCount($uid = '', $status = '')
  1191. {
  1192. $res = self::statusByWhere($status, $uid)->where('uid', 'IN', $uid)->column('pay_price');
  1193. return $res;
  1194. }
  1195. /**
  1196. * 搜索某个订单详细信息
  1197. * @param $uid
  1198. * @param $order_id
  1199. * @return bool|mixed
  1200. * @throws \think\db\exception\DataNotFoundException
  1201. * @throws \think\db\exception\ModelNotFoundException
  1202. * @throws \think\exception\DbException
  1203. */
  1204. public static function searchUserOrder($uid, $order_id)
  1205. {
  1206. $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')
  1207. ->order('add_time DESC')->find();
  1208. if (!$order)
  1209. return false;
  1210. else
  1211. return self::tidyOrder($order->toArray(), true);
  1212. }
  1213. /**
  1214. * 订单评价信息记录
  1215. * @param $oid
  1216. * @return StoreOrderStatus|\think\Model
  1217. * @throws \Exception
  1218. */
  1219. public static function orderOver($oid)
  1220. {
  1221. $res = self::edit(['status' => '3'], $oid, 'id');
  1222. if (!$res) exception('评价后置操作失败!');
  1223. return StoreOrderStatus::status($oid, 'check_order_over', '用户评价');
  1224. }
  1225. /**
  1226. * 设置订单产品评价完毕事件
  1227. * @param $oid
  1228. * @return StoreOrderStatus|\think\Model
  1229. * @throws \Exception
  1230. */
  1231. public static function checkOrderOver($oid)
  1232. {
  1233. $uniqueList = StoreOrderCartInfo::where('oid', $oid)->column('unique', 'unique');
  1234. //订单产品全部评价完成
  1235. if (StoreProductReply::where('unique', 'IN', $uniqueList)->where('oid', $oid)->count() == count($uniqueList)) {
  1236. event('StoreProductOrderOver', [$oid]);
  1237. return self::orderOver($oid);
  1238. }
  1239. }
  1240. public static function getOrderStatusNum($uid)
  1241. {
  1242. $noBuy = (int)self::where('uid', $uid)->where('paid', 0)->where('is_del', 0)->where('pay_type', '<>', 'offline')->count();
  1243. $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();
  1244. $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();
  1245. $noPostage = (int)bcadd($noPostageNoPink, $noPostageYesPink, 0);
  1246. $noTake = (int)self::where('uid', $uid)->where('paid', 1)->where('is_del', 0)->where('status', 1)->where('pay_type', '<>', 'offline')->count();
  1247. $noReply = (int)self::where('uid', $uid)->where('paid', 1)->where('is_del', 0)->where('status', 2)->count();
  1248. $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();
  1249. $noRefund = (int)self::where('uid', $uid)->where('paid', 1)->where('is_del', 0)->where('refund_status', 'IN', '1,2')->count();
  1250. return compact('noBuy', 'noPostage', 'noTake', 'noReply', 'noPink', 'noRefund');
  1251. }
  1252. /**
  1253. * 购买商品赠送积分
  1254. * @param $order
  1255. * @return bool
  1256. * @throws \think\Exception
  1257. * @throws \think\db\exception\DataNotFoundException
  1258. * @throws \think\db\exception\ModelNotFoundException
  1259. * @throws \think\exception\DbException
  1260. */
  1261. public static function gainUserIntegral($order)
  1262. {
  1263. if ($order['gain_integral'] > 0) {
  1264. $userInfo = User::getUserInfo($order['uid']);
  1265. BaseModel::beginTrans();
  1266. $res1 = false != User::where('uid', $userInfo['uid'])->update(['integral' => bcadd($userInfo['integral'], $order['gain_integral'], 2)]);
  1267. $res2 = false != UserBill::income('购买商品赠送积分', $order['uid'], 'integral', 'gain', $order['gain_integral'], $order['id'], $userInfo['integral'], '购买商品赠送' . floatval($order['gain_integral']) . '积分');
  1268. $res = $res1 && $res2;
  1269. BaseModel::checkTrans($res);
  1270. return $res;
  1271. }
  1272. return true;
  1273. }
  1274. /**
  1275. * 获取当前订单中有没有拼团存在
  1276. * @param $pid
  1277. * @return int|string
  1278. */
  1279. public static function getIsOrderPink($pid = 0, $uid = 0)
  1280. {
  1281. return self::where('uid', $uid)->where('pink_id', $pid)->where('refund_status', 0)->where('is_del', 0)->count();
  1282. }
  1283. /**
  1284. * 获取order_id
  1285. * @param $pid
  1286. * @return mixed
  1287. */
  1288. public static function getStoreIdPink($pid = 0, $uid = 0)
  1289. {
  1290. return self::where('uid', $uid)->where('pink_id', $pid)->where('is_del', 0)->value('order_id');
  1291. }
  1292. /**
  1293. * 删除当前用户拼团未支付的订单
  1294. */
  1295. public static function delCombination()
  1296. {
  1297. self::where('combination', '>', 0)->where('paid', 0)->where('uid', User::getActiveUid())->delete();
  1298. }
  1299. public static function getUserPrice($uid = 0)
  1300. {
  1301. if (!$uid) return 0;
  1302. $price = self::where('paid', 1)->where('uid', $uid)->where('status', 2)->where('refund_status', 0)->column('pay_price', 'id');
  1303. $count = 0;
  1304. if ($price) {
  1305. foreach ($price as $v) {
  1306. $count = bcadd($count, $v, 2);
  1307. }
  1308. }
  1309. return $count;
  1310. }
  1311. /**
  1312. * 个人中心获取个人订单列表和订单搜索
  1313. * @param int $uid 用户uid
  1314. * @param int | string 查找订单类型
  1315. * @param int $first 分页
  1316. * @param int 每页显示多少条
  1317. * @param string $search 订单号
  1318. * @return array
  1319. * */
  1320. public static function getUserOrderSearchList($uid, $type, $page, $limit, $search)
  1321. {
  1322. if ($search) {
  1323. $order = self::searchUserOrder($uid, $search) ?: [];
  1324. $list = $order == false ? [] : [$order];
  1325. } else {
  1326. $list = self::getUserOrderList($uid, $type, $page, $limit);
  1327. }
  1328. foreach ($list as $k => $order) {
  1329. $list[$k] = self::tidyOrder($order, true);
  1330. if ($list[$k]['_status']['_type'] == 3) {
  1331. foreach ($order['cartInfo'] ?: [] as $key => $product) {
  1332. $list[$k]['cartInfo'][$key]['is_reply'] = StoreProductReply::isReply($product['unique'], 'product');
  1333. //$list[$k]['cartInfo'][$key]['add_time'] = $product['add_time'];
  1334. }
  1335. }
  1336. }
  1337. return $list;
  1338. }
  1339. /**
  1340. * 获取用户下级的订单
  1341. * @param int $xuid 下级用户用户uid
  1342. * @param int $uid 用户uid
  1343. * @param int $type 订单类型
  1344. * @param int $first 截取行数
  1345. * @param int $limit 展示条数
  1346. * @return array
  1347. * */
  1348. public static function getSubordinateOrderlist($xUid, $uid, $type, $first, $limit)
  1349. {
  1350. $list = [];
  1351. if (!$xUid) {
  1352. $arr = User::getOneSpreadUid($uid);
  1353. foreach ($arr as $v) $list = StoreOrder::getUserOrderList($v, $type, $first, $limit);
  1354. } else $list = self::getUserOrderList($xUid, $type, $first, $limit);
  1355. foreach ($list as $k => $order) {
  1356. $list[$k] = self::tidyOrder($order, true);
  1357. if ($list[$k]['_status']['_type'] == 3) {
  1358. foreach ($order['cartInfo'] ?: [] as $key => $product) {
  1359. $list[$k]['cartInfo'][$key]['is_reply'] = StoreProductReply::isReply($product['unique'], 'product');
  1360. }
  1361. }
  1362. }
  1363. return $list;
  1364. }
  1365. /**
  1366. * 获取 今日 昨日 本月 订单金额
  1367. * @return mixed
  1368. */
  1369. public static function getOrderTimeData($store_id = 0, $is_consumer = 0)
  1370. {
  1371. $where = [];
  1372. if ($store_id > 0) {
  1373. $where['store_id'] = $store_id;
  1374. }
  1375. $where['is_consumer'] = $is_consumer;
  1376. $to_day = strtotime(date('Y-m-d'));//今日
  1377. $pre_day = strtotime(date('Y-m-d', strtotime('-1 day')));//昨日
  1378. $now_month = strtotime(date('Y-m'));//本月
  1379. //今日成交额
  1380. // $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;
  1381. $data['todayPrice'] = number_format(self::where('is_del', 0)->where('pay_time', '>=', $to_day)->where('paid', 1)->where('refund_status', 0)->where($where)->value('sum(pay_price)'), 2) ?? 0;
  1382. //今日订单数
  1383. $data['todayCount'] = self::where('is_del', 0)->where('pay_time', '>=', $to_day)->where('paid', 1)->where('refund_status', 0)->where($where)->count();
  1384. //昨日成交额
  1385. $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)->where($where)->value('sum(pay_price)'), 2) ?? 0;
  1386. //昨日订单数
  1387. $data['proCount'] = self::where('is_del', 0)->where('pay_time', '<', $to_day)->where('pay_time', '>=', $pre_day)->where('paid', 1)->where('refund_status', 0)->where($where)->count();
  1388. //本月成交额
  1389. $data['monthPrice'] = number_format(self::where('is_del', 0)->where('pay_time', '>=', $now_month)->where('paid', 1)->where('refund_status', 0)->where($where)->value('sum(pay_price)'), 2) ?? 0;
  1390. //本月订单数
  1391. $data['monthCount'] = self::where('is_del', 0)->where('pay_time', '>=', $now_month)->where('paid', 1)->where('refund_status', 0)->where($where)->count();
  1392. return $data;
  1393. }
  1394. /**
  1395. * 获取某个用户的订单统计数据
  1396. * @param $uid
  1397. * @return mixed
  1398. */
  1399. public static function getOrderData($uid)
  1400. {
  1401. //订单支付没有退款 数量
  1402. $data['order_count'] = self::where('is_del', 0)->where('paid', 1)->where('uid', $uid)->where('refund_status', 0)->count();
  1403. //订单支付没有退款 支付总金额
  1404. $data['sum_price'] = self::where('is_del', 0)->where('paid', 1)->where('uid', $uid)->where('refund_status', 0)->sum('pay_price');
  1405. //订单待支付 数量
  1406. $data['unpaid_count'] = self::statusByWhere(0, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1407. //订单待发货 数量
  1408. $data['unshipped_count'] = self::statusByWhere(1, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1409. //订单待收货 数量
  1410. $data['received_count'] = self::statusByWhere(2, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1411. //订单待评价 数量
  1412. $data['evaluated_count'] = self::statusByWhere(3, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1413. //订单已完成 数量
  1414. $data['complete_count'] = self::statusByWhere(4, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1415. //订单退款
  1416. $data['refund_count'] = self::statusByWhere(-1, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1417. return $data;
  1418. }
  1419. /**
  1420. * 获取订单统计数据
  1421. * @param $uid
  1422. * @return mixed
  1423. */
  1424. public static function getOrderDataAdmin($store_id = 0, $is_consumer = 0)
  1425. {
  1426. $where = [];
  1427. if ($store_id > 0) {
  1428. $where['store_id'] = $store_id;
  1429. }
  1430. $where['is_consumer'] = $is_consumer;
  1431. //订单支付没有退款 数量
  1432. $data['order_count'] = self::where('is_del', 0)->where('paid', 1)->where('refund_status', 0)->where($where)->count();
  1433. //订单支付没有退款 支付总金额
  1434. $data['sum_price'] = self::where('is_del', 0)->where('paid', 1)->where('refund_status', 0)->where($where)->sum('pay_price');
  1435. //订单待支付 数量
  1436. $data['unpaid_count'] = self::statusByWhere(0, 0)->where('is_del', 0)->where($where)->count();
  1437. //订单待发货 数量
  1438. $data['unshipped_count'] = self::statusByWhere(1, 0)->where('is_del', 0)->where($where)->count();
  1439. //订单待收货 数量
  1440. $data['received_count'] = self::statusByWhere(2, 0)->where('is_del', 0)->where($where)->count();
  1441. //订单待评价 数量
  1442. $data['evaluated_count'] = self::statusByWhere(3, 0)->where('is_del', 0)->where($where)->count();
  1443. //订单已完成 数量
  1444. $data['complete_count'] = self::statusByWhere(4, 0)->where('is_del', 0)->where($where)->count();
  1445. //订单退款 数量
  1446. $data['refund_count'] = self::statusByWhere(-3, 0)->where('is_del', 0)->where($where)->count();
  1447. return $data;
  1448. }
  1449. /**
  1450. * 累计消费
  1451. * @param $uid
  1452. * @return float
  1453. */
  1454. public static function getOrderStatusSum($uid)
  1455. {
  1456. return self::where('uid', $uid)->where('is_del', 0)->where('paid', 1)->where('refund_status', 0)->sum('pay_price');
  1457. }
  1458. public static function getPinkOrderId($id)
  1459. {
  1460. return self::where('id', $id)->value('order_id');
  1461. }
  1462. /**
  1463. * 未支付订单自动取消
  1464. * @param int $limit 分页截取条数
  1465. * @param string $prefid 缓存名称
  1466. * @param int $expire 缓存时间
  1467. * @return string|null
  1468. * @throws \Psr\SimpleCache\InvalidArgumentException
  1469. */
  1470. public static function orderUnpaidCancel()
  1471. {
  1472. //系统预设取消订单时间段
  1473. $keyValue = ['order_cancel_time', 'order_activity_time', 'order_bargain_time', 'order_seckill_time', 'order_pink_time'];
  1474. //获取配置
  1475. $systemValue = SystemConfigService::more($keyValue);
  1476. //格式化数据
  1477. $systemValue = self::setValeTime($keyValue, is_array($systemValue) ? $systemValue : []);
  1478. //检查是否有未支付的订单 未支付查询条件
  1479. $unPidCount = self::where('paid', 0)->where('pay_type', '<>', 'offline')->where('is_del', 0)->where('status', 0)->where('refund_status', 0)->count();
  1480. if (!$unPidCount) return null;
  1481. try {
  1482. $res = true;
  1483. // 未支付查询条件
  1484. $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();
  1485. foreach ($orderList as $order) {
  1486. if ($order['seckill_id']) {
  1487. //优先使用单独配置的过期时间
  1488. $order_seckill_time = $systemValue['order_seckill_time'] ? $systemValue['order_seckill_time'] : $systemValue['order_activity_time'];
  1489. $res = $res && self::RegressionAll($order_seckill_time, $order);
  1490. unset($order_seckill_time);
  1491. } else if ($order['bargain_id']) {
  1492. $order_bargain_time = $systemValue['order_bargain_time'] ? $systemValue['order_bargain_time'] : $systemValue['order_activity_time'];
  1493. $res = $res && self::RegressionAll($order_bargain_time, $order);
  1494. unset($order_bargain_time);
  1495. } else if ($order['pink_id'] || $order['combination_id']) {
  1496. $order_pink_time = $systemValue['order_pink_time'] ? $systemValue['order_pink_time'] : $systemValue['order_activity_time'];
  1497. $res = $res && self::RegressionAll($order_pink_time, $order);
  1498. unset($order_pink_time);
  1499. } else {
  1500. $res = $res && self::RegressionAll($systemValue['order_cancel_time'], $order);
  1501. }
  1502. }
  1503. if (!$res) throw new \Exception('更新错误');
  1504. unset($orderList, $res, $pages);
  1505. return null;
  1506. } catch (PDOException $e) {
  1507. Log::error('未支付自动取消时发生数据库查询错误,错误原因为:' . $e->getMessage());
  1508. throw new \Exception($e->getMessage());
  1509. } catch (\think\Exception $e) {
  1510. Log::error('未支付自动取消时发生系统错误,错误原因为:' . $e->getMessage());
  1511. throw new \Exception($e->getMessage());
  1512. }
  1513. }
  1514. /**
  1515. * 未支付订单超过预设时间回退所有,如果不设置未支付过期时间,将不取消订单
  1516. * @param $time 预设时间
  1517. * @param $order 订单详情
  1518. * @return bool
  1519. * @throws \think\db\exception\DataNotFoundException
  1520. * @throws \think\db\exception\ModelNotFoundException
  1521. * @throws \think\exception\DbException
  1522. */
  1523. protected static function RegressionAll($time, $order)
  1524. {
  1525. if ($time == 0) return true;
  1526. if ((strtotime($order['add_time']) + bcmul($time, 3600, 0)) < time()) {
  1527. $res1 = self::RegressionStock($order);
  1528. $res2 = self::RegressionIntegral($order);
  1529. $res3 = self::RegressionCoupon($order);
  1530. $res = $res1 && $res2 && $res3;
  1531. if ($res) $res = false !== self::where('order_id', $order['order_id'])->update(['is_del' => 1, 'mark' => '订单未支付已超过系统预设时间']);
  1532. unset($res1, $res2, $res3);
  1533. return $res;
  1534. } else
  1535. return true;
  1536. }
  1537. /**
  1538. * 格式化数据
  1539. * @param array $array 原本数据键
  1540. * @param $value 需要格式化的数据
  1541. * @param int $default 默认值
  1542. * @return mixed
  1543. */
  1544. protected static function setValeTime(array $array, $value, $default = 0)
  1545. {
  1546. foreach ($array as $item) {
  1547. if (!isset($value[$item]))
  1548. $value[$item] = $default;
  1549. else if (is_string($value[$item]))
  1550. $value[$item] = (float)$value[$item];
  1551. }
  1552. return $value;
  1553. }
  1554. public static function getOrderTotalPrice($cartInfo)
  1555. {
  1556. $totalPrice = 0;
  1557. foreach ($cartInfo as $cart) {
  1558. $totalPrice = bcadd($totalPrice, bcmul($cart['cart_num'], $cart['truePrice'], 2), 2);
  1559. }
  1560. return $totalPrice;
  1561. }
  1562. public static function getOrderCostPrice($cartInfo)
  1563. {
  1564. $costPrice = 0;
  1565. foreach ($cartInfo as $cart) {
  1566. $costPrice = bcadd($costPrice, bcmul($cart['cart_num'], $cart['costPrice'], 2), 2);
  1567. }
  1568. return $costPrice;
  1569. }
  1570. public static function getCombinationOrderCostPrice($cartInfo)
  1571. {
  1572. $costPrice = 0;
  1573. foreach ($cartInfo as $cart) {
  1574. if ($cart['combination_id']) {
  1575. $costPrice = bcadd($costPrice, bcmul($cart['cart_num'], StoreCombination::where('id', $cart['combination_id'])->value('price'), 2), 2);
  1576. }
  1577. }
  1578. return (float)$costPrice;
  1579. }
  1580. public static function yueRefundAfter($order)
  1581. {
  1582. }
  1583. /**
  1584. * 获取余额支付的金额
  1585. * @param $uid
  1586. * @return float|int
  1587. */
  1588. public static function getOrderStatusYueSum($uid)
  1589. {
  1590. return self::where('uid', $uid)->where('is_del', 0)->where('is_del', 0)->where('pay_type', 'yue')->where('paid', 1)->sum('pay_price');
  1591. }
  1592. /**
  1593. * 砍价支付成功订单数量
  1594. * @param $bargain
  1595. * @return int
  1596. */
  1597. public static function getBargainPayCount($bargain)
  1598. {
  1599. return self::where('bargain_id', $bargain)->where(['paid' => 1, 'refund_status' => 0])->count();
  1600. }
  1601. /**
  1602. * 7天自动收货
  1603. * @return bool
  1604. */
  1605. public static function startTakeOrder()
  1606. {
  1607. //7天前时间戳
  1608. $systemDeliveryTime = SystemConfigService::get('system_delivery_time') ?? 0;
  1609. //0为取消自动收货功能
  1610. if ($systemDeliveryTime == 0) return true;
  1611. $sevenDay = strtotime(date('Y-m-d H:i:s', strtotime('-' . $systemDeliveryTime . ' day')));
  1612. $model = new self;
  1613. $model = $model->alias('o');
  1614. $model = $model->join('StoreOrderStatus s', 's.oid=o.id');
  1615. $model = $model->where('o.paid', 1);
  1616. $model = $model->where('s.change_type', 'IN', ['delivery_goods', 'delivery_fictitious', 'delivery']);
  1617. $model = $model->where('s.change_time', '<', $sevenDay);
  1618. $model = $model->where('o.status', 1);
  1619. $model = $model->where('o.refund_status', 0);
  1620. $model = $model->where('o.is_del', 0);
  1621. $orderInfo = $model->column('id', 'id');
  1622. if (!count($orderInfo)) return true;
  1623. $res = true;
  1624. foreach ($orderInfo as $key => &$item) {
  1625. $order = self::get($item);
  1626. if ($order['status'] == 2) continue;
  1627. if ($order['paid'] == 1 && $order['status'] == 1) $data['status'] = 2;
  1628. else if ($order['pay_type'] == 'offline') $data['status'] = 2;
  1629. else continue;
  1630. if (!self::edit($data, $item, 'id')) continue;
  1631. try {
  1632. OrderRepository::storeProductOrderTakeDeliveryAdmin($order, $item);
  1633. $res = $res && true;
  1634. } catch (\Exception $e) {
  1635. $res = $res && false;
  1636. }
  1637. $res = $res && StoreOrderStatus::status($item, 'take_delivery', '已收货[自动收货]');
  1638. }
  1639. if (!$res) {
  1640. throw new \Exception('');
  1641. }
  1642. }
  1643. /**
  1644. * 获取订单信息
  1645. * @param $id
  1646. * @param string $field
  1647. * @return array|null|\think\Model
  1648. * @throws \think\db\exception\DataNotFoundException
  1649. * @throws \think\db\exception\ModelNotFoundException
  1650. * @throws \think\exception\DbException
  1651. */
  1652. public static function getOrderInfo($id, $field = 'order_id')
  1653. {
  1654. return self::where('id', $id)->field($field)->find();
  1655. }
  1656. /**
  1657. * 订单每月统计数据
  1658. * @param $page
  1659. * @param $limit
  1660. * @return array
  1661. */
  1662. public static function getOrderDataPriceCount($page, $limit, $start, $stop)
  1663. {
  1664. if (!$limit) return [];
  1665. $model = new self;
  1666. if ($start != '' && $stop != '') $model = $model->where('pay_time', '>', $start)->where('pay_time', '<=', $stop);
  1667. $model = $model->field('sum(pay_price) as price,count(id) as count,FROM_UNIXTIME(pay_time, \'%m-%d\') as time');
  1668. $model = $model->where('is_del', 0);
  1669. $model = $model->where('paid', 1);
  1670. $model = $model->where('refund_status', 0);
  1671. $model = $model->group("FROM_UNIXTIME(pay_time, '%Y-%m-%d')");
  1672. $model = $model->order('pay_time DESC');
  1673. if ($page) $model = $model->page($page, $limit);
  1674. return $model->select();
  1675. }
  1676. /**
  1677. * 每月订单汇总
  1678. * @param $store_id
  1679. * @param $start
  1680. * @param $end
  1681. * @return array
  1682. * @throws \think\db\exception\DataNotFoundException
  1683. * @throws \think\db\exception\DbException
  1684. * @throws \think\db\exception\ModelNotFoundException
  1685. */
  1686. public static function getordermonth($store_id, $start, $end)
  1687. {
  1688. $model = new self;
  1689. $model = $model->where('pay_time', '>', $start)->where('pay_time', '<=', $end);
  1690. $model = $model->where('is_del', 0);
  1691. $model = $model->where('paid', 1);
  1692. $model = $model->where('refund_status', 0);
  1693. $model = $model->where('store_id', $store_id);
  1694. $data[] = $model->where('is_consumer', 0)->where('use_integral', 0)->field("sum(pay_price) as price,count(id) as count,'普通订单' as order_type")->find()->toArray();
  1695. $data[] = $model->where('is_consumer', 1)->field("sum(pay_price) as price,count(id) as count,'消费券订单' as order_type")->find()->toArray();
  1696. $data[] = $model->where('is_consumer', 0)->where('use_integral', '>', 0)->field("sum(pay_price) as price,count(id) as count,'积分订单' as order_type")->find()->toArray();
  1697. $day = self::where('paid', 1)->where('refund_status', 0)->where('store_id', $store_id)->where('pay_time', '>', date("y-m-d"))->field('sum(pay_price) as price,count(id) as count')->find();
  1698. return compact('day', 'data');
  1699. }
  1700. /**
  1701. * 前台订单管理订单列表获取
  1702. * @param $where
  1703. * @return mixed
  1704. */
  1705. public static function orderList($where)
  1706. {
  1707. $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')->where('is_del', 0);
  1708. if ($where['order'] != '') {
  1709. $model = $model->order(self::setOrder($where['order']));
  1710. } else {
  1711. $model = $model->order('a.id desc');
  1712. }
  1713. $count = $model->count('id');
  1714. $data = ($data = $model->page((int)$where['page'], (int)$where['limit'])->select()) && count($data) ? $data->toArray() : [];
  1715. $data = self::tidyAdminOrder($data);
  1716. return compact('count', 'data');
  1717. }
  1718. /**
  1719. * 前台订单管理 订单信息设置
  1720. * @param $data
  1721. * @param bool $status
  1722. * @return mixed
  1723. * @throws \think\db\exception\DataNotFoundException
  1724. * @throws \think\db\exception\ModelNotFoundException
  1725. * @throws \think\exception\DbException
  1726. */
  1727. public static function tidyAdminOrder($data, $status = false)
  1728. {
  1729. foreach ($data as &$item) {
  1730. $_info = StoreOrderCartInfo::where('oid', $item['id'])->field('cart_info')->select()->toArray();
  1731. foreach ($_info as $k => $v) {
  1732. if (!is_array($v['cart_info']))
  1733. $_info[$k]['cart_info'] = json_decode($v['cart_info'], true);
  1734. }
  1735. foreach ($_info as $k => $v) {
  1736. 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']);
  1737. $_info[$k]['cart_info']['productInfo']['suk'] = '';
  1738. if (isset($v['cart_info']['productInfo']['attrInfo'])) {
  1739. $_info[$k]['cart_info']['productInfo']['image'] = $_info[$k]['cart_info']['productInfo']['attrInfo']['image'];
  1740. $_info[$k]['cart_info']['productInfo']['price'] = $_info[$k]['cart_info']['productInfo']['attrInfo']['price'];
  1741. $_info[$k]['cart_info']['productInfo']['suk'] = $_info[$k]['cart_info']['productInfo']['attrInfo']['suk'];
  1742. unset($_info[$k]['cart_info']['productInfo']['attrInfo']);
  1743. }
  1744. if (!isset($v['cart_info']['productInfo']['ot_price'])) {
  1745. $_info[$k]['cart_info']['productInfo']['ot_price'] = $v['cart_info']['productInfo']['price'];
  1746. }
  1747. }
  1748. $item['_info'] = $_info;
  1749. // if($item['pink_id'] || $item['combination_id']){
  1750. // $pinkStatus = StorePink::where('order_id_key',$item['id'])->value('status');
  1751. // switch ($pinkStatus){
  1752. // case 1:
  1753. // $item['pink_name'] = '[拼团订单]正在进行中';
  1754. // $item['color'] = '#f00';
  1755. // break;
  1756. // case 2:
  1757. // $item['pink_name'] = '[拼团订单]已完成';
  1758. // $item['color'] = '#00f';
  1759. // break;
  1760. // case 3:
  1761. // $item['pink_name'] = '[拼团订单]未完成';
  1762. // $item['color'] = '#f0f';
  1763. // break;
  1764. // default:
  1765. // $item['pink_name'] = '[拼团订单]历史订单';
  1766. // $item['color'] = '#457856';
  1767. // break;
  1768. // }
  1769. // }elseif ($item['seckill_id']){
  1770. // $item['pink_name'] = '[秒杀订单]';
  1771. // $item['color'] = '#32c5e9';
  1772. // }elseif ($item['bargain_id']){
  1773. // $item['pink_name'] = '[砍价订单]';
  1774. // $item['color'] = '#12c5e9';
  1775. // }else{
  1776. // $item['pink_name'] = '[普通订单]';
  1777. // $item['color'] = '#895612';
  1778. // }
  1779. // if($item['paid']==1){
  1780. // switch ($item['pay_type']){
  1781. // case 'weixin':
  1782. // $item['pay_type_name']='微信支付';
  1783. // break;
  1784. // case 'yue':
  1785. // $item['pay_type_name']='余额支付';
  1786. // break;
  1787. // case 'offline':
  1788. // $item['pay_type_name']='线下支付';
  1789. // break;
  1790. // default:
  1791. // $item['pay_type_name']='其他支付';
  1792. // break;
  1793. // }
  1794. // }else{
  1795. // switch ($item['pay_type']){
  1796. // default:
  1797. // $item['pay_type_name']='未支付';
  1798. // break;
  1799. // case 'offline':
  1800. // $item['pay_type_name']='线下支付';
  1801. // $item['pay_type_info']=1;
  1802. // break;
  1803. // }
  1804. // }
  1805. if ($status) {
  1806. $status = [];
  1807. if (!$item['paid'] && $item['pay_type'] == 'offline' && !$item['status'] >= 2) {
  1808. $status['_type'] = 9;
  1809. $status['_title'] = '线下付款';
  1810. $status['_msg'] = '商家处理中,请耐心等待';
  1811. $status['_class'] = 'nobuy';
  1812. } else if (!$item['paid']) {
  1813. $status['_type'] = 0;
  1814. $status['_title'] = '未支付';
  1815. //系统预设取消订单时间段
  1816. $keyValue = ['order_cancel_time', 'order_activity_time', 'order_bargain_time', 'order_seckill_time', 'order_pink_time'];
  1817. //获取配置
  1818. $systemValue = SystemConfigService::more($keyValue);
  1819. //格式化数据
  1820. $systemValue = self::setValeTime($keyValue, is_array($systemValue) ? $systemValue : []);
  1821. if ($item['pink_id'] || $item['combination_id']) {
  1822. $order_pink_time = $systemValue['order_pink_time'] ? $systemValue['order_pink_time'] : $systemValue['order_activity_time'];
  1823. $time = bcadd(strtotime($item['add_time']), $order_pink_time * 3600, 0);
  1824. $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
  1825. } else if ($item['seckill_id']) {
  1826. $order_seckill_time = $systemValue['order_seckill_time'] ? $systemValue['order_seckill_time'] : $systemValue['order_activity_time'];
  1827. $time = bcadd(strtotime($item['add_time']), $order_seckill_time * 3600, 0);
  1828. $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
  1829. } else if ($item['bargain_id']) {
  1830. $order_bargain_time = $systemValue['order_bargain_time'] ? $systemValue['order_bargain_time'] : $systemValue['order_activity_time'];
  1831. $time = bcadd(strtotime($item['add_time']), $order_bargain_time * 3600, 0);
  1832. $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
  1833. } else {
  1834. $time = bcadd(strtotime($item['add_time']), $systemValue['order_cancel_time'] * 3600, 0);
  1835. $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
  1836. }
  1837. $status['_class'] = 'nobuy';
  1838. } else if ($item['refund_status'] == 1) {
  1839. $status['_type'] = -1;
  1840. $status['_title'] = '申请退款中';
  1841. $status['_msg'] = '商家审核中,请耐心等待';
  1842. $status['_class'] = 'state-sqtk';
  1843. } else if ($item['refund_status'] == 2) {
  1844. $status['_type'] = -2;
  1845. $status['_title'] = '已退款';
  1846. $status['_msg'] = '已为您退款,感谢您的支持';
  1847. $status['_class'] = 'state-sqtk';
  1848. } else if (!$item['status']) {
  1849. if ($item['pink_id']) {
  1850. if (StorePink::where('id', $item['pink_id'])->where('status', 1)->count()) {
  1851. $status['_type'] = 11;
  1852. $status['_title'] = '拼团中';
  1853. $status['_msg'] = '等待其他人参加拼团';
  1854. $status['_class'] = 'state-nfh';
  1855. } else {
  1856. $status['_type'] = 1;
  1857. $status['_title'] = '未发货';
  1858. $status['_msg'] = '商家未发货,请耐心等待';
  1859. $status['_class'] = 'state-nfh';
  1860. }
  1861. } else {
  1862. $status['_type'] = 1;
  1863. $status['_title'] = '未发货';
  1864. $status['_msg'] = '商家未发货,请耐心等待';
  1865. $status['_class'] = 'state-nfh';
  1866. }
  1867. } else if ($item['status'] == 1) {
  1868. if ($item['delivery_type'] == 'send') {//TODO 送货
  1869. $status['_type'] = 2;
  1870. $status['_title'] = '待收货';
  1871. $status['_msg'] = date('m月d日H时i分', StoreOrderStatus::getTime($item['id'], 'delivery')) . '服务商已送货';
  1872. $status['_class'] = 'state-ysh';
  1873. } else {//TODO 发货
  1874. $status['_type'] = 2;
  1875. $status['_title'] = '待收货';
  1876. $status['_msg'] = date('m月d日H时i分', StoreOrderStatus::getTime($item['id'], 'delivery_goods')) . '服务商已发货';
  1877. $status['_class'] = 'state-ysh';
  1878. }
  1879. } else if ($item['status'] == 2) {
  1880. $status['_type'] = 3;
  1881. $status['_title'] = '待评价';
  1882. $status['_msg'] = '已收货,快去评价一下吧';
  1883. $status['_class'] = 'state-ypj';
  1884. } else if ($item['status'] == 3) {
  1885. $status['_type'] = 4;
  1886. $status['_title'] = '交易完成';
  1887. $status['_msg'] = '交易完成,感谢您的支持';
  1888. $status['_class'] = 'state-ytk';
  1889. }
  1890. if (isset($item['pay_type']))
  1891. $status['_payType'] = isset(self::$payType[$item['pay_type']]) ? self::$payType[$item['pay_type']] : '其他方式';
  1892. if (isset($item['delivery_type']))
  1893. $status['_deliveryType'] = isset(self::$deliveryType[$item['delivery_type']]) ? self::$deliveryType[$item['delivery_type']] : '其他方式';
  1894. $item['_status'] = $status;
  1895. } else {
  1896. if ($item['paid'] == 0 && $item['status'] == 0) {
  1897. $item['status_name'] = '未支付';
  1898. } else if ($item['paid'] == 1 && $item['status'] == 0 && $item['refund_status'] == 0) {
  1899. $item['status_name'] = '未发货';
  1900. } else if ($item['paid'] == 1 && $item['status'] == 1 && $item['refund_status'] == 0) {
  1901. $item['status_name'] = '待收货';
  1902. } else if ($item['paid'] == 1 && $item['status'] == 2 && $item['refund_status'] == 0) {
  1903. $item['status_name'] = '待评价';
  1904. } else if ($item['paid'] == 1 && $item['status'] == 3 && $item['refund_status'] == 0) {
  1905. $item['status_name'] = '已完成';
  1906. }
  1907. }
  1908. // unset($item['refund_status']);
  1909. // else if($item['paid']==1 && $item['refund_status']==1){
  1910. // $item['status_name']=<<<HTML
  1911. //<b style="color:#f124c7">申请退款</b><br/>
  1912. //<span>退款原因:{$item['refund_reason_wap']}</span>
  1913. //HTML;
  1914. // }else if($item['paid']==1 && $item['refund_status']==2){
  1915. // $item['status_name']='已退款';
  1916. // }
  1917. // if($item['paid']==0 && $item['status']==0 && $item['refund_status']==0){
  1918. // $item['_status']=1;
  1919. // }else if($item['paid']==1 && $item['status']==0 && $item['refund_status']==0){
  1920. // $item['_status']=2;
  1921. // }else if($item['paid']==1 && $item['refund_status']==1){
  1922. // $item['_status']=3;
  1923. // }else if($item['paid']==1 && $item['status']==1 && $item['refund_status']==0){
  1924. // $item['_status']=4;
  1925. // }else if($item['paid']==1 && $item['status']==2 && $item['refund_status']==0){
  1926. // $item['_status']=5;
  1927. // }else if($item['paid']==1 && $item['status']==3 && $item['refund_status']==0){
  1928. // $item['_status']=6;
  1929. // }else if($item['paid']==1 && $item['refund_status']==2){
  1930. // $item['_status']=7;
  1931. // }
  1932. }
  1933. return $data;
  1934. }
  1935. /**
  1936. * 处理where条件
  1937. * @param $where
  1938. * @param $model
  1939. * @param string $aler
  1940. * @param string $join
  1941. * @return StoreOrder|null
  1942. */
  1943. public static function getOrderWhere($where, $model, $aler = '', $join = '')
  1944. {
  1945. if (isset($where['status']) && $where['status'] != '') $model = self::statusWhere($where['status'], $model, $aler);
  1946. if (isset($where['is_del']) && $where['is_del'] != '' && $where['is_del'] != -1) $model = $model->where($aler . 'is_del', $where['is_del']);
  1947. if (isset($where['combination_id'])) {
  1948. if ($where['combination_id'] == '普通订单') {
  1949. $model = $model->where($aler . 'combination_id', 0)->where($aler . 'seckill_id', 0)->where($aler . 'bargain_id', 0);
  1950. }
  1951. if ($where['combination_id'] == '拼团订单') {
  1952. $model = $model->where($aler . 'combination_id', ">", 0)->where($aler . 'pink_id', ">", 0);
  1953. }
  1954. if ($where['combination_id'] == '秒杀订单') {
  1955. $model = $model->where($aler . 'seckill_id', ">", 0);
  1956. }
  1957. if ($where['combination_id'] == '砍价订单') {
  1958. $model = $model->where($aler . 'bargain_id', ">", 0);
  1959. }
  1960. }
  1961. if (isset($where['type'])) {
  1962. switch ($where['type']) {
  1963. case 1:
  1964. $model = $model->where($aler . 'combination_id', 0)->where($aler . 'seckill_id', 0)->where($aler . 'bargain_id', 0);
  1965. break;
  1966. case 2:
  1967. $model = $model->where($aler . 'combination_id', ">", 0);
  1968. break;
  1969. case 3:
  1970. $model = $model->where($aler . 'seckill_id', ">", 0);
  1971. break;
  1972. case 4:
  1973. $model = $model->where($aler . 'bargain_id', ">", 0);
  1974. break;
  1975. }
  1976. }
  1977. if (isset($where['real_name']) && $where['real_name'] != '')
  1978. $model = $model->where($aler . 'order_id|' . $aler . 'real_name|' . $aler . 'user_phone' . ($join ? '|' . $join . '.nickname|' . $join . '.uid' : ''), 'LIKE', "%$where[real_name]%");
  1979. if (isset($where['store_id']) && $where['store_id'] > 0) {
  1980. $model = $model->where($aler . 'store_id', "=", $where['store_id']);
  1981. }
  1982. if (isset($where['data']) && $where['data'] !== '') {
  1983. list($startTime, $endTime) = explode(' - ', $where['data']);
  1984. $model = $model->where($aler . 'add_time', '>', $startTime);
  1985. $model = $model->where($aler . 'add_time', '<', date("Y-m-d H:i:s", bcadd(strtotime($endTime), 86400, 0)));
  1986. }
  1987. return $model;
  1988. }
  1989. /**
  1990. * 设置where条件
  1991. * @param $status
  1992. * @param null $model
  1993. * @param string $alert
  1994. * @return StoreOrder|null
  1995. */
  1996. public static function statusWhere($status, $model = null, $alert = '')
  1997. {
  1998. if ($model == null) $model = new self;
  1999. if ('' === $status)
  2000. return $model;
  2001. else if ($status == 0)//未支付
  2002. return $model->where($alert . 'paid', 0)->where($alert . 'status', 0)->where($alert . 'refund_status', 0);
  2003. else if ($status == 1)//已支付 未发货
  2004. return $model->where($alert . 'paid', 1)->where($alert . 'status', 0)->where($alert . 'refund_status', 0);
  2005. else if ($status == 2)//已支付 待收货
  2006. return $model->where($alert . 'paid', 1)->where($alert . 'status', 1)->where($alert . 'refund_status', 0);
  2007. else if ($status == 3)// 已支付 已收货 待评价
  2008. return $model->where($alert . 'paid', 1)->where($alert . 'status', 2)->where($alert . 'refund_status', 0);
  2009. else if ($status == 4)// 交易完成
  2010. return $model->where($alert . 'paid', 1)->where($alert . 'status', 3)->where($alert . 'refund_status', 0);
  2011. else if ($status == -1)//退款中
  2012. return $model->where($alert . 'paid', 1)->where($alert . 'refund_status', 1);
  2013. else if ($status == -2)//已退款
  2014. return $model->where($alert . 'paid', 1)->where($alert . 'refund_status', 2);
  2015. else if ($status == -3)//退款
  2016. return $model->where($alert . 'paid', 1)->where($alert . 'refund_status', 'in', '1,2');
  2017. else
  2018. return $model;
  2019. }
  2020. /**
  2021. * 订单详情 管理员
  2022. * @param $orderId
  2023. * @param string $field
  2024. * @return array|null|\think\Model
  2025. * @throws \think\db\exception\DataNotFoundException
  2026. * @throws \think\db\exception\ModelNotFoundException
  2027. * @throws \think\exception\DbException
  2028. */
  2029. public static function getAdminOrderDetail($orderId, $field = '*')
  2030. {
  2031. return self::where('order_id', $orderId)->field($field)->find();
  2032. }
  2033. /**
  2034. * 获取指定时间区间的支付金额 管理员
  2035. * @param $start
  2036. * @param $stop
  2037. * @return float
  2038. */
  2039. public static function getOrderTimeBusinessVolumePrice($start, $stop)
  2040. {
  2041. return self::where('is_del', 0)->where('paid', 1)->where('refund_status', 0)->where('add_time', '>=', date("Y-m-d H:i:s", $start))->where('add_time', '<', date("Y-m-d H:i:s", $stop))->sum('pay_price');
  2042. }
  2043. /**
  2044. * 获取指定时间区间的支付订单数量 管理员
  2045. * @param $start
  2046. * @param $stop
  2047. * @return float
  2048. */
  2049. public static function getOrderTimeBusinessVolumeNumber($start, $stop)
  2050. {
  2051. return self::where('is_del', 0)->where('paid', 1)->where('refund_status', 0)->where('add_time', '>=', date("Y-m-d H:i:s", $start))->where('add_time', '<', date("Y-m-d H:i:s", $stop))->count();
  2052. }
  2053. /**
  2054. * 获取当前时间到指定时间的支付金额 管理员
  2055. * @param $start 开始时间
  2056. * @param $stop 结束时间
  2057. * @return mixed
  2058. */
  2059. public static function chartTimePrice($start, $stop)
  2060. {
  2061. $model = new self;
  2062. $model = $model->field('sum(pay_price) as num,FROM_UNIXTIME(add_time, \'%Y-%m-%d\') as time');
  2063. $model = $model->where('is_del', 0);
  2064. $model = $model->where('paid', 1);
  2065. $model = $model->where('refund_status', 0);
  2066. $model = $model->where('add_time', '>=', $start);
  2067. $model = $model->where('add_time', '<', $stop);
  2068. $model = $model->group("TO_DAYS(add_time, '%Y-%m-%d')");
  2069. $model = $model->order('add_time ASC');
  2070. return $model->select();
  2071. }
  2072. /**
  2073. * 获取当前时间到指定时间的支付订单数 管理员
  2074. * @param $start 开始时间
  2075. * @param $stop 结束时间
  2076. * @return mixed
  2077. */
  2078. public static function chartTimeNumber($start, $stop)
  2079. {
  2080. $model = new self;
  2081. $model = $model->field('count(id) as num,FROM_UNIXTIME(add_time, \'%Y-%m-%d\') as time');
  2082. $model = $model->where('is_del', 0);
  2083. $model = $model->where('paid', 1);
  2084. $model = $model->where('refund_status', 0);
  2085. $model = $model->where('add_time', '>=', date("Y-m-d H:i:s", $start));
  2086. $model = $model->where('add_time', '<', date("Y-m-d H:i:s", $stop));
  2087. $model = $model->group("TO_DAYS(add_time, '%Y-%m-%d')");
  2088. $model = $model->order('add_time ASC');
  2089. return $model->select();
  2090. }
  2091. /**
  2092. * 修改支付方式为线下支付
  2093. * @param $orderId
  2094. * @return bool
  2095. */
  2096. public static function setOrderTypePayOffline($orderId)
  2097. {
  2098. return self::edit(['pay_type' => 'offline'], $orderId, 'order_id');
  2099. }
  2100. /**
  2101. * 线下付款
  2102. * @param $id
  2103. * @return $this
  2104. */
  2105. public static function updateOffline($id)
  2106. {
  2107. $count = self::where('id', $id)->count();
  2108. if (!$count) return self::setErrorInfo('订单不存在');
  2109. $count = self::where('id', $id)->where('paid', 0)->count();
  2110. if (!$count) return self::setErrorInfo('订单已支付');
  2111. $res = self::where('id', $id)->update(['paid' => 1, 'pay_time' => time()]);
  2112. return $res;
  2113. }
  2114. /**
  2115. * 处理订单
  2116. * @param $order
  2117. * @throws \think\db\exception\DataNotFoundException
  2118. * @throws \think\db\exception\DbException
  2119. * @throws \think\db\exception\ModelNotFoundException
  2120. * @throws \think\exception\DbException
  2121. */
  2122. public static function handle_order($order)
  2123. {
  2124. //会员升级
  2125. $newsum = StoreOrderCartInfo::getProductcount($order['id']);
  2126. $cartlist = StoreOrderCartInfo::getProductList($order['id']);
  2127. $user = User::where('uid', $order['uid'])->field('uid,nickname,level,spread_uid')->find();
  2128. $spreaduser = User::where('uid', $order['uid'])->field('uid,nickname,level,spread_uid')->find();
  2129. $upgrade = 0;
  2130. $code_stock_right = 0;
  2131. foreach ($cartlist as $v) {
  2132. if (isset($v['attrInfo']['upgrade'])) {
  2133. $upgrade = bcsub($v['attrInfo']['upgrade'], $upgrade) > 0 ? $v['attrInfo']['upgrade'] : $upgrade;
  2134. }
  2135. if (isset($v['attrInfo']['upgrade'])) {
  2136. $code_stock_right += intval($v['attrInfo']['stock_right']);
  2137. }
  2138. }
  2139. $level = User::where('uid', $order['uid'])->value('level');
  2140. if ($upgrade > $level) {
  2141. UserLevel::setUserLevel($order['uid'], $upgrade);
  2142. if ($upgrade == 6) {
  2143. UserCode::add_code($order['uid'], $cartlist, $newsum);
  2144. if (intval($spreaduser['level']) == 6 || User::where('spread_uid', $spreaduser['uid'])->where('level', 6)->count() > 1) {
  2145. $spreaduser->where('uid', $spreaduser['uid'])->inc('brokerage_price', sys_config('code_recommend', 60000))->update();
  2146. $str = sprintf("推荐%s用户升级为总代,获得推荐奖:%d", $user['nickname'], sys_config('code_recommend', 60000));
  2147. UserBill::income('总代推荐奖', $spreaduser['uid'], 'now_money', 'brokerage', sys_config('code_recommend', 60000), $order['id'], bcadd($spreaduser['brokerage_price'], sys_config('code_recommend', 60000), 0), $str, 1);
  2148. }
  2149. } elseif ($upgrade == 5) {
  2150. User::where('uid', $v['uid'])->setField('give_stock_right', 20);
  2151. }
  2152. }
  2153. //处理团队单数
  2154. User::where('uid', $user['uid'])->inc('team_cts', $newsum);
  2155. User::where('uid', $spreaduser['uid'])->inc('team_cts', $newsum);
  2156. UserLevel::setLevelComplete($spreaduser['uid']);
  2157. if (intval($spreaduser['level']) == 5 && intval($spreaduser['give_stock_right']) == 0) {
  2158. User::where('uid', $spreaduser['uid'])->setField('give_stock_right', 10);
  2159. }
  2160. //处理极差
  2161. $users = User::field('uid,level,spread_uid')->select();
  2162. $rs = UtilService::getparentid($users, $spreaduser['uid']);
  2163. $levels = SystemUserLevel::where('is_del', 0)->where('is_show', 1)->field('id,name,range_award')->select();
  2164. $levela = [];
  2165. $current_level = $spreaduser['level'];
  2166. $system_range = sys_config('system_range');
  2167. $range_award = 0;
  2168. foreach ($levels as $v) {
  2169. $levela[$v['id']]['bl'] = bcsub($v['id'], $spreaduser['level'], 0) < 0 ? true : false;
  2170. $levela[$v['id']]['sbl'] = true;
  2171. $levela[$v['id']]['s_range'] = sys_config('PeerAward', 1);
  2172. $levela[$v['id']]['range_award'] = $v['range_award'];
  2173. $levela[$v['id']]['use'] = 0;
  2174. $levela[$v['id']]['team_cts'] = 0;
  2175. }
  2176. foreach ($rs as $v) {
  2177. if ($v['level'] >= $current_level) {
  2178. //处理第一次
  2179. if ($levela[$v['level']]['use'] == 0) {
  2180. $level_award = $range_award == 0 ? $levela[$v['level']]['range_award'] : bcsub($levela[$v['level']]['range_award'], $range_award, 0);
  2181. $levela[$v['level']]['use'] = 1;
  2182. $levela[$v['id']]['team_cts'] = $v['team_cts'];
  2183. $range_award = $levela[$v['level']]['range_award'];
  2184. } else {
  2185. if ($levela[$v['id']]['sbl'] && bcsub($levela[$v['id']]['team_cts'], $v['team_cts'])) {
  2186. $level_award = $levela[$v['level']]['s_range'];
  2187. $levela[$v['id']]['sbl'] = false;
  2188. $range_award = bcadd($range_award, $level_award, 0);
  2189. }
  2190. }
  2191. if ($v['level'] > $current_level) {
  2192. $current_level = $v['level'];
  2193. } else {
  2194. if ($v['level'] == $current_level && $levela[$v['id']]['sbl'] == 1) {
  2195. $current_level++;
  2196. }
  2197. }
  2198. $proportion = bcmul(bcsub($order['total_price'], $order['cost'], 2), bcdiv($level_award, 100, 2), 2);
  2199. $mark = "订单号" . $order['order_id'] . '产生津贴绿积分,奖励推广佣金' . $proportion;
  2200. //TODO 添加推广记录
  2201. $res1 = UserBill::income('津贴绿积分', $v['uid'], 'now_money', 'brokerage', $proportion, $order['id'], $proportion, $mark);
  2202. //TODO 添加用户余额
  2203. $res2 = User::where('uid', $v['uid'])->inc('brokerage', $proportion)->update();
  2204. }
  2205. }
  2206. }
  2207. /**
  2208. * 向创建订单10分钟未付款的用户发送短信
  2209. */
  2210. public static function sendTen()
  2211. {
  2212. $switch = sys_config('unpaid_order_switch') ? true : false;
  2213. if ($switch) {
  2214. $list = self::where('paid', 0)
  2215. ->where('is_del', 0)
  2216. ->where('is_system_del', 0)
  2217. ->where('add_time', 'exp', 'DATE_SUB()')
  2218. ->where('add_time', '<', time() - 600)
  2219. ->field('order_id,user_phone')
  2220. ->select();
  2221. if ($list) {
  2222. $list = $list->toArray();
  2223. foreach ($list as $phone) {
  2224. ShortLetterRepositories::send(true, $phone['user_phone'], ['order_id' => $phone['order_id']], 'ORDER_PAY_FALSE');
  2225. }
  2226. }
  2227. }
  2228. }
  2229. public function productInfo()
  2230. {
  2231. return $this->hasMany(StoreProductReply::class, 'oid', 'id');
  2232. }
  2233. public static function setOrderProductReplyWhere($where)
  2234. {
  2235. $model = self::where('status', 3)->order('add_time desc')->whereIn('id', function ($query) {
  2236. $query->name('store_order')->alias('o')->join('store_product_reply a', 'a.oid = o.id')->group('o.id')->field('o.id')->select();
  2237. })->with('productInfo', function ($query) use ($where) {
  2238. $alias = '';
  2239. if (isset($where['title']) && $where['title'] != '')
  2240. $query->where("{$alias}comment", 'LIKE', "%$where[title]%");
  2241. if (isset($where['is_reply']) && $where['is_reply'] != '') {
  2242. if ($where['is_reply'] >= 0) {
  2243. $query->where("{$alias}is_reply", $where['is_reply']);
  2244. } else {
  2245. $query->where("{$alias}is_reply", '>', 0);
  2246. }
  2247. }
  2248. if (isset($where['producr_id']) && $where['producr_id'] != 0)
  2249. $query->where($alias . 'product_id', $where['producr_id']);
  2250. $query->where("{$alias}is_del", 0);
  2251. });
  2252. return $model;
  2253. }
  2254. public static function getOrderProductReplyList($where)
  2255. {
  2256. $list = self::setOrderProductReplyWhere($where)->page((int)$where['message_page'], (int)$where['limit'])->select();
  2257. $list = count($list) ? $list->toArray() : [];
  2258. foreach ($list as $key => $item) {
  2259. if (isset($item['productInfo']) && is_array($item['productInfo']) && count($item['productInfo'])) {
  2260. foreach ($item['productInfo'] as $k => $v) {
  2261. if (!$v['nickname'] && $v['uid']) {
  2262. $v['nickname'] = User::where('uid', $v['uid'])->value('nickname');
  2263. $v['avatar'] = User::where('uid', $v['uid'])->value('avatar');
  2264. }
  2265. $v['image'] = '';
  2266. $v['store_name'] = '';
  2267. if ($v['product_id']) {
  2268. $product = StoreProduct::where('id', $v['product_id'])->field(['image', 'store_name'])->find();
  2269. if ($product) {
  2270. $v['image'] = $product['image'];
  2271. $v['store_name'] = $product['store_name'];
  2272. }
  2273. }
  2274. $list[$key]['productInfo'][$k] = $v;
  2275. }
  2276. }
  2277. }
  2278. $count = self::setOrderProductReplyWhere($where)->count();
  2279. return compact('list', 'count');
  2280. }
  2281. /**
  2282. * 验证加入购物车、生成订单时商品得库存以及是否能购买情况
  2283. * @param $uid
  2284. * @param $product_id
  2285. * @param int $cart_num
  2286. * @param string $product_attr_unique
  2287. * @param int $combination_id
  2288. * @param int $seckill_id
  2289. * @param int $bargain_id
  2290. * @return bool
  2291. * @throws \think\db\exception\DataNotFoundException
  2292. * @throws \think\db\exception\DbException
  2293. * @throws \think\db\exception\ModelNotFoundException
  2294. */
  2295. public static function checkProductStock($uid, $product_id, $cart_num = 1, $product_attr_unique = '', $combination_id = 0, $seckill_id = 0, $bargain_id = 0)
  2296. {
  2297. if ($cart_num < 1) $cart_num = 1;
  2298. if (!$product_attr_unique) return self::setErrorInfo('请选择商品属性');
  2299. if ($seckill_id) {
  2300. if (!StoreSeckill::isSeckillEnd($seckill_id))
  2301. return self::setErrorInfo('活动已结束');
  2302. $StoreSeckillinfo = StoreSeckill::getValidProduct($seckill_id);
  2303. if (!$StoreSeckillinfo)
  2304. return self::setErrorInfo('该产品已下架或删除');
  2305. $userbuycount = StoreOrder::where('uid', $uid)->where('paid', 1)->where('seckill_id', $seckill_id)->sum('total_num');
  2306. if ($StoreSeckillinfo['num'] <= $userbuycount || $StoreSeckillinfo['num'] < $cart_num)
  2307. return self::setErrorInfo('每人限购' . $StoreSeckillinfo['num'] . '件');
  2308. $res = StoreProductAttrValue::where('product_id', $seckill_id)->where('unique', $product_attr_unique)->where('type', 1)->field('suk,quota')->find();
  2309. if ($cart_num > $res['quota'])
  2310. return self::setErrorInfo('该产品库存不足' . $cart_num);
  2311. $product_stock = StoreProductAttrValue::where('product_id', $StoreSeckillinfo['product_id'])->where('suk', $res['suk'])->where('type', 0)->value('stock');
  2312. if ($product_stock < $cart_num)
  2313. return self::setErrorInfo('该产品库存不足' . $cart_num);
  2314. } elseif ($bargain_id) {
  2315. if (!StoreBargain::validBargain($bargain_id))
  2316. return self::setErrorInfo('该产品已下架或删除');
  2317. $StoreBargainInfo = StoreBargain::getBargain($bargain_id);
  2318. $res = StoreProductAttrValue::where('product_id', $bargain_id)->where('type', 2)->field('suk,quota')->find();
  2319. if ($cart_num > $res['quota'])
  2320. return self::setErrorInfo('该产品库存不足' . $cart_num);
  2321. $product_stock = StoreProductAttrValue::where('product_id', $StoreBargainInfo['product_id'])->where('suk', $res['suk'])->where('type', 0)->value('stock');
  2322. if ($product_stock < $cart_num)
  2323. return self::setErrorInfo('该产品库存不足' . $cart_num);
  2324. } elseif ($combination_id) {//拼团
  2325. $StoreCombinationInfo = StoreCombination::getCombinationOne($combination_id);
  2326. if (!$StoreCombinationInfo)
  2327. return self::setErrorInfo('该产品已下架或删除');
  2328. $userbuycount = StoreOrder::where('uid', $uid)->where('paid', 1)->where('combination_id', $combination_id)->count();
  2329. if ($StoreCombinationInfo['num'] <= $userbuycount || $StoreCombinationInfo['num'] < $cart_num)
  2330. return self::setErrorInfo('每人限购' . $StoreCombinationInfo['num'] . '件');
  2331. $res = StoreProductAttrValue::where('product_id', $combination_id)->where('unique', $product_attr_unique)->where('type', 3)->field('suk,quota')->find();
  2332. if ($cart_num > $res['quota'])
  2333. return self::setErrorInfo('该产品库存不足' . $cart_num);
  2334. $product_stock = StoreProductAttrValue::where('product_id', $StoreCombinationInfo['product_id'])->where('suk', $res['suk'])->where('type', 0)->value('stock');
  2335. if ($product_stock < $cart_num)
  2336. return self::setErrorInfo('该产品库存不足' . $cart_num);
  2337. } else {
  2338. if (!StoreProduct::isValidProduct($product_id))
  2339. return self::setErrorInfo('该产品已下架或删除');
  2340. if (!StoreProductAttr::issetProductUnique($product_id, $product_attr_unique))
  2341. return self::setErrorInfo('请选择有效的产品属性');
  2342. if (StoreProduct::getProductStock($product_id, $product_attr_unique) < $cart_num)
  2343. return self::setErrorInfo('该产品库存不足' . $cart_num);
  2344. }
  2345. return true;
  2346. }
  2347. public static function do_jialie()
  2348. {
  2349. $rs = self::where('paid', 0)->where('jialie_do', 1)->where('jialie_count', '<', 31)->select()->toArray();
  2350. try {
  2351. foreach ($rs as $v) {
  2352. self::edit(['jialie_do' => 2], $v['id']);
  2353. if (empty($v['re_order_id'])) {
  2354. $res = JiaLieService::initialize()::paymentquery(JiaLieService::QUERY, ['out_trade_no' => $v['order_id'], 'nonce_str' => uniqid() . mt_rand(1000, 9999)]);
  2355. } else {
  2356. $res = JiaLieService::initialize()::paymentquery(JiaLieService::QUERY, ['out_trade_no' => $v['re_order_id'], 'nonce_str' => uniqid() . mt_rand(1000, 9999)]);
  2357. }
  2358. if ($res['ret_code'] == 0 && $res['status'] == 2) {
  2359. self::paySuccess($v['order_id'], 'jialie');
  2360. self::edit(['jialie_do' => 0, 'is_del' => 0, 'status' => 2], $v['id']);
  2361. OrderRepository::storeProductOrderTakeDeliveryAdmin($v);
  2362. StoreOrderStatus::status($v['id'], 'take_delivery', '已核销');
  2363. } else {
  2364. self::where('id', $v['id'])->inc('jialie_count', 1)->update();
  2365. self::edit(['jialie_do' => 1], $v['id']);
  2366. }
  2367. }
  2368. } catch (Exception $e) {
  2369. @file_put_contents("jialie.txt", $e->getLine() . '--' . $e->getMessage() . "-end\r\n", 8);
  2370. }
  2371. return true;
  2372. }
  2373. public static function sendGroupAward($order): bool
  2374. {
  2375. // return true;
  2376. //TODO 营销产品不返佣金
  2377. if (isset($order['combination_id']) && $order['combination_id']) return true;
  2378. if (isset($order['seckill_id']) && $order['seckill_id']) return true;
  2379. if (isset($order['bargain_id']) && $order['bargain_id']) return true;
  2380. $userInfo = User::getUserInfo($order['uid']);
  2381. $spread = User::getUserInfo($userInfo['spread_uid']);
  2382. // if (StoreOrder::where('uid', $order['uid'])->where('paid', 1)->where('refund_status', 0)->where('is_del', 0)->where('is_system_del', 0)
  2383. // ->where('id', '<>', $order['id'])->where('suit', '>', 0)->find()) {
  2384. // $spread = $userInfo;
  2385. // }
  2386. $cartInfo = StoreOrderCartInfo::whereIn('cart_id', $order['cart_id'])->column('cart_info');
  2387. $suit = 0;
  2388. $suit_exit = 0;
  2389. $suit_award = 0;
  2390. $suit_price = 0;
  2391. $extra_price = 0;
  2392. $calculator_ratio = sys_config('calculator_ratio', 80);
  2393. foreach ($cartInfo as $value) {
  2394. $product = json_decode($value, true);
  2395. if (isset($product['productInfo'])) {
  2396. $productInfo = $product['productInfo'];
  2397. if (($productInfo['attrInfo']['brokerage_suit'] ?? 0) > 0) {
  2398. $suit_award += $product['productInfo']['attrInfo']['brokerage_suit'] * $product['cart_num'];
  2399. $suit_price += bcsub(($productInfo['attrInfo']['price'] ?? $product['price']), ($productInfo['attrInfo']['cost'] ?? $product['cost']), 2) * $product['cart_num'];
  2400. $suit_price = bcdiv(bcmul($suit_price, $calculator_ratio), 100, 2);
  2401. if ($product['is_suit']) $suit_exit += $product['cart_num'] ?? 0;
  2402. }
  2403. if ($product['is_suit']) {
  2404. $suit += $product['cart_num'] ?? 0;
  2405. $suit_price += bcsub(($productInfo['attrInfo']['price'] ?? $product['price']), ($productInfo['attrInfo']['cost'] ?? $product['cost']), 2) * $product['cart_num'];
  2406. $suit_price = bcdiv(bcmul($suit_price, $calculator_ratio), 100, 2);
  2407. }
  2408. if (!$product['is_award']) {
  2409. $extra_price += bcsub(($productInfo['attrInfo']['price'] ?? $product['price']), ($productInfo['attrInfo']['cost'] ?? $product['cost']), 2) * $product['cart_num'];
  2410. $extra_price = bcdiv(bcmul($extra_price, $calculator_ratio), 100, 2);
  2411. }
  2412. }
  2413. }
  2414. $res = true;
  2415. $suit_recommend = sys_config('suit_recommend', 0, true);
  2416. if ($spread) {
  2417. //推荐奖
  2418. $brokeragePrice = bcmul($suit_recommend, $suit - $suit_exit, 2);
  2419. $brokeragePrice = bcadd($suit_award, $brokeragePrice, 2);
  2420. if ($brokeragePrice > 0) {
  2421. $mark = '用户' . $userInfo['nickname'] . '(' . $order['uid'] . ')' . '购买套装商品,获得推荐奖励' . $brokeragePrice;
  2422. $res = $res && UserBill::income('奖励积分', $spread['uid'], 'now_money', 'brokerage', $brokeragePrice, $order['id'], bcadd($spread['brokerage_price'], $brokeragePrice, 2), $mark);
  2423. $res = $res && User::where('uid', $spread['uid'])->inc('brokerage_price', $brokeragePrice)->update();
  2424. $spread['brokerage_price'] = bcadd($spread['brokerage_price'], $brokeragePrice, 2);
  2425. }
  2426. }
  2427. $send = 0;
  2428. $send_normal = 0;
  2429. $layer = 1;
  2430. $layer_award = sys_data('suit_sub_award');
  2431. $layer_award_real = [];
  2432. $company_award = false;
  2433. $operate_award = false;
  2434. foreach ($layer_award as $v) {
  2435. $layer_award_real[$v['layer']] = $v;
  2436. }
  2437. while ($spread) {
  2438. $group_level = SystemGroupLevel::get($spread['group_level']);
  2439. $award_level = SystemGroupLevel::get($spread['award_level']);
  2440. $balance = $spread['brokerage_price'];
  2441. if ($suit) {
  2442. $award_group = $group_level['suit_award'] ?? 0;
  2443. $award_award = $award_level['suit_award'] ?? 0;
  2444. $big = $award_group > $award_award ? $group_level['id'] : $award_level['id'];
  2445. $brokeragePrice_a = bcmul($award_award, $suit, 2);
  2446. $brokeragePrice_g = bcmul($award_group, $suit, 2);
  2447. $brokeragePrice_big = $brokeragePrice_a > $brokeragePrice_g ? $brokeragePrice_a : $brokeragePrice_g;
  2448. // $brokeragePrice_small = $brokeragePrice_a > $brokeragePrice_g ? $brokeragePrice_g : $brokeragePrice_a;
  2449. // if ($brokeragePrice_big == $brokeragePrice_small) {
  2450. $brokeragePrice = $brokeragePrice_big;
  2451. if ($brokeragePrice > $send) {
  2452. $real_send = bcsub($brokeragePrice, $send, 2);
  2453. if ($real_send > 0) {
  2454. $mark = '用户' . $userInfo['nickname'] . '(' . $order['uid'] . ')' . '购买套装商品,获得津贴绿积分' . $real_send;
  2455. $res = $res && UserBill::income('套装津贴绿积分', $spread['uid'], 'now_money', 'brokerage', $real_send, $order['id'], bcadd($balance, $real_send, 2), $mark);
  2456. $res = $res && User::where('uid', $spread['uid'])->inc('brokerage_price', $real_send)->update();
  2457. $balance = bcadd($balance, $real_send, 2);
  2458. $send = $brokeragePrice;
  2459. }
  2460. }
  2461. if (($group_level['company_award'] > 0 || $award_level['company_award'] > 0) && !$company_award) {
  2462. $ratio = ($group_level['company_award'] > $award_level['company_award'] ? $group_level['company_award'] : $award_level['company_award']);
  2463. $spread_up = User::where('uid', $spread['spread_uid'])->find();
  2464. $group_levels = SystemGroupLevel::where('company_award', '>', 0)->column('id');
  2465. $p_ratio = 0;
  2466. $award_levels = SystemAwardLevel::where('company_award', '>', 0)->column('id');
  2467. // @file_put_contents('order.txt', '【8.8】' . time() . PHP_EOL, FILE_APPEND);
  2468. while ($spread_up) {
  2469. if (in_array($spread_up['group_level'], $group_levels) || in_array($spread_up['award_level'], $award_levels)) {
  2470. $ratio -= 1;
  2471. $p_ratio = 1;
  2472. break;
  2473. }
  2474. $spread_up = User::where('uid', $spread_up['spread_uid'])->find();
  2475. }
  2476. // @file_put_contents('order.txt', '【8.9】' . time() . PHP_EOL, FILE_APPEND);
  2477. // $c = [];
  2478. // $p = [$spread['uid']];
  2479. // while ($p) {
  2480. // $child = User::where('spread_uid', 'in', $p)->where(function ($query) use ($group_levels, $award_levels) {
  2481. // if (count($group_levels) && count($award_levels)) {
  2482. // $query->where('group_level', 'in', $group_levels)
  2483. // ->whereOr('award_level', 'in', $award_levels);
  2484. // } else if (count($group_levels)) {
  2485. // $query->where('group_level', 'in', $group_levels);
  2486. // } else if (count($award_levels)) {
  2487. // $query->where('award_level', 'in', $award_levels);
  2488. // } else {
  2489. // $query->where('award_level', '100000000000');
  2490. // }
  2491. // })->column('uid');
  2492. // if (count($child)) {
  2493. // $c = array_merge($c, $child);
  2494. // }
  2495. // $p = User::where('spread_uid', 'in', $p)->where('uid', 'not in', $child)->column('uid');
  2496. // }
  2497. // $ratio += count(array_unique($c));
  2498. if ($ratio > 0) {
  2499. $op_award = bcmul($suit_price, bcdiv($ratio, 100, 4), 2);
  2500. if ($op_award > 0) {
  2501. $mark = '用户' . $userInfo['nickname'] . '(' . $order['uid'] . ')' . '购买套装商品,获得分公司奖奖励' . $op_award;
  2502. $res = $res && UserBill::income('分公司奖', $spread['uid'], 'now_money', 'brokerage', $op_award, $order['id'], bcadd($balance, $op_award, 2), $mark);
  2503. $res = $res && User::where('uid', $spread['uid'])->inc('brokerage_price', $op_award)->update();
  2504. $balance = bcadd($balance, $op_award, 2);
  2505. }
  2506. }
  2507. if ($p_ratio > 0) {
  2508. $op_award = bcmul($suit_price, bcdiv($p_ratio, 100, 4), 2);
  2509. if ($op_award > 0) {
  2510. $mark = '用户' . $userInfo['nickname'] . '(' . $order['uid'] . ')' . '购买套装商品,获得分公司奖奖励' . $op_award;
  2511. $res = $res && UserBill::income('分公司奖', $spread_up['uid'], 'now_money', 'brokerage', $op_award, $order['id'], bcadd($spread_up['brokerage_price'], $op_award, 2), $mark);
  2512. $res = $res && User::where('uid', $spread_up['uid'])->inc('brokerage_price', $op_award)->update();
  2513. }
  2514. }
  2515. $company_award = true;
  2516. }
  2517. if (($group_level['operate_award'] > 0 || $award_level['operate_award'] > 0) && !$operate_award) {
  2518. $ratio = ($group_level['operate_award'] > $award_level['operate_award'] ? $group_level['operate_award'] : $award_level['operate_award']);
  2519. if ($ratio > 0) {
  2520. $op_award = bcmul($suit_price, bcdiv($ratio, 100, 4), 2);
  2521. if ($op_award > 0) {
  2522. $mark = '用户' . $userInfo['nickname'] . '(' . $order['uid'] . ')' . '购买套装商品,获得运营公司奖励' . $op_award;
  2523. $res = $res && UserBill::income('运营公司奖', $spread['uid'], 'now_money', 'brokerage', $op_award, $order['id'], bcadd($balance, $op_award, 2), $mark);
  2524. $res = $res && User::where('uid', $spread['uid'])->inc('brokerage_price', $op_award)->update();
  2525. $balance = bcadd($balance, $op_award, 2);
  2526. }
  2527. }
  2528. $operate_award = true;
  2529. }
  2530. }
  2531. $lay_award = $layer_award_real[$layer] ?? null;
  2532. if ($lay_award) {
  2533. $sps = User::where('spread_uid', $spread['uid'])->column('uid');
  2534. $count = 0;
  2535. foreach ($sps as $vvv) {
  2536. if (StoreOrder::where('uid', $vvv)->where('paid', 1)->where('refund_status', 0)->where('is_del', 0)->where('is_system_del', 0)
  2537. ->where('suit', '>', 0)->find()) {
  2538. $count++;
  2539. }
  2540. }
  2541. if ($count >= $lay_award['recommend']
  2542. || StoreOrder::where('uid', $spread['uid'])
  2543. ->where('paid', 1)
  2544. ->where('refund_status', 0)
  2545. ->where('is_del', 0)
  2546. ->where('is_system_del', 0)
  2547. ->where('suit', '>', 0)
  2548. ->sum('suit') >= 25) {
  2549. if ($suit) {
  2550. $brokeragePrice = bcmul($lay_award['award'], $suit, 2);
  2551. if ($brokeragePrice > 0) {
  2552. $mark = '用户' . $userInfo['nickname'] . '(' . $order['uid'] . ')' . '购买套装商品,获得见点奖励' . $brokeragePrice;
  2553. $res = $res && UserBill::income('管理积分', $spread['uid'], 'now_money', 'brokerage', $brokeragePrice, $order['id'], bcadd($balance, $brokeragePrice, 2), $mark);
  2554. $res = $res && User::where('uid', $spread['uid'])->inc('brokerage_price', $brokeragePrice)->update();
  2555. $balance = bcadd($balance, $brokeragePrice, 2);
  2556. }
  2557. }
  2558. if ($order['use_integral'] > 0) {
  2559. $award_price_num = bcsub(bcsub(bcdiv(bcmul(bcsub($order['total_price'], $order['cost'], 2), $calculator_ratio), 100, 2), $suit_price, 2), $extra_price, 2);
  2560. $brokeragePrice = bcmul(bcdiv($lay_award['integral_award'], 100, 4), $award_price_num, 2);
  2561. if ($brokeragePrice > 0) {
  2562. $mark = '用户' . $userInfo['nickname'] . '(' . $order['uid'] . ')' . '购买积分商品,获得见点奖励' . $brokeragePrice;
  2563. $res = $res && UserBill::income('见点奖', $spread['uid'], 'now_money', 'brokerage', $brokeragePrice, $order['id'], bcadd($balance, $brokeragePrice, 2), $mark);
  2564. $res = $res && User::where('uid', $spread['uid'])->inc('brokerage_price', $brokeragePrice)->update();
  2565. $balance = bcadd($balance, $brokeragePrice, 2);
  2566. }
  2567. }
  2568. $layer++;
  2569. }
  2570. }
  2571. // if ($group_level) {
  2572. if (!$group_level) {
  2573. $group_award_basic = sys_config('group_award_basic', 0);
  2574. $integral_group_award_basic = sys_config('integral_group_award_basic', 0);
  2575. $award_price_num = bcsub(bcsub(bcdiv(bcmul(bcsub($order['total_price'], $order['cost'], 2), $calculator_ratio), 100, 2), $suit_price, 2), $extra_price, 2);
  2576. $brokeragePrice = bcmul(bcdiv($group_award_basic, 100, 4), $award_price_num, 2);
  2577. if ($order['use_integral'] > 0) $brokeragePrice = bcmul(bcdiv($integral_group_award_basic, 100, 4), bcsub(bcsub(bcsub($order['total_price'], $order['cost'], 2), $suit_price, 2), $extra_price, 2), 2);
  2578. } else {
  2579. $award_price_num = bcsub(bcsub(bcdiv(bcmul(bcsub($order['total_price'], $order['cost'], 2), $calculator_ratio), 100, 2), $suit_price, 2), $extra_price, 2);
  2580. $brokeragePrice = bcmul(bcdiv($group_level['group_award'], 100, 4), $award_price_num, 2);
  2581. if ($order['use_integral'] > 0) $brokeragePrice = bcmul(bcdiv($group_level['integral_group_award'], 100, 4), $award_price_num, 2);
  2582. }
  2583. if ($brokeragePrice > $send_normal) {
  2584. $real_send = bcsub($brokeragePrice, $send_normal, 2);
  2585. if ($real_send > 0) {
  2586. $mark = '用户' . $userInfo['nickname'] . '(' . $order['uid'] . ')' . '购买' . ($order['use_integral'] > 0 ? '积分' : '普通') . '商品,获得津贴绿积分' . $real_send;
  2587. $res = $res && UserBill::income('津贴绿积分', $spread['uid'], 'now_money', 'brokerage', $real_send, $order['id'], bcadd($balance, $real_send, 2), $mark);
  2588. $res = $res && User::where('uid', $spread['uid'])->inc('brokerage_price', $real_send)->update();
  2589. $send_normal = $brokeragePrice;
  2590. }
  2591. }
  2592. // }
  2593. $spread = User::getUserInfo($spread['spread_uid']);
  2594. }
  2595. return $res;
  2596. }
  2597. public static function sendGroupAwardSee($order): bool
  2598. {
  2599. // return true;
  2600. //TODO 营销产品不返佣金
  2601. if (isset($order['combination_id']) && $order['combination_id']) return true;
  2602. if (isset($order['seckill_id']) && $order['seckill_id']) return true;
  2603. if (isset($order['bargain_id']) && $order['bargain_id']) return true;
  2604. $userInfo = User::getUserInfo($order['uid']);
  2605. $spread = User::getUserInfo($userInfo['spread_uid']);
  2606. // if (StoreOrder::where('uid', $order['uid'])->where('paid', 1)->where('refund_status', 0)->where('is_del', 0)->where('is_system_del', 0)
  2607. // ->where('id', '<>', $order['id'])->where('suit', '>', 0)->find()) {
  2608. // $spread = $userInfo;
  2609. // }
  2610. $cartInfo = StoreOrderCartInfo::whereIn('cart_id', $order['cart_id'])->column('cart_info');
  2611. $suit = 0;
  2612. $suit_exit = 0;
  2613. $suit_award = 0;
  2614. $suit_price = 0;
  2615. $extra_price = 0;
  2616. foreach ($cartInfo as $value) {
  2617. $product = json_decode($value, true);
  2618. if (isset($product['productInfo'])) {
  2619. $productInfo = $product['productInfo'];
  2620. if (($productInfo['attrInfo']['brokerage_suit'] ?? 0) > 0) {
  2621. $suit_award += $product['productInfo']['attrInfo']['brokerage_suit'] * $product['cart_num'];
  2622. $suit_price += ($productInfo['attrInfo']['price'] ?? $product['price']) * $product['cart_num'];
  2623. if ($product['is_suit']) $suit_exit += $product['cart_num'] ?? 0;
  2624. }
  2625. if ($product['is_suit']) {
  2626. $suit += $product['cart_num'] ?? 0;
  2627. $suit_price += ($productInfo['attrInfo']['price'] ?? $product['price']) * $product['cart_num'];
  2628. }
  2629. if (!$product['is_award']) {
  2630. $extra_price += ($productInfo['attrInfo']['price'] ?? $product['price']) * $product['cart_num'];
  2631. }
  2632. }
  2633. }
  2634. $res = true;
  2635. $suit_recommend = sys_config('suit_recommend', 0, true);
  2636. if ($spread) {
  2637. //推荐奖
  2638. $brokeragePrice = bcmul($suit_recommend, $suit - $suit_exit, 2);
  2639. $brokeragePrice = bcadd($suit_award, $brokeragePrice, 2);
  2640. if ($brokeragePrice > 0) {
  2641. $mark = '用户' . $userInfo['nickname'] . '(' . $order['uid'] . ')' . '购买套装商品,获得推荐奖励' . $brokeragePrice;
  2642. var_dump($mark);
  2643. }
  2644. }
  2645. $send = 0;
  2646. $send_normal = 0;
  2647. $layer = 1;
  2648. $layer_award = sys_data('suit_sub_award');
  2649. $layer_award_real = [];
  2650. $company_award = false;
  2651. $operate_award = false;
  2652. foreach ($layer_award as $v) {
  2653. $layer_award_real[$v['layer']] = $v;
  2654. }
  2655. while ($spread) {
  2656. $group_level = SystemGroupLevel::get($spread['group_level']);
  2657. $award_level = SystemGroupLevel::get($spread['award_level']);
  2658. $balance = $spread['brokerage_price'];
  2659. if ($suit) {
  2660. $award_group = $group_level['suit_award'] ?? 0;
  2661. $award_award = $award_level['suit_award'] ?? 0;
  2662. $big = $award_group > $award_award ? $group_level['id'] : $award_level['id'];
  2663. $brokeragePrice_a = bcmul($award_award, $suit, 2);
  2664. $brokeragePrice_g = bcmul($award_group, $suit, 2);
  2665. $brokeragePrice_big = $brokeragePrice_a > $brokeragePrice_g ? $brokeragePrice_a : $brokeragePrice_g;
  2666. // $brokeragePrice_small = $brokeragePrice_a > $brokeragePrice_g ? $brokeragePrice_g : $brokeragePrice_a;
  2667. // if ($brokeragePrice_big == $brokeragePrice_small) {
  2668. $brokeragePrice = $brokeragePrice_big;
  2669. if ($brokeragePrice > $send) {
  2670. $real_send = bcsub($brokeragePrice, $send, 2);
  2671. if ($real_send > 0) {
  2672. $mark = '用户' . $userInfo['nickname'] . '(' . $order['uid'] . ')' . '购买套装商品,获得津贴绿积分' . $real_send;
  2673. var_dump($mark);
  2674. }
  2675. }
  2676. if (($group_level['company_award'] > 0 || $award_level['company_award'] > 0) && !$company_award) {
  2677. $ratio = ($group_level['company_award'] > $award_level['company_award'] ? $group_level['company_award'] : $award_level['company_award']);
  2678. $spread_up = User::where('uid', $spread['spread_uid'])->find();
  2679. $group_levels = SystemGroupLevel::where('company_award', '>', 0)->column('id');
  2680. $p_ratio = 0;
  2681. $award_levels = SystemAwardLevel::where('company_award', '>', 0)->column('id');
  2682. // @file_put_contents('order.txt', '【8.8】' . time() . PHP_EOL, FILE_APPEND);
  2683. while ($spread_up) {
  2684. if (in_array($spread_up['group_level'], $group_levels) || in_array($spread_up['award_level'], $award_levels)) {
  2685. $ratio -= 1;
  2686. $p_ratio = 1;
  2687. break;
  2688. }
  2689. $spread_up = User::where('uid', $spread_up['spread_uid'])->find();
  2690. }
  2691. if ($ratio > 0) {
  2692. $op_award = bcmul($suit_price, bcdiv($ratio, 100, 4), 2);
  2693. if ($op_award > 0) {
  2694. $mark = '用户' . $userInfo['nickname'] . '(' . $order['uid'] . ')' . '购买套装商品,获得分公司奖奖励' . $op_award;
  2695. var_dump($mark);
  2696. }
  2697. }
  2698. if ($p_ratio > 0) {
  2699. $op_award = bcmul($suit_price, bcdiv($p_ratio, 100, 4), 2);
  2700. if ($op_award > 0) {
  2701. $mark = '用户' . $userInfo['nickname'] . '(' . $order['uid'] . ')' . '购买套装商品,获得分公司奖奖励' . $op_award;
  2702. var_dump($mark);
  2703. }
  2704. }
  2705. $company_award = true;
  2706. }
  2707. if (($group_level['operate_award'] > 0 || $award_level['operate_award'] > 0) && !$operate_award) {
  2708. $ratio = ($group_level['operate_award'] > $award_level['operate_award'] ? $group_level['operate_award'] : $award_level['operate_award']);
  2709. if ($ratio > 0) {
  2710. $op_award = bcmul($suit_price, bcdiv($ratio, 100, 4), 2);
  2711. if ($op_award > 0) {
  2712. $mark = '用户' . $userInfo['nickname'] . '(' . $order['uid'] . ')' . '购买套装商品,获得运营公司奖励' . $op_award;
  2713. var_dump($mark);
  2714. }
  2715. }
  2716. $operate_award = true;
  2717. }
  2718. }
  2719. $lay_award = $layer_award_real[$layer] ?? null;
  2720. if ($lay_award) {
  2721. $sps = User::where('spread_uid', $spread['uid'])->column('uid');
  2722. $count = 0;
  2723. foreach ($sps as $vvv) {
  2724. if (StoreOrder::where('uid', $vvv)->where('paid', 1)->where('refund_status', 0)->where('is_del', 0)->where('is_system_del', 0)
  2725. ->where('suit', '>', 0)->find()) {
  2726. $count++;
  2727. }
  2728. }
  2729. if ($count >= $lay_award['recommend']
  2730. || StoreOrder::where('uid', $spread['uid'])
  2731. ->where('paid', 1)
  2732. ->where('refund_status', 0)
  2733. ->where('is_del', 0)
  2734. ->where('is_system_del', 0)
  2735. ->where('suit', '>', 0)
  2736. ->sum('suit') >= 25) {
  2737. if ($suit) {
  2738. $brokeragePrice = bcmul($lay_award['award'], $suit, 2);
  2739. if ($brokeragePrice > 0) {
  2740. $mark = '用户' . $userInfo['nickname'] . '(' . $order['uid'] . ')' . '购买套装商品,获得见点奖励' . $brokeragePrice;
  2741. var_dump($mark);
  2742. }
  2743. }
  2744. if ($order['use_integral'] > 0) {
  2745. $brokeragePrice = bcmul(bcdiv($lay_award['integral_award'], 100, 4), bcsub(bcsub($order['total_price'], $suit_price, 2), $extra_price, 2), 2);
  2746. if ($brokeragePrice > 0) {
  2747. $mark = '用户' . $userInfo['nickname'] . '(' . $order['uid'] . ')' . '购买积分商品,获得见点奖励' . $brokeragePrice;
  2748. var_dump($mark);
  2749. }
  2750. }
  2751. $layer++;
  2752. }
  2753. }
  2754. var_dump($group_level['level_id']);
  2755. // if ($group_level) {
  2756. if (!$group_level) {
  2757. $group_award_basic = sys_config('group_award_basic', 0);
  2758. $integral_group_award_basic = sys_config('integral_group_award_basic', 0);
  2759. $brokeragePrice = bcmul(bcdiv($group_award_basic, 100, 4), bcsub(bcsub($order['total_price'], $suit_price, 2), $extra_price, 2), 2);
  2760. if ($order['use_integral'] > 0) $brokeragePrice = bcmul(bcdiv($integral_group_award_basic, 100, 4), bcsub(bcsub($order['total_price'], $suit_price, 2), $extra_price, 2), 2);
  2761. } else {
  2762. $brokeragePrice = bcmul(bcdiv($group_level['group_award'], 100, 4), bcsub(bcsub($order['total_price'], $suit_price, 2), $extra_price, 2), 2);
  2763. if ($order['use_integral'] > 0) $brokeragePrice = bcmul(bcdiv($group_level['integral_group_award'], 100, 4), bcsub(bcsub($order['total_price'], $suit_price, 2), $extra_price, 2), 2);
  2764. }
  2765. if ($brokeragePrice > $send_normal) {
  2766. $real_send = bcsub($brokeragePrice, $send_normal, 2);
  2767. if ($real_send > 0) {
  2768. $mark = '用户' . $userInfo['nickname'] . '(' . $order['uid'] . ')' . '购买' . ($order['use_integral'] > 0 ? '积分' : '普通') . '商品,获得津贴绿积分' . $real_send;
  2769. var_dump($mark);
  2770. }
  2771. }
  2772. // }
  2773. $spread = User::getUserInfo($spread['spread_uid']);
  2774. }
  2775. return $res;
  2776. }
  2777. public static function sendAllSystemAward($order): bool
  2778. {
  2779. // return true;
  2780. //TODO 营销产品不返佣金
  2781. if (isset($order['combination_id']) && $order['combination_id']) return true;
  2782. if (isset($order['seckill_id']) && $order['seckill_id']) return true;
  2783. if (isset($order['bargain_id']) && $order['bargain_id']) return true;
  2784. $userInfo = User::getUserInfo($order['uid']);
  2785. $cartInfo = StoreOrderCartInfo::whereIn('cart_id', $order['cart_id'])->column('cart_info');
  2786. $suit = 0;
  2787. $suit_price = 0;
  2788. foreach ($cartInfo as $value) {
  2789. $product = json_decode($value, true);
  2790. if (isset($product['productInfo'])) {
  2791. $productInfo = $product['productInfo'];
  2792. if ($product['is_suit']) {
  2793. $suit += $product['cart_num'] ?? 0;
  2794. $suit_price += ($productInfo['attrInfo']['price'] ?? $product['price']) * $product['cart_num'];
  2795. }
  2796. }
  2797. }
  2798. $levels = SystemGroupLevel::where('system_award', 1)->column('id');
  2799. $levels2 = SystemAwardLevel::where('system_award', 1)->column('id');
  2800. if (count($levels) && count($levels2)) {
  2801. $users = User::where('group_level', 'in', $levels)->whereOr('award_level', 'in', $levels2)
  2802. ->select();
  2803. } else if (count($levels)) {
  2804. $users = User::where('group_level', 'in', $levels)
  2805. ->select();
  2806. } else if (count($levels2)) {
  2807. $users = User::where('award_level', 'in', $levels2)
  2808. ->select();
  2809. } else {
  2810. $users = [];
  2811. }
  2812. $res = true;
  2813. $award = bcdiv(bcmul(100, $suit, 2), count($users) ?: 1, 2);
  2814. if ($suit && $award && count($users)) {
  2815. foreach ($users as $v) {
  2816. $mark = '用户' . $userInfo['nickname'] . '(' . $order['uid'] . ')' . '购买套装商品,获得董事分红' . $award;
  2817. $res = $res && UserBill::income('董事加权分红', $v['uid'], 'now_money', 'brokerage', $award, $order['id'], bcadd($v['brokerage_price'], $award, 2), $mark);
  2818. $res = $res && User::where('uid', $v['uid'])->inc('brokerage_price', $award)->update();
  2819. }
  2820. }
  2821. return $res;
  2822. }
  2823. public static function sendSuit($order): bool
  2824. {
  2825. // return true;
  2826. //TODO 营销产品不返佣金
  2827. if (isset($order['combination_id']) && $order['combination_id']) return true;
  2828. if (isset($order['seckill_id']) && $order['seckill_id']) return true;
  2829. if (isset($order['bargain_id']) && $order['bargain_id']) return true;
  2830. $userInfo = User::getUserInfo($order['uid']);
  2831. $cartInfo = StoreOrderCartInfo::whereIn('cart_id', $order['cart_id'])->column('cart_info');
  2832. $suit = 0;
  2833. foreach ($cartInfo as $value) {
  2834. $product = json_decode($value, true);
  2835. if (isset($product['productInfo'])) {
  2836. if ($product['is_suit']) {
  2837. $suit += $product['cart_num'] ?? 0;
  2838. }
  2839. }
  2840. }
  2841. $res = true;
  2842. $suit_give_integral = sys_config('suit_give_integral', 0, true);
  2843. $suit_give_gf = sys_config('suit_give_gf', 0, true);
  2844. if ($suit_give_integral > 0) {
  2845. //获得积分
  2846. $brokeragePrice = bcmul($suit_give_integral, $suit, 2);
  2847. if ($brokeragePrice > 0) {
  2848. $mark = '购买套装商品,获得积分' . $brokeragePrice;
  2849. $res = $res && UserBill::income('购买套装赠送', $userInfo['uid'], 'integral', 'suit_gain', $brokeragePrice, $order['id'], bcadd($userInfo['integral'], $brokeragePrice, 2), $mark);
  2850. $res = $res && User::where('uid', $userInfo['uid'])->inc('integral', $brokeragePrice)->update();
  2851. }
  2852. }
  2853. // if ($suit_give_gf > 0 && SystemStoreMember::be(['uid' => $userInfo['uid']])) {
  2854. // //获得股份
  2855. // $brokeragePrice = bcmul($suit_give_gf, $suit, 2);
  2856. // if ($brokeragePrice > 0) {
  2857. // $res = $res && SystemStoreMember::where('uid', $userInfo['uid'])->inc('consume_rights', $brokeragePrice)->update();
  2858. // }
  2859. // }
  2860. return $res;
  2861. }
  2862. }