StoreOrder.php 121 KB

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