StoreOrder.php 120 KB

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