StoreOrder.php 120 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564
  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. return false !== $res;
  781. }
  782. /**
  783. * @param $order
  784. * @return bool``
  785. * @throws DataNotFoundException
  786. * @throws DbException
  787. * @throws ModelNotFoundException
  788. */
  789. public static function backGroupAward($order): bool
  790. {
  791. // return true;
  792. //TODO 营销产品不返佣金
  793. if (isset($orderInfo['combination_id']) && $orderInfo['combination_id']) return true;
  794. if (isset($orderInfo['seckill_id']) && $orderInfo['seckill_id']) return true;
  795. if (isset($orderInfo['bargain_id']) && $orderInfo['bargain_id']) return true;
  796. if (isset($orderInfo['exchange_id']) && $orderInfo['exchange_id']) return true;
  797. $userInfo = User::getUserInfo($order['uid']);
  798. $spread = User::getUserInfo($userInfo['spread_uid']);
  799. $cartInfo = StoreOrderCartInfo::whereIn('cart_id', $order['cart_id'])->column('cart_info');
  800. $user_level_id = UserLevel::getUserLevelInfo(UserLevel::getUserLevel($order['uid']), 'level_id');
  801. if (!$user_level_id) $user_level_id = 0;
  802. $last_price = [];
  803. $cartNum = [];
  804. foreach ($cartInfo as $value) {
  805. $product = json_decode($value, true);
  806. if (isset($product['productInfo'])) {
  807. $productInfo = $product['productInfo'];
  808. $cartNum[$product['id']] = $product['cart_num'] ?? 0;
  809. if (isset($productInfo['attrInfo'])) {
  810. $attrInfo = $productInfo['attrInfo'];
  811. $level_price = json_decode($attrInfo['level_price'] ?? '', true);
  812. if ($user_level_id > 0) {
  813. if (isset($level_price['level_' . $user_level_id]) && $level_price['level_' . $user_level_id]) {
  814. $price = (float)$level_price['level_' . $user_level_id];
  815. } else {
  816. $price = (float)StoreProduct::setLevelPrice($attrInfo['price'], $order['uid'], true);
  817. }
  818. } else {
  819. $price = $attrInfo['price'];
  820. }
  821. if ($userInfo['store_id'] > 0 && $userInfo['store_id'] == $productInfo['store_id']) {
  822. $level_price = json_decode($attrInfo['level_price'], true);
  823. if (count($level_price) > 0) {
  824. $price = (float)min($level_price);
  825. } else {
  826. $discount = SystemUserLevel::setWhere()->min('discount');
  827. $discount = bcdiv($discount, 100, 2);
  828. $price = (float)bcmul($discount, $attrInfo['price'], 2);
  829. }
  830. }
  831. } else {
  832. $price = (float)StoreProduct::setLevelPrice($productInfo['price'], $order['uid'], true);
  833. if ($userInfo['store_id'] > 0 && $userInfo['store_id'] == $productInfo['store_id']) {
  834. $discount = SystemUserLevel::setWhere()->min('discount');
  835. $discount = bcdiv($discount, 100, 2);
  836. $price = (float)bcmul($discount, $productInfo['price'], 2);
  837. }
  838. }
  839. $last_price[(isset($productInfo['store_type']) && $productInfo['store_type'] == 1 ? 'real' : 'virtual')][$product['id']] = $price;
  840. }
  841. }
  842. $last_level = 0;
  843. $last_send = [
  844. 'real' => 0,
  845. 'virtual' => 0,
  846. ];
  847. $same = 0;
  848. $res = true;
  849. while ($spread) {
  850. $level = UserLevel::getUserLevelInfo(UserLevel::getUserLevel($spread['uid']));
  851. $user_level_id = UserLevel::getUserLevelInfo(UserLevel::getUserLevel($spread['uid']), 'level_id');
  852. if (!$user_level_id) $user_level_id = 0;
  853. $this_price = [];
  854. foreach ($cartInfo as $value) {
  855. $product = json_decode($value, true);
  856. if (isset($product['productInfo'])) {
  857. $productInfo = $product['productInfo'];
  858. $user = User::get($spread['uid']);
  859. if (isset($productInfo['attrInfo'])) {
  860. $attrInfo = $productInfo['attrInfo'];
  861. $level_price = json_decode($attrInfo['level_price'] ?? '', true);
  862. if ($user_level_id > 0) {
  863. if (isset($level_price['level_' . $user_level_id]) && $level_price['level_' . $user_level_id]) {
  864. $price = (float)$level_price['level_' . $user_level_id];
  865. } else {
  866. $price = (float)StoreProduct::setLevelPrice($attrInfo['price'], $spread['uid'], true);
  867. }
  868. } else {
  869. $price = $attrInfo['price'];
  870. }
  871. if ($user['store_id'] > 0 && $user['store_id'] == $productInfo['store_id']) {
  872. $level_price = json_decode($attrInfo['level_price'], true);
  873. if (count($level_price) > 0) {
  874. $price = (float)min($level_price);
  875. } else {
  876. $discount = SystemUserLevel::setWhere()->min('discount');
  877. $discount = bcdiv($discount, 100, 2);
  878. $price = (float)bcmul($discount, $attrInfo['price'], 2);
  879. }
  880. }
  881. } else {
  882. $price = (float)StoreProduct::setLevelPrice($productInfo['price'], $spread['uid'], true);
  883. if ($user['store_id'] > 0 && $user['store_id'] == $productInfo['store_id']) {
  884. $discount = SystemUserLevel::setWhere()->min('discount');
  885. $discount = bcdiv($discount, 100, 2);
  886. $price = (float)bcmul($discount, $productInfo['price'], 2);
  887. }
  888. }
  889. $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']];
  890. }
  891. }
  892. if ($this_price == $last_price && $same == 0 && $user_level_id == $last_level) {
  893. //平级奖
  894. $brokeragePrice = bcmul($last_send['real'], bcdiv($level['same_level_award_ratio'], 100, 4), 8);
  895. if ($brokeragePrice <= 0) {
  896. $spread = User::getUserInfo($spread['spread_uid']);
  897. continue;
  898. }
  899. $mark = '用户' . $userInfo['nickname'] . '(' . $order['uid'] . ')' . '购买实体商品,获得团队平级奖励' . $brokeragePrice;
  900. $res = $res && UserBill::income('获得商品平级奖', $spread['uid'], 'now_money', 'brokerage', $brokeragePrice, $order['id'], $spread['brokerage_price'], $mark, 0);
  901. $brokeragePrice = bcmul($last_send['virtual'], bcdiv($level['same_level_award_ratio'], 100, 4), 8);
  902. if ($brokeragePrice <= 0) {
  903. $spread = User::getUserInfo($spread['spread_uid']);
  904. continue;
  905. }
  906. $mark = '用户' . $userInfo['nickname'] . '(' . $order['uid'] . ')' . '购买虚拟商品,获得团队平级奖励' . $brokeragePrice;
  907. $res = $res && UserBill::income('获得商品平级奖', $spread['uid'], 'now_money', 'brokerage', $brokeragePrice, $order['id'], bcadd($spread['brokerage_price'], $brokeragePrice, 2), $mark);
  908. Message::addMessage($order['uid'], $mark, 200);
  909. $res = $res && User::where('uid', $spread['uid'])->inc('brokerage_price', $brokeragePrice)->update();
  910. $same++;
  911. $spread = User::getUserInfo($spread['spread_uid']);
  912. continue;
  913. }
  914. if (isset($this_price['real'])) {
  915. $price1 = 0;
  916. $price2 = 0;
  917. $sub = 0;
  918. foreach ($this_price['real'] as $k => $price) {
  919. if ($price < $last_price['real'][$k]) {
  920. $price1 += $price;
  921. $price2 += $last_price['real'][$k];
  922. $sub += (float)bcsub($last_price['real'][$k], $price, 2);
  923. }
  924. }
  925. // if ($spread['now_money'] >= $price1 && $price1 > 0 && $price2 > 0) {
  926. // $mark = '用户' . $userInfo['nickname'] . '(' . $order['uid'] . ')' . '购买实体商品,获得团队极差奖励' . $price2;
  927. // $res = $res && UserBill::expend('余额转团队奖', $spread['uid'], 'now_money', 'to_brokerage', $price1, $order['id'], bcsub($spread['now_money'], $price1, 2), $mark);
  928. // $res = $res && UserBill::income('获得商品团队奖', $spread['uid'], 'now_money', 'brokerage', $price2, $order['id'], $spread['brokerage_price'], $mark, 0);
  929. // $res = $res && User::where('uid', $spread['uid'])->dec('now_money', $price1)->update();
  930. // $spread['now_money'] = $spread['now_money'] - $price1;
  931. // } else if ($sub > 0) {
  932. $mark = '用户' . $userInfo['nickname'] . '(' . $order['uid'] . ')' . '购买实体商品,获得团队极差奖励' . $sub;
  933. $res = $res && UserBill::income('获得商品团队奖', $spread['uid'], 'now_money', 'brokerage', $sub, $order['id'], $spread['brokerage_price'], $mark, 0);
  934. // }
  935. }
  936. if (isset($this_price['virtual'])) {
  937. $price1 = 0;
  938. $price2 = 0;
  939. $sub = 0;
  940. foreach ($this_price['virtual'] as $k => $price) {
  941. if ($price < $last_price['virtual'][$k]) {
  942. $price1 += $price;
  943. $price2 += $last_price['virtual'][$k];
  944. $sub += (float)bcsub($last_price['virtual'][$k], $price, 2);
  945. }
  946. }
  947. // if ($spread['now_money'] >= $price1 && $price1 > 0 && $price2 > 0) {
  948. // $mark = '用户' . $userInfo['nickname'] . '(' . $order['uid'] . ')' . '购买虚拟商品,获得团队极差奖励' . $price2;
  949. // $res = $res && UserBill::expend('余额转团队奖', $spread['uid'], 'now_money', 'to_brokerage', $price1, $order['id'], bcsub($spread['now_money'], $price1, 2), $mark);
  950. // $res = $res && UserBill::income('获得商品团队奖', $spread['uid'], 'now_money', 'brokerage', $price2, $order['id'], bcadd($spread['brokerage_price'], $price2, 2), $mark);
  951. // $res = $res && User::where('uid', $spread['uid'])->dec('now_money', $price1)->inc('brokerage_price', $price2)->update();
  952. // Message::addMessage($spread['uid'], $mark, 200);
  953. // $spread['now_money'] = $spread['now_money'] - $price1;
  954. // } else if ($sub > 0) {
  955. $mark = '用户' . $userInfo['nickname'] . '(' . $order['uid'] . ')' . '购买虚拟商品,获得团队极差奖励' . $sub;
  956. $res = $res && UserBill::income('获得商品团队奖', $spread['uid'], 'now_money', 'product_brokerage_group', $sub, $order['id'], bcadd($spread['brokerage_price'], $sub, 2), $mark);
  957. $res = $res && User::where('uid', $spread['uid'])->inc('brokerage_price', $sub)->update();
  958. Message::addMessage($spread['uid'], $mark, 200);
  959. // }
  960. }
  961. $same = 0;
  962. $last_price = $this_price;
  963. $last_level = $level['level_id'];
  964. $last_send['real'] = $sub;
  965. $spread = User::getUserInfo($spread['spread_uid']);
  966. }
  967. return $res;
  968. }
  969. /*
  970. * 线下支付消息通知
  971. * 待完善
  972. *
  973. * */
  974. public static function createOrderTemplate($order)
  975. {
  976. //$goodsName = StoreOrderCartInfo::getProductNameList($order['id']);
  977. // RoutineTemplateService::sendTemplate(WechatUser::getOpenId($order['uid']),RoutineTemplateService::ORDER_CREATE, [
  978. // 'first'=>'亲,您购买的商品已支付成功',
  979. // 'keyword1'=>date('Y/m/d H:i',$order['add_time']),
  980. // 'keyword2'=>implode(',',$goodsName),
  981. // 'keyword3'=>$order['order_id'],
  982. // 'remark'=>'点击查看订单详情'
  983. // ],Url::build('/wap/My/order',['uni'=>$order['order_id']],true,true));
  984. // RoutineTemplateService::sendAdminNoticeTemplate([
  985. // 'first'=>"亲,您有一个新订单 \n订单号:{$order['order_id']}",
  986. // 'keyword1'=>'新订单',
  987. // 'keyword2'=>'线下支付',
  988. // 'keyword3'=>date('Y/m/d H:i',time()),
  989. // 'remark'=>'请及时处理'
  990. // ]);
  991. }
  992. /**
  993. * 获取订单详情
  994. * @param $uid
  995. * @param $key
  996. * @return array|\think\Model|null
  997. * @throws DataNotFoundException
  998. * @throws ModelNotFoundException
  999. * @throws \think\exception\DbException
  1000. */
  1001. public static function getUserOrderDetail($uid, $key)
  1002. {
  1003. return self::where('order_id|unique', $key)->where('uid', $uid)->where('is_del', 0)->find();
  1004. }
  1005. /**
  1006. * TODO 订单发货
  1007. * @param array $postageData 发货信息
  1008. * @param string $oid orderID
  1009. */
  1010. public static function orderPostageAfter($postageData, $oid)
  1011. {
  1012. $order = self::where('id', $oid)->find();
  1013. if ($postageData['delivery_type'] == 'send') {//送货
  1014. RoutineTemplate::sendOrderPostage($order);
  1015. } else if ($postageData['delivery_type'] == 'express') {//发货
  1016. RoutineTemplate::sendOrderPostage($order, 1);
  1017. }
  1018. }
  1019. /** 收货后发送模版消息
  1020. * @param $order
  1021. */
  1022. public static function orderTakeAfter($order)
  1023. {
  1024. $title = self::getProductTitle($order['cart_id']);
  1025. if ($order['is_channel'] == 1) {//小程序
  1026. RoutineTemplate::sendOrderTakeOver($order, $title);
  1027. } else {
  1028. $openid = WechatUser::where('uid', $order['uid'])->value('openid');
  1029. \crmeb\services\WechatTemplateService::sendTemplate($openid, \crmeb\services\WechatTemplateService::ORDER_TAKE_SUCCESS, [
  1030. 'first' => '亲,您的订单已收货',
  1031. 'keyword1' => $order['order_id'],
  1032. 'keyword2' => '已收货',
  1033. 'keyword3' => date('Y-m-d H:i:s', time()),
  1034. 'keyword4' => $title,
  1035. 'remark' => '感谢您的光临!'
  1036. ]);
  1037. }
  1038. }
  1039. /**
  1040. * 删除订单
  1041. * @param $uni
  1042. * @param $uid
  1043. * @return bool
  1044. */
  1045. public static function removeOrder($uni, $uid)
  1046. {
  1047. $order = self::getUserOrderDetail($uid, $uni);
  1048. if (!$order) return self::setErrorInfo('订单不存在!');
  1049. $order = self::tidyOrder($order);
  1050. if ($order['_status']['_type'] != 0 && $order['_status']['_type'] != -2 && $order['_status']['_type'] != 4)
  1051. return self::setErrorInfo('该订单无法删除!');
  1052. if (false !== self::edit(['is_del' => 1], $order['id'], 'id') && false !== StoreOrderStatus::status($order['id'], 'remove_order', '删除订单')) {
  1053. //未支付和已退款的状态下才可以退积分退库存退优惠券
  1054. if ($order['_status']['_type'] == 0 || $order['_status']['_type'] == -2) {
  1055. event('StoreOrderRegressionAllAfter', [$order]);
  1056. }
  1057. event('UserOrderRemoved', $uni);
  1058. return true;
  1059. } else
  1060. return self::setErrorInfo('订单删除失败!');
  1061. }
  1062. /**
  1063. * //TODO 用户确认收货
  1064. * @param $uni
  1065. * @param $uid
  1066. */
  1067. public static function takeOrder($uni, $uid)
  1068. {
  1069. $order = self::getUserOrderDetail($uid, $uni);
  1070. if (!$order) return self::setErrorInfo('订单不存在!');
  1071. $order = self::tidyOrder($order);
  1072. if ($order['_status']['_type'] != 2) return self::setErrorInfo('订单状态错误!');
  1073. self::beginTrans();
  1074. if (false !== self::edit(['status' => 2], $order['id'], 'id') &&
  1075. false !== StoreOrderStatus::status($order['id'], 'user_take_delivery', '用户已收货')) {
  1076. try {
  1077. OrderRepository::storeProductOrderUserTakeDelivery($order, $uid);
  1078. UserBill::where('uid', $order['uid'])->where('link_id', $order['id'])->where('type', 'pay_money')->update(['take' => 1]);
  1079. } catch (\Exception $e) {
  1080. self::rollbackTrans();
  1081. return self::setErrorInfo($e->getMessage());
  1082. }
  1083. self::commitTrans();
  1084. event('UserLevelAfter', [User::get($uni)]);
  1085. event('UserOrderTake', $uni);
  1086. //短信通知
  1087. event('ShortMssageSend', [$order['order_id'], ['Receiving', 'AdminConfirmTakeOver']]);
  1088. return true;
  1089. } else {
  1090. self::rollbackTrans();
  1091. return false;
  1092. }
  1093. }
  1094. /**
  1095. * 获取订单状态购物车等信息
  1096. * @param $order
  1097. * @param bool $detail 是否获取订单购物车详情
  1098. * @param bool $isPic 是否获取订单状态图片
  1099. * @return mixed
  1100. * @throws DataNotFoundException
  1101. * @throws ModelNotFoundException
  1102. * @throws \think\exception\DbException
  1103. */
  1104. public static function tidyOrder($order, $detail = false, $isPic = false)
  1105. {
  1106. if ($detail == true && isset($order['id'])) {
  1107. $cartInfo = StoreOrderCartInfo::where('oid', $order['id'])->column('cart_info', 'unique') ?: [];
  1108. $info = [];
  1109. foreach ($cartInfo as $k => $cart) {
  1110. $cart = json_decode($cart, true);
  1111. $cart['unique'] = $k;
  1112. //新增是否评价字段
  1113. $cart['is_reply'] = StoreProductReply::where('unique', $k)->count();
  1114. if (isset($cart['productInfo']['attrInfo']['money_type'])) $cart['productInfo']['attrInfo']['money_type_name'] = get_money_name($cart['productInfo']['attrInfo']['money_type']);
  1115. array_push($info, $cart);
  1116. unset($cart);
  1117. }
  1118. $order['cartInfo'] = $info;
  1119. }
  1120. $status = [];
  1121. if (!$order['paid'] && $order['pay_type'] == 'offline' && !$order['status'] >= 2) {
  1122. $status['_type'] = 9;
  1123. $status['_title'] = '线下付款';
  1124. $status['_msg'] = '商家处理中,请耐心等待';
  1125. $status['_class'] = 'nobuy';
  1126. } else if (!$order['paid']) {
  1127. $status['_type'] = 0;
  1128. $status['_title'] = '未支付';
  1129. //系统预设取消订单时间段
  1130. $keyValue = ['order_cancel_time', 'order_activity_time', 'order_bargain_time', 'order_seckill_time', 'order_pink_time'];
  1131. //获取配置
  1132. $systemValue = SystemConfigService::more($keyValue);
  1133. //格式化数据
  1134. $systemValue = self::setValeTime($keyValue, is_array($systemValue) ? $systemValue : []);
  1135. if ($order['pink_id'] || $order['combination_id']) {
  1136. $order_pink_time = $systemValue['order_pink_time'] ? $systemValue['order_pink_time'] : $systemValue['order_activity_time'];
  1137. $time = bcadd($order['add_time'], $order_pink_time * 3600, 0);
  1138. $status['_msg'] = '请在' . date('m-d H:i:s', $time) . '前完成支付!';
  1139. } else if ($order['seckill_id']) {
  1140. $order_seckill_time = $systemValue['order_seckill_time'] ? $systemValue['order_seckill_time'] : $systemValue['order_activity_time'];
  1141. $time = bcadd($order['add_time'], $order_seckill_time * 3600, 0);
  1142. $status['_msg'] = '请在' . date('m-d H:i:s', $time) . '前完成支付!';
  1143. } else if ($order['bargain_id']) {
  1144. $order_bargain_time = $systemValue['order_bargain_time'] ? $systemValue['order_bargain_time'] : $systemValue['order_activity_time'];
  1145. $time = bcadd($order['add_time'], $order_bargain_time * 3600, 0);
  1146. $status['_msg'] = '请在' . date('m-d H:i:s', $time) . '前完成支付!';
  1147. } else {
  1148. $time = bcadd($order['add_time'], $systemValue['order_cancel_time'] * 3600, 0);
  1149. $status['_msg'] = '请在' . date('m-d H:i:s', $time) . '前完成支付!';
  1150. }
  1151. $status['_class'] = 'nobuy';
  1152. } else if ($order['refund_status'] == 1) {
  1153. $status['_type'] = -1;
  1154. $status['_title'] = '申请退款中';
  1155. $status['_msg'] = '商家审核中,请耐心等待';
  1156. $status['_class'] = 'state-sqtk';
  1157. } else if ($order['refund_status'] == 2) {
  1158. $status['_type'] = -2;
  1159. $status['_title'] = '已退款';
  1160. $status['_msg'] = '已为您退款,感谢您的支持';
  1161. $status['_class'] = 'state-sqtk';
  1162. } else if (!$order['status']) {
  1163. if ($order['pink_id']) {
  1164. if (StorePink::where('id', $order['pink_id'])->where('status', 1)->count()) {
  1165. $status['_type'] = 1;
  1166. $status['_title'] = '拼团中';
  1167. $status['_msg'] = '等待其他人参加拼团';
  1168. $status['_class'] = 'state-nfh';
  1169. } else {
  1170. $status['_type'] = 1;
  1171. $status['_title'] = '未发货';
  1172. $status['_msg'] = '商家未发货,请耐心等待';
  1173. $status['_class'] = 'state-nfh';
  1174. }
  1175. } else {
  1176. if ($order['shipping_type'] === 1) {
  1177. $status['_type'] = 1;
  1178. $status['_title'] = '未发货';
  1179. $status['_msg'] = '商家未发货,请耐心等待';
  1180. $status['_class'] = 'state-nfh';
  1181. } else {
  1182. $status['_type'] = 1;
  1183. $status['_title'] = '待核销';
  1184. $status['_msg'] = '待核销,请到核销点进行核销';
  1185. $status['_class'] = 'state-nfh';
  1186. }
  1187. }
  1188. } else if ($order['status'] == 1) {
  1189. if ($order['delivery_type'] == 'send') {//TODO 送货
  1190. $status['_type'] = 2;
  1191. $status['_title'] = '待收货';
  1192. $status['_msg'] = date('m月d日H时i分', StoreOrderStatus::getTime($order['id'], 'delivery')) . '服务商已送货';
  1193. $status['_class'] = 'state-ysh';
  1194. } else {//TODO 发货
  1195. $status['_type'] = 2;
  1196. $status['_title'] = '待收货';
  1197. if ($order['delivery_type'] == 'fictitious')
  1198. $_time = StoreOrderStatus::getTime($order['id'], 'delivery_fictitious');
  1199. else
  1200. $_time = StoreOrderStatus::getTime($order['id'], 'delivery_goods');
  1201. $status['_msg'] = date('m月d日H时i分', $_time) . '服务商已发货';
  1202. $status['_class'] = 'state-ysh';
  1203. }
  1204. } else if ($order['status'] == 2) {
  1205. $status['_type'] = 3;
  1206. $status['_title'] = '待评价';
  1207. $status['_msg'] = '已收货,快去评价一下吧';
  1208. $status['_class'] = 'state-ypj';
  1209. } else if ($order['status'] == 3) {
  1210. $status['_type'] = 4;
  1211. $status['_title'] = '交易完成';
  1212. $status['_msg'] = '交易完成,感谢您的支持';
  1213. $status['_class'] = 'state-ytk';
  1214. }
  1215. if (isset($order['pay_type']))
  1216. $status['_payType'] = isset(self::$payType[$order['pay_type']]) ? self::$payType[$order['pay_type']] : '其他方式';
  1217. if (isset($order['delivery_type']))
  1218. $status['_deliveryType'] = isset(self::$deliveryType[$order['delivery_type']]) ? self::$deliveryType[$order['delivery_type']] : '其他方式';
  1219. $order['_status'] = $status;
  1220. $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']);
  1221. $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']) : '';
  1222. $order['status_pic'] = '';
  1223. //获取产品状态图片
  1224. if ($isPic) {
  1225. $order_details_images = sys_data('order_details_images') ?: [];
  1226. foreach ($order_details_images as $image) {
  1227. if (isset($image['order_status']) && $image['order_status'] == $order['_status']['_type']) {
  1228. $order['status_pic'] = $image['pic'];
  1229. break;
  1230. }
  1231. }
  1232. }
  1233. $order['offlinePayStatus'] = (int)sys_config('offline_pay_status') ?? (int)2;
  1234. return $order;
  1235. }
  1236. /**
  1237. * 设置订单查询状态
  1238. * @param $status
  1239. * @param int $uid
  1240. * @param null $model
  1241. * @return StoreOrder|null
  1242. */
  1243. public static function statusByWhere($status, $uid = 0, $model = null)
  1244. {
  1245. // $orderId = StorePink::where('uid',$uid)->where('status',1)->column('order_id','id');//获取正在拼团的订单编号
  1246. if ($model == null) $model = new self;
  1247. if ('' === $status)
  1248. return $model;
  1249. else if ($status == 0)//未支付
  1250. return $model->where('paid', 0)->where('status', 0)->where('refund_status', 0);
  1251. else if ($status == 1)//待发货
  1252. return $model->where('paid', 1)->where('status', 0)->where('refund_status', 0);
  1253. else if ($status == 2)//待收货
  1254. return $model->where('paid', 1)->where('status', 1)->where('refund_status', 0);
  1255. else if ($status == 3)//待评价
  1256. return $model->where('paid', 1)->where('status', 2)->where('refund_status', 0);
  1257. else if ($status == 4)//已完成
  1258. return $model->where('paid', 1)->where('status', 3)->where('refund_status', 0);
  1259. else if ($status == -1)//退款中
  1260. return $model->where('paid', 1)->where('refund_status', 1);
  1261. else if ($status == -2)//已退款
  1262. return $model->where('paid', 1)->where('refund_status', 2);
  1263. else if ($status == -3)//退款
  1264. return $model->where('paid', 1)->where('refund_status', 'IN', '1,2');
  1265. // else if($status == 11){
  1266. // return $model->where('order_id','IN',implode(',',$orderId));
  1267. // }
  1268. else
  1269. return $model;
  1270. }
  1271. /**
  1272. * 获取订单并分页
  1273. * @param $uid
  1274. * @param string $status
  1275. * @param int $page
  1276. * @param int $limit
  1277. * @return mixed
  1278. * @throws DataNotFoundException
  1279. * @throws ModelNotFoundException
  1280. * @throws \think\exception\DbException
  1281. */
  1282. public static function getUserOrderList($uid, $status = '', $page = 0, $limit = 8)
  1283. {
  1284. if ($page) $list = self::statusByWhere($status, $uid)->where('is_del', 0)->where('uid', $uid)
  1285. ->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')
  1286. ->order('add_time DESC')->page((int)$page, (int)$limit)->select()->each(function ($item) {
  1287. if ($item['exchange_money']) {
  1288. $exchange_moneys = json_decode($item['exchange_money'], true);
  1289. $exchange_money = [];
  1290. foreach ($exchange_moneys as $k => $v) {
  1291. $exchange_money[] = ['type' => get_money_name($k), 'value' => $v];
  1292. }
  1293. $item['exchange_money'] = $exchange_money;
  1294. }
  1295. })->toArray();
  1296. else $list = self::statusByWhere($status, $uid)->where('is_del', 0)->where('uid', $uid)
  1297. ->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')
  1298. ->order('add_time DESC')->page((int)$page, (int)$limit)->select()->each(function ($item) {
  1299. if ($item['exchange_money']) {
  1300. $exchange_moneys = json_decode($item['exchange_money'], true);
  1301. $exchange_money = [];
  1302. foreach ($exchange_moneys as $k => $v) {
  1303. $exchange_money[] = ['type' => get_money_name($k), 'value' => $v];
  1304. }
  1305. $item['exchange_money'] = $exchange_money;
  1306. }
  1307. })->toArray();
  1308. foreach ($list as $k => $order) {
  1309. $list[$k] = self::tidyOrder($order, true);
  1310. }
  1311. return $list;
  1312. }
  1313. /**
  1314. * 获取推广人地下用户的订单金额
  1315. * @param string $uid
  1316. * @param string $status
  1317. * @return array
  1318. */
  1319. public static function getUserOrderCount($uid = '', $status = '')
  1320. {
  1321. $res = self::statusByWhere($status, $uid)->where('uid', 'IN', $uid)->column('pay_price');
  1322. return $res;
  1323. }
  1324. /**
  1325. * 搜索某个订单详细信息
  1326. * @param $uid
  1327. * @param $order_id
  1328. * @return bool|mixed
  1329. * @throws DataNotFoundException
  1330. * @throws ModelNotFoundException
  1331. * @throws \think\exception\DbException
  1332. */
  1333. public static function searchUserOrder($uid, $order_id)
  1334. {
  1335. $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')
  1336. ->order('add_time DESC')->find();
  1337. if (!$order)
  1338. return false;
  1339. else
  1340. return self::tidyOrder($order->toArray(), true);
  1341. }
  1342. /**
  1343. * 订单评价信息记录
  1344. * @param $oid
  1345. * @return StoreOrderStatus|\think\Model
  1346. * @throws \Exception
  1347. */
  1348. public static function orderOver($oid)
  1349. {
  1350. $res = self::edit(['status' => '3'], $oid, 'id');
  1351. if (!$res) exception('评价后置操作失败!');
  1352. return StoreOrderStatus::status($oid, 'check_order_over', '用户评价');
  1353. }
  1354. /**
  1355. * 设置订单产品评价完毕事件
  1356. * @param $oid
  1357. * @return StoreOrderStatus|\think\Model
  1358. * @throws \Exception
  1359. */
  1360. public static function checkOrderOver($oid)
  1361. {
  1362. $uniqueList = StoreOrderCartInfo::where('oid', $oid)->column('unique', 'unique');
  1363. //订单产品全部评价完成
  1364. if (StoreProductReply::where('unique', 'IN', $uniqueList)->where('oid', $oid)->count() == count($uniqueList)) {
  1365. event('StoreProductOrderOver', [$oid]);
  1366. return self::orderOver($oid);
  1367. }
  1368. }
  1369. public static function getOrderStatusNum($uid)
  1370. {
  1371. $noBuy = (int)self::where('uid', $uid)->where('paid', 0)->where('is_del', 0)->where('pay_type', '<>', 'offline')->count();
  1372. $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();
  1373. $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();
  1374. $noPostage = (int)bcadd($noPostageNoPink, $noPostageYesPink, 0);
  1375. $noTake = (int)self::where('uid', $uid)->where('paid', 1)->where('is_del', 0)->where('status', 1)->where('pay_type', '<>', 'offline')->count();
  1376. $noReply = (int)self::where('uid', $uid)->where('paid', 1)->where('is_del', 0)->where('status', 2)->count();
  1377. $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();
  1378. $noRefund = (int)self::where('uid', $uid)->where('paid', 1)->where('is_del', 0)->where('refund_status', 'IN', '1,2')->count();
  1379. return compact('noBuy', 'noPostage', 'noTake', 'noReply', 'noPink', 'noRefund');
  1380. }
  1381. /**
  1382. * 购买商品赠送积分
  1383. * @param $order
  1384. * @return bool
  1385. * @throws \think\Exception
  1386. * @throws DataNotFoundException
  1387. * @throws ModelNotFoundException
  1388. * @throws \think\exception\DbException
  1389. */
  1390. public static function gainUserIntegral($order)
  1391. {
  1392. if ($order['gain_integral'] > 0) {
  1393. $userInfo = User::getUserInfo($order['uid']);
  1394. BaseModel::beginTrans();
  1395. $res1 = false != User::where('uid', $userInfo['uid'])->update(['integral' => bcadd($userInfo['integral'], $order['gain_integral'], 2)]);
  1396. $res2 = false != UserBill::income('购买商品赠送积分', $order['uid'], 'integral', 'gain', $order['gain_integral'], $order['id'], $userInfo['integral'], '购买商品赠送' . floatval($order['gain_integral']) . '积分');
  1397. $res = $res1 && $res2;
  1398. BaseModel::checkTrans($res);
  1399. return $res;
  1400. }
  1401. return true;
  1402. }
  1403. /**
  1404. * 获取当前订单中有没有拼团存在
  1405. * @param $pid
  1406. * @return int|string
  1407. */
  1408. public static function getIsOrderPink($pid = 0, $uid = 0)
  1409. {
  1410. return self::where('uid', $uid)->where('pink_id', $pid)->where('refund_status', 0)->where('is_del', 0)->count();
  1411. }
  1412. /**
  1413. * 获取order_id
  1414. * @param $pid
  1415. * @return mixed
  1416. */
  1417. public static function getStoreIdPink($pid = 0, $uid = 0)
  1418. {
  1419. return self::where('uid', $uid)->where('pink_id', $pid)->where('is_del', 0)->value('order_id');
  1420. }
  1421. /**
  1422. * 删除当前用户拼团未支付的订单
  1423. */
  1424. public static function delCombination()
  1425. {
  1426. self::where('combination', '>', 0)->where('paid', 0)->where('uid', User::getActiveUid())->delete();
  1427. }
  1428. public static function getUserPrice($uid = 0)
  1429. {
  1430. if (!$uid) return 0;
  1431. $price = self::where('paid', 1)->where('uid', $uid)->where('status', 2)->where('refund_status', 0)->column('pay_price', 'id');
  1432. $count = 0;
  1433. if ($price) {
  1434. foreach ($price as $v) {
  1435. $count = bcadd($count, $v, 2);
  1436. }
  1437. }
  1438. return $count;
  1439. }
  1440. /**
  1441. * 个人中心获取个人订单列表和订单搜索
  1442. * @param int $uid 用户uid
  1443. * @param int | string 查找订单类型
  1444. * @param int $first 分页
  1445. * @param int 每页显示多少条
  1446. * @param string $search 订单号
  1447. * @return array
  1448. * */
  1449. public static function getUserOrderSearchList($uid, $type, $page, $limit, $search)
  1450. {
  1451. if ($search) {
  1452. $order = self::searchUserOrder($uid, $search) ?: [];
  1453. $list = $order == false ? [] : [$order];
  1454. } else {
  1455. $list = self::getUserOrderList($uid, $type, $page, $limit);
  1456. }
  1457. foreach ($list as $k => $order) {
  1458. $list[$k] = self::tidyOrder($order, true);
  1459. if ($list[$k]['_status']['_type'] == 3) {
  1460. foreach ($order['cartInfo'] ?: [] as $key => $product) {
  1461. $list[$k]['cartInfo'][$key]['is_reply'] = StoreProductReply::isReply($product['unique'], 'product');
  1462. $list[$k]['cartInfo'][$key]['add_time'] = isset($product['add_time']) ? date('Y-m-d H:i', $product['add_time']) : '时间错误';
  1463. }
  1464. }
  1465. }
  1466. return $list;
  1467. }
  1468. /**
  1469. * 获取用户下级的订单
  1470. * @param int $xuid 下级用户用户uid
  1471. * @param int $uid 用户uid
  1472. * @param int $type 订单类型
  1473. * @param int $first 截取行数
  1474. * @param int $limit 展示条数
  1475. * @return array
  1476. * */
  1477. public static function getSubordinateOrderlist($xUid, $uid, $type, $first, $limit)
  1478. {
  1479. $list = [];
  1480. if (!$xUid) {
  1481. $arr = User::getOneSpreadUid($uid);
  1482. foreach ($arr as $v) $list = StoreOrder::getUserOrderList($v, $type, $first, $limit);
  1483. } else $list = self::getUserOrderList($xUid, $type, $first, $limit);
  1484. foreach ($list as $k => $order) {
  1485. $list[$k] = self::tidyOrder($order, true);
  1486. if ($list[$k]['_status']['_type'] == 3) {
  1487. foreach ($order['cartInfo'] ?: [] as $key => $product) {
  1488. $list[$k]['cartInfo'][$key]['is_reply'] = StoreProductReply::isReply($product['unique'], 'product');
  1489. }
  1490. }
  1491. }
  1492. return $list;
  1493. }
  1494. /**
  1495. * 获取 今日 昨日 本月 订单金额
  1496. * @return mixed
  1497. */
  1498. public static function getOrderTimeData()
  1499. {
  1500. $to_day = strtotime(date('Y-m-d'));//今日
  1501. $pre_day = strtotime(date('Y-m-d', strtotime('-1 day')));//昨日
  1502. $now_month = strtotime(date('Y-m'));//本月
  1503. //今日成交额
  1504. // $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;
  1505. $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;
  1506. //今日订单数
  1507. $data['todayCount'] = self::where('is_del', 0)->where('pay_time', '>=', $to_day)->where('paid', 1)->where('refund_status', 0)->count();
  1508. //昨日成交额
  1509. $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;
  1510. //昨日订单数
  1511. $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();
  1512. //本月成交额
  1513. $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;
  1514. //本月订单数
  1515. $data['monthCount'] = self::where('is_del', 0)->where('pay_time', '>=', $now_month)->where('paid', 1)->where('refund_status', 0)->count();
  1516. return $data;
  1517. }
  1518. /**
  1519. * 获取某个用户的订单统计数据
  1520. * @param $uid
  1521. * @return mixed
  1522. */
  1523. public static function getOrderData($uid)
  1524. {
  1525. //订单支付没有退款 数量
  1526. $data['order_count'] = self::where('is_del', 0)->where('paid', 1)->where('uid', $uid)->where('refund_status', 0)->count();
  1527. //订单支付没有退款 支付总金额
  1528. $data['sum_price'] = self::where('is_del', 0)->where('paid', 1)->where('uid', $uid)->where('refund_status', 0)->sum('pay_price');
  1529. //订单待支付 数量
  1530. $data['unpaid_count'] = self::statusByWhere(0, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1531. //订单待发货 数量
  1532. $data['unshipped_count'] = self::statusByWhere(1, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1533. //订单待收货 数量
  1534. $data['received_count'] = self::statusByWhere(2, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1535. //订单待评价 数量
  1536. $data['evaluated_count'] = self::statusByWhere(3, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1537. //订单已完成 数量
  1538. $data['complete_count'] = self::statusByWhere(4, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1539. //订单退款
  1540. $data['refund_count'] = self::statusByWhere(-1, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1541. return $data;
  1542. }
  1543. /**
  1544. * 获取订单统计数据
  1545. * @param $uid
  1546. * @return mixed
  1547. */
  1548. public static function getOrderDataAdmin()
  1549. {
  1550. //订单支付没有退款 数量
  1551. $data['order_count'] = self::where('is_del', 0)->where('paid', 1)->where('refund_status', 0)->count();
  1552. //订单支付没有退款 支付总金额
  1553. $data['sum_price'] = self::where('is_del', 0)->where('paid', 1)->where('refund_status', 0)->sum('pay_price');
  1554. //订单待支付 数量
  1555. $data['unpaid_count'] = self::statusByWhere(0, 0)->where('is_del', 0)->count();
  1556. //订单待发货 数量
  1557. $data['unshipped_count'] = self::statusByWhere(1, 0)->where('is_del', 0)->count();
  1558. //订单待收货 数量
  1559. $data['received_count'] = self::statusByWhere(2, 0)->where('is_del', 0)->count();
  1560. //订单待评价 数量
  1561. $data['evaluated_count'] = self::statusByWhere(3, 0)->where('is_del', 0)->count();
  1562. //订单已完成 数量
  1563. $data['complete_count'] = self::statusByWhere(4, 0)->where('is_del', 0)->count();
  1564. //订单退款 数量
  1565. $data['refund_count'] = self::statusByWhere(-3, 0)->where('is_del', 0)->count();
  1566. return $data;
  1567. }
  1568. /**
  1569. * 累计消费
  1570. * @param $uid
  1571. * @return float
  1572. */
  1573. public static function getOrderStatusSum($uid)
  1574. {
  1575. return self::where('uid', $uid)->where('is_del', 0)->where('paid', 1)->sum('pay_price');
  1576. }
  1577. public static function getPinkOrderId($id)
  1578. {
  1579. return self::where('id', $id)->value('order_id');
  1580. }
  1581. /**
  1582. * 未支付订单自动取消
  1583. * @param int $limit 分页截取条数
  1584. * @param string $prefid 缓存名称
  1585. * @param int $expire 缓存时间
  1586. * @return string|null
  1587. * @throws \Psr\SimpleCache\InvalidArgumentException
  1588. */
  1589. public static function orderUnpaidCancel()
  1590. {
  1591. //系统预设取消订单时间段
  1592. $keyValue = ['order_cancel_time', 'order_activity_time', 'order_bargain_time', 'order_seckill_time', 'order_pink_time'];
  1593. //获取配置
  1594. $systemValue = SystemConfigService::more($keyValue);
  1595. //格式化数据
  1596. $systemValue = self::setValeTime($keyValue, is_array($systemValue) ? $systemValue : []);
  1597. //检查是否有未支付的订单 未支付查询条件
  1598. $unPidCount = self::where('paid', 0)->where('pay_type', '<>', 'offline')->where('is_del', 0)->where('status', 0)->where('refund_status', 0)->count();
  1599. if (!$unPidCount) return null;
  1600. try {
  1601. $res = true;
  1602. // 未支付查询条件
  1603. $orderList = self::where('paid', 0)->where('pay_type', '<>', 'offline')->where('is_del', 0)->where('status', 0)->where('refund_status', 0)->field('add_time,exchange_id,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();
  1604. foreach ($orderList as $order) {
  1605. if ($order['seckill_id']) {
  1606. //优先使用单独配置的过期时间
  1607. $order_seckill_time = $systemValue['order_seckill_time'] ? $systemValue['order_seckill_time'] : $systemValue['order_activity_time'];
  1608. $res = $res && self::RegressionAll($order_seckill_time, $order);
  1609. unset($order_seckill_time);
  1610. } else if ($order['bargain_id']) {
  1611. $order_bargain_time = $systemValue['order_bargain_time'] ? $systemValue['order_bargain_time'] : $systemValue['order_activity_time'];
  1612. $res = $res && self::RegressionAll($order_bargain_time, $order);
  1613. unset($order_bargain_time);
  1614. } else if ($order['pink_id'] || $order['combination_id']) {
  1615. $order_pink_time = $systemValue['order_pink_time'] ? $systemValue['order_pink_time'] : $systemValue['order_activity_time'];
  1616. $res = $res && self::RegressionAll($order_pink_time, $order);
  1617. unset($order_pink_time);
  1618. } else if ($order['exchange_id']) {
  1619. $order_pink_time = $systemValue['order_activity_time'];
  1620. $res = $res && self::RegressionAll($order_pink_time, $order);
  1621. unset($order_pink_time);
  1622. } else {
  1623. $res = $res && self::RegressionAll($systemValue['order_cancel_time'], $order);
  1624. }
  1625. }
  1626. if (!$res) throw new \Exception('更新错误');
  1627. unset($orderList, $res, $pages);
  1628. return null;
  1629. } catch (PDOException $e) {
  1630. Log::error('未支付自动取消时发生数据库查询错误,错误原因为:' . $e->getMessage());
  1631. throw new \Exception($e->getMessage());
  1632. } catch (\think\Exception $e) {
  1633. Log::error('未支付自动取消时发生系统错误,错误原因为:' . $e->getMessage());
  1634. throw new \Exception($e->getMessage());
  1635. }
  1636. }
  1637. /**
  1638. * 未支付订单超过预设时间回退所有,如果不设置未支付过期时间,将不取消订单
  1639. * @param $time 预设时间
  1640. * @param $order 订单详情
  1641. * @return bool
  1642. * @throws DataNotFoundException
  1643. * @throws ModelNotFoundException
  1644. * @throws \think\exception\DbException
  1645. */
  1646. protected static function RegressionAll($time, $order)
  1647. {
  1648. if ($time == 0) return true;
  1649. if (($order['add_time'] + bcmul($time, 3600, 0)) < time()) {
  1650. $res1 = self::RegressionStock($order);
  1651. $res2 = self::RegressionIntegral($order);
  1652. $res3 = self::RegressionCoupon($order);
  1653. $res = $res1 && $res2 && $res3;
  1654. if ($res) $res = false !== self::where('order_id', $order['order_id'])->update(['is_del' => 1, 'mark' => '订单未支付已超过系统预设时间']);
  1655. unset($res1, $res2, $res3);
  1656. return $res;
  1657. } else
  1658. return true;
  1659. }
  1660. /**
  1661. * 格式化数据
  1662. * @param array $array 原本数据键
  1663. * @param $value 需要格式化的数据
  1664. * @param int $default 默认值
  1665. * @return mixed
  1666. */
  1667. protected static function setValeTime(array $array, $value, $default = 0)
  1668. {
  1669. foreach ($array as $item) {
  1670. if (!isset($value[$item]))
  1671. $value[$item] = $default;
  1672. else if (is_string($value[$item]))
  1673. $value[$item] = (float)$value[$item];
  1674. }
  1675. return $value;
  1676. }
  1677. public static function getOrderTotalPrice($cartInfo)
  1678. {
  1679. $totalPrice = 0;
  1680. foreach ($cartInfo as $cart) {
  1681. $totalPrice = bcadd($totalPrice, bcmul($cart['cart_num'], $cart['truePrice'], 2), 2);
  1682. }
  1683. return $totalPrice;
  1684. }
  1685. public static function getOrderCostPrice($cartInfo)
  1686. {
  1687. $costPrice = 0;
  1688. foreach ($cartInfo as $cart) {
  1689. $costPrice = bcadd($costPrice, bcmul($cart['cart_num'], $cart['costPrice'], 2), 2);
  1690. }
  1691. return $costPrice;
  1692. }
  1693. public static function getCombinationOrderCostPrice($cartInfo)
  1694. {
  1695. $costPrice = 0;
  1696. foreach ($cartInfo as $cart) {
  1697. if ($cart['combination_id']) {
  1698. $costPrice = bcadd($costPrice, bcmul($cart['cart_num'], StoreCombination::where('id', $cart['combination_id'])->value('price'), 2), 2);
  1699. }
  1700. }
  1701. return (float)$costPrice;
  1702. }
  1703. public static function yueRefundAfter($order)
  1704. {
  1705. }
  1706. /**
  1707. * 获取余额支付的金额
  1708. * @param $uid
  1709. * @return float|int
  1710. */
  1711. public static function getOrderStatusYueSum($uid)
  1712. {
  1713. return self::where('uid', $uid)->where('is_del', 0)->where('is_del', 0)->where('pay_type', 'yue')->where('paid', 1)->sum('pay_price');
  1714. }
  1715. /**
  1716. * 砍价支付成功订单数量
  1717. * @param $bargain
  1718. * @return int
  1719. */
  1720. public static function getBargainPayCount($bargain)
  1721. {
  1722. return self::where('bargain_id', $bargain)->where(['paid' => 1, 'refund_status' => 0])->count();
  1723. }
  1724. /**
  1725. * 7天自动收货
  1726. * @return bool
  1727. */
  1728. public static function startTakeOrder()
  1729. {
  1730. //7天前时间戳
  1731. $systemDeliveryTime = SystemConfigService::get('system_delivery_time') ?? 0;
  1732. //0为取消自动收货功能
  1733. if ($systemDeliveryTime == 0) return true;
  1734. $sevenDay = strtotime(date('Y-m-d H:i:s', strtotime('-' . $systemDeliveryTime . ' day')));
  1735. $model = new self;
  1736. $model = $model->alias('o');
  1737. $model = $model->join('StoreOrderStatus s', 's.oid=o.id');
  1738. $model = $model->where('o.paid', 1);
  1739. $model = $model->where('s.change_type', 'delivery_goods');
  1740. $model = $model->where('s.change_time', '<', $sevenDay);
  1741. $model = $model->where('o.status', 1);
  1742. $model = $model->where('o.refund_status', 0);
  1743. $model = $model->where('o.is_del', 0);
  1744. $orderInfo = $model->column('id', 'id');
  1745. if (!count($orderInfo)) return true;
  1746. $res = true;
  1747. foreach ($orderInfo as $key => &$item) {
  1748. $order = self::get($item);
  1749. if ($order['status'] == 2) continue;
  1750. if ($order['paid'] == 1 && $order['status'] == 1) $data['status'] = 2;
  1751. else if ($order['pay_type'] == 'offline') $data['status'] = 2;
  1752. else continue;
  1753. if (!self::edit($data, $item, 'id')) continue;
  1754. try {
  1755. OrderRepository::storeProductOrderTakeDeliveryAdmin($order, $item);
  1756. $res = $res && true;
  1757. } catch (\Exception $e) {
  1758. $res = $res && false;
  1759. }
  1760. $res = $res && StoreOrderStatus::status($item, 'take_delivery', '已收货[自动收货]');
  1761. }
  1762. if (!$res) {
  1763. throw new \Exception('');
  1764. }
  1765. }
  1766. /**
  1767. * 获取订单信息
  1768. * @param $id
  1769. * @param string $field
  1770. * @return array|null|\think\Model
  1771. * @throws DataNotFoundException
  1772. * @throws ModelNotFoundException
  1773. * @throws \think\exception\DbException
  1774. */
  1775. public static function getOrderInfo($id, $field = 'order_id')
  1776. {
  1777. return self::where('id', $id)->field($field)->find();
  1778. }
  1779. /**
  1780. * 订单每月统计数据
  1781. * @param $page
  1782. * @param $limit
  1783. * @return array
  1784. */
  1785. public static function getOrderDataPriceCount($page, $limit, $start, $stop)
  1786. {
  1787. if (!$limit) return [];
  1788. $model = new self;
  1789. if ($start != '' && $stop != '') $model = $model->where('pay_time', '>', $start)->where('pay_time', '<=', $stop);
  1790. $model = $model->field('sum(pay_price) as price,count(id) as count,FROM_UNIXTIME(pay_time, \'%m-%d\') as time');
  1791. $model = $model->where('is_del', 0);
  1792. $model = $model->where('paid', 1);
  1793. $model = $model->where('refund_status', 0);
  1794. $model = $model->group("FROM_UNIXTIME(pay_time, '%Y-%m-%d')");
  1795. $model = $model->order('pay_time DESC');
  1796. if ($page) $model = $model->page($page, $limit);
  1797. return $model->select();
  1798. }
  1799. /**
  1800. * 前台订单管理订单列表获取
  1801. * @param $where
  1802. * @return mixed
  1803. */
  1804. public static function orderList($where)
  1805. {
  1806. $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');
  1807. if ($where['order'] != '') {
  1808. $model = $model->order(self::setOrder($where['order']));
  1809. } else {
  1810. $model = $model->order('a.id desc');
  1811. }
  1812. $data = ($data = $model->page((int)$where['page'], (int)$where['limit'])->select()) && count($data) ? $data->toArray() : [];
  1813. return self::tidyAdminOrder($data);
  1814. }
  1815. /**
  1816. * 前台订单管理 订单信息设置
  1817. * @param $data
  1818. * @param bool $status
  1819. * @return mixed
  1820. * @throws DataNotFoundException
  1821. * @throws ModelNotFoundException
  1822. * @throws \think\exception\DbException
  1823. */
  1824. public static function tidyAdminOrder($data, $status = false)
  1825. {
  1826. foreach ($data as &$item) {
  1827. $_info = StoreOrderCartInfo::where('oid', $item['id'])->field('cart_info')->select()->toArray();
  1828. foreach ($_info as $k => $v) {
  1829. if (!is_array($v['cart_info']))
  1830. $_info[$k]['cart_info'] = json_decode($v['cart_info'], true);
  1831. }
  1832. foreach ($_info as $k => $v) {
  1833. 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']);
  1834. $_info[$k]['cart_info']['productInfo']['suk'] = '';
  1835. if (isset($v['cart_info']['productInfo']['attrInfo'])) {
  1836. $_info[$k]['cart_info']['productInfo']['image'] = $_info[$k]['cart_info']['productInfo']['attrInfo']['image'];
  1837. $_info[$k]['cart_info']['productInfo']['price'] = $_info[$k]['cart_info']['productInfo']['attrInfo']['price'];
  1838. $_info[$k]['cart_info']['productInfo']['suk'] = $_info[$k]['cart_info']['productInfo']['attrInfo']['suk'];
  1839. unset($_info[$k]['cart_info']['productInfo']['attrInfo']);
  1840. }
  1841. if (!isset($v['cart_info']['productInfo']['ot_price'])) {
  1842. $_info[$k]['cart_info']['productInfo']['ot_price'] = $v['cart_info']['productInfo']['price'];
  1843. }
  1844. }
  1845. $item['_info'] = $_info;
  1846. $item['add_time'] = date('Y-m-d H:i:s', $item['add_time']);
  1847. // if($item['pink_id'] || $item['combination_id']){
  1848. // $pinkStatus = StorePink::where('order_id_key',$item['id'])->value('status');
  1849. // switch ($pinkStatus){
  1850. // case 1:
  1851. // $item['pink_name'] = '[拼团订单]正在进行中';
  1852. // $item['color'] = '#f00';
  1853. // break;
  1854. // case 2:
  1855. // $item['pink_name'] = '[拼团订单]已完成';
  1856. // $item['color'] = '#00f';
  1857. // break;
  1858. // case 3:
  1859. // $item['pink_name'] = '[拼团订单]未完成';
  1860. // $item['color'] = '#f0f';
  1861. // break;
  1862. // default:
  1863. // $item['pink_name'] = '[拼团订单]历史订单';
  1864. // $item['color'] = '#457856';
  1865. // break;
  1866. // }
  1867. // }elseif ($item['seckill_id']){
  1868. // $item['pink_name'] = '[秒杀订单]';
  1869. // $item['color'] = '#32c5e9';
  1870. // }elseif ($item['bargain_id']){
  1871. // $item['pink_name'] = '[砍价订单]';
  1872. // $item['color'] = '#12c5e9';
  1873. // }else{
  1874. // $item['pink_name'] = '[普通订单]';
  1875. // $item['color'] = '#895612';
  1876. // }
  1877. // if($item['paid']==1){
  1878. // switch ($item['pay_type']){
  1879. // case 'weixin':
  1880. // $item['pay_type_name']='微信支付';
  1881. // break;
  1882. // case 'yue':
  1883. // $item['pay_type_name']='余额支付';
  1884. // break;
  1885. // case 'offline':
  1886. // $item['pay_type_name']='线下支付';
  1887. // break;
  1888. // default:
  1889. // $item['pay_type_name']='其他支付';
  1890. // break;
  1891. // }
  1892. // }else{
  1893. // switch ($item['pay_type']){
  1894. // default:
  1895. // $item['pay_type_name']='未支付';
  1896. // break;
  1897. // case 'offline':
  1898. // $item['pay_type_name']='线下支付';
  1899. // $item['pay_type_info']=1;
  1900. // break;
  1901. // }
  1902. // }
  1903. if ($status) {
  1904. $status = [];
  1905. if (!$item['paid'] && $item['pay_type'] == 'offline' && !$item['status'] >= 2) {
  1906. $status['_type'] = 9;
  1907. $status['_title'] = '线下付款';
  1908. $status['_msg'] = '商家处理中,请耐心等待';
  1909. $status['_class'] = 'nobuy';
  1910. } else if (!$item['paid']) {
  1911. $status['_type'] = 0;
  1912. $status['_title'] = '未支付';
  1913. //系统预设取消订单时间段
  1914. $keyValue = ['order_cancel_time', 'order_activity_time', 'order_bargain_time', 'order_seckill_time', 'order_pink_time'];
  1915. //获取配置
  1916. $systemValue = SystemConfigService::more($keyValue);
  1917. //格式化数据
  1918. $systemValue = self::setValeTime($keyValue, is_array($systemValue) ? $systemValue : []);
  1919. if ($item['pink_id'] || $item['combination_id']) {
  1920. $order_pink_time = $systemValue['order_pink_time'] ? $systemValue['order_pink_time'] : $systemValue['order_activity_time'];
  1921. $time = bcadd($item['add_time'], $order_pink_time * 3600, 0);
  1922. $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
  1923. } else if ($item['seckill_id']) {
  1924. $order_seckill_time = $systemValue['order_seckill_time'] ? $systemValue['order_seckill_time'] : $systemValue['order_activity_time'];
  1925. $time = bcadd($item['add_time'], $order_seckill_time * 3600, 0);
  1926. $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
  1927. } else if ($item['bargain_id']) {
  1928. $order_bargain_time = $systemValue['order_bargain_time'] ? $systemValue['order_bargain_time'] : $systemValue['order_activity_time'];
  1929. $time = bcadd($item['add_time'], $order_bargain_time * 3600, 0);
  1930. $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
  1931. } else {
  1932. $time = bcadd($item['add_time'], $systemValue['order_cancel_time'] * 3600, 0);
  1933. $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
  1934. }
  1935. $status['_class'] = 'nobuy';
  1936. } else if ($item['refund_status'] == 1) {
  1937. $status['_type'] = -1;
  1938. $status['_title'] = '申请退款中';
  1939. $status['_msg'] = '商家审核中,请耐心等待';
  1940. $status['_class'] = 'state-sqtk';
  1941. } else if ($item['refund_status'] == 2) {
  1942. $status['_type'] = -2;
  1943. $status['_title'] = '已退款';
  1944. $status['_msg'] = '已为您退款,感谢您的支持';
  1945. $status['_class'] = 'state-sqtk';
  1946. } else if (!$item['status']) {
  1947. if ($item['pink_id']) {
  1948. if (StorePink::where('id', $item['pink_id'])->where('status', 1)->count()) {
  1949. $status['_type'] = 11;
  1950. $status['_title'] = '拼团中';
  1951. $status['_msg'] = '等待其他人参加拼团';
  1952. $status['_class'] = 'state-nfh';
  1953. } else {
  1954. $status['_type'] = 1;
  1955. $status['_title'] = '未发货';
  1956. $status['_msg'] = '商家未发货,请耐心等待';
  1957. $status['_class'] = 'state-nfh';
  1958. }
  1959. } else {
  1960. $status['_type'] = 1;
  1961. $status['_title'] = '未发货';
  1962. $status['_msg'] = '商家未发货,请耐心等待';
  1963. $status['_class'] = 'state-nfh';
  1964. }
  1965. } else if ($item['status'] == 1) {
  1966. if ($item['delivery_type'] == 'send') {//TODO 送货
  1967. $status['_type'] = 2;
  1968. $status['_title'] = '待收货';
  1969. $status['_msg'] = date('m月d日H时i分', StoreOrderStatus::getTime($item['id'], 'delivery')) . '服务商已送货';
  1970. $status['_class'] = 'state-ysh';
  1971. } else {//TODO 发货
  1972. $status['_type'] = 2;
  1973. $status['_title'] = '待收货';
  1974. $status['_msg'] = date('m月d日H时i分', StoreOrderStatus::getTime($item['id'], 'delivery_goods')) . '服务商已发货';
  1975. $status['_class'] = 'state-ysh';
  1976. }
  1977. } else if ($item['status'] == 2) {
  1978. $status['_type'] = 3;
  1979. $status['_title'] = '待评价';
  1980. $status['_msg'] = '已收货,快去评价一下吧';
  1981. $status['_class'] = 'state-ypj';
  1982. } else if ($item['status'] == 3) {
  1983. $status['_type'] = 4;
  1984. $status['_title'] = '交易完成';
  1985. $status['_msg'] = '交易完成,感谢您的支持';
  1986. $status['_class'] = 'state-ytk';
  1987. }
  1988. if (isset($item['pay_type']))
  1989. $status['_payType'] = isset(self::$payType[$item['pay_type']]) ? self::$payType[$item['pay_type']] : '其他方式';
  1990. if (isset($item['delivery_type']))
  1991. $status['_deliveryType'] = isset(self::$deliveryType[$item['delivery_type']]) ? self::$deliveryType[$item['delivery_type']] : '其他方式';
  1992. $item['_status'] = $status;
  1993. } else {
  1994. if ($item['paid'] == 0 && $item['status'] == 0) {
  1995. $item['status_name'] = '未支付';
  1996. } else if ($item['paid'] == 1 && $item['status'] == 0 && $item['refund_status'] == 0) {
  1997. $item['status_name'] = '未发货';
  1998. } else if ($item['paid'] == 1 && $item['status'] == 1 && $item['refund_status'] == 0) {
  1999. $item['status_name'] = '待收货';
  2000. } else if ($item['paid'] == 1 && $item['status'] == 2 && $item['refund_status'] == 0) {
  2001. $item['status_name'] = '待评价';
  2002. } else if ($item['paid'] == 1 && $item['status'] == 3 && $item['refund_status'] == 0) {
  2003. $item['status_name'] = '已完成';
  2004. }
  2005. }
  2006. // unset($item['refund_status']);
  2007. // else if($item['paid']==1 && $item['refund_status']==1){
  2008. // $item['status_name']=<<<HTML
  2009. //<b style="color:#f124c7">申请退款</b><br/>
  2010. //<span>退款原因:{$item['refund_reason_wap']}</span>
  2011. //HTML;
  2012. // }else if($item['paid']==1 && $item['refund_status']==2){
  2013. // $item['status_name']='已退款';
  2014. // }
  2015. // if($item['paid']==0 && $item['status']==0 && $item['refund_status']==0){
  2016. // $item['_status']=1;
  2017. // }else if($item['paid']==1 && $item['status']==0 && $item['refund_status']==0){
  2018. // $item['_status']=2;
  2019. // }else if($item['paid']==1 && $item['refund_status']==1){
  2020. // $item['_status']=3;
  2021. // }else if($item['paid']==1 && $item['status']==1 && $item['refund_status']==0){
  2022. // $item['_status']=4;
  2023. // }else if($item['paid']==1 && $item['status']==2 && $item['refund_status']==0){
  2024. // $item['_status']=5;
  2025. // }else if($item['paid']==1 && $item['status']==3 && $item['refund_status']==0){
  2026. // $item['_status']=6;
  2027. // }else if($item['paid']==1 && $item['refund_status']==2){
  2028. // $item['_status']=7;
  2029. // }
  2030. }
  2031. return $data;
  2032. }
  2033. /**
  2034. * 处理where条件
  2035. * @param $where
  2036. * @param $model
  2037. * @param string $aler
  2038. * @param string $join
  2039. * @return StoreOrder|null
  2040. */
  2041. public static function getOrderWhere($where, $model, $aler = '', $join = '')
  2042. {
  2043. if (isset($where['status']) && $where['status'] != '') $model = self::statusWhere($where['status'], $model, $aler);
  2044. if (isset($where['is_del']) && $where['is_del'] != '' && $where['is_del'] != -1) $model = $model->where($aler . 'is_del', $where['is_del']);
  2045. if (isset($where['combination_id'])) {
  2046. if ($where['combination_id'] == '普通订单') {
  2047. $model = $model->where($aler . 'combination_id', 0)->where($aler . 'seckill_id', 0)->where($aler . 'bargain_id', 0);
  2048. }
  2049. if ($where['combination_id'] == '拼团订单') {
  2050. $model = $model->where($aler . 'combination_id', ">", 0)->where($aler . 'pink_id', ">", 0);
  2051. }
  2052. if ($where['combination_id'] == '秒杀订单') {
  2053. $model = $model->where($aler . 'seckill_id', ">", 0);
  2054. }
  2055. if ($where['combination_id'] == '砍价订单') {
  2056. $model = $model->where($aler . 'bargain_id', ">", 0);
  2057. }
  2058. }
  2059. if (isset($where['type'])) {
  2060. switch ($where['type']) {
  2061. case 1:
  2062. $model = $model->where($aler . 'combination_id', 0)->where($aler . 'seckill_id', 0)->where($aler . 'bargain_id', 0);
  2063. break;
  2064. case 2:
  2065. $model = $model->where($aler . 'combination_id', ">", 0);
  2066. break;
  2067. case 3:
  2068. $model = $model->where($aler . 'seckill_id', ">", 0);
  2069. break;
  2070. case 4:
  2071. $model = $model->where($aler . 'bargain_id', ">", 0);
  2072. break;
  2073. }
  2074. }
  2075. if (isset($where['real_name']) && $where['real_name'] != '')
  2076. $model = $model->where($aler . 'order_id|' . $aler . 'real_name|' . $aler . 'user_phone' . ($join ? '|' . $join . '.nickname|' . $join . '.uid' : ''), 'LIKE', "%$where[real_name]%");
  2077. if (isset($where['data']) && $where['data'] !== '')
  2078. $model = self::getModelTime($where, $model, $aler . 'add_time');
  2079. return $model;
  2080. }
  2081. /**
  2082. * 设置where条件
  2083. * @param $status
  2084. * @param null $model
  2085. * @param string $alert
  2086. * @return StoreOrder|null
  2087. */
  2088. public static function statusWhere($status, $model = null, $alert = '')
  2089. {
  2090. if ($model == null) $model = new self;
  2091. if ('' === $status)
  2092. return $model;
  2093. else if ($status == 0)//未支付
  2094. return $model->where($alert . 'paid', 0)->where($alert . 'status', 0)->where($alert . 'refund_status', 0);
  2095. else if ($status == 1)//已支付 未发货
  2096. return $model->where($alert . 'paid', 1)->where($alert . 'status', 0)->where($alert . 'refund_status', 0);
  2097. else if ($status == 2)//已支付 待收货
  2098. return $model->where($alert . 'paid', 1)->where($alert . 'status', 1)->where($alert . 'refund_status', 0);
  2099. else if ($status == 3)// 已支付 已收货 待评价
  2100. return $model->where($alert . 'paid', 1)->where($alert . 'status', 2)->where($alert . 'refund_status', 0);
  2101. else if ($status == 4)// 交易完成
  2102. return $model->where($alert . 'paid', 1)->where($alert . 'status', 3)->where($alert . 'refund_status', 0);
  2103. else if ($status == -1)//退款中
  2104. return $model->where($alert . 'paid', 1)->where($alert . 'refund_status', 1);
  2105. else if ($status == -2)//已退款
  2106. return $model->where($alert . 'paid', 1)->where($alert . 'refund_status', 2);
  2107. else if ($status == -3)//退款
  2108. return $model->where($alert . 'paid', 1)->where($alert . 'refund_status', 'in', '1,2');
  2109. else
  2110. return $model;
  2111. }
  2112. /**
  2113. * 订单详情 管理员
  2114. * @param $orderId
  2115. * @param string $field
  2116. * @return array|null|\think\Model
  2117. * @throws DataNotFoundException
  2118. * @throws ModelNotFoundException
  2119. * @throws \think\exception\DbException
  2120. */
  2121. public static function getAdminOrderDetail($orderId, $field = '*')
  2122. {
  2123. return self::where('order_id', $orderId)->field($field)->find();
  2124. }
  2125. /**
  2126. * 获取指定时间区间的支付金额 管理员
  2127. * @param $start
  2128. * @param $stop
  2129. * @return float
  2130. */
  2131. public static function getOrderTimeBusinessVolumePrice($start, $stop)
  2132. {
  2133. return self::where('is_del', 0)->where('paid', 1)->where('refund_status', 0)->where('add_time', '>=', $start)->where('add_time', '<', $stop)->sum('pay_price');
  2134. }
  2135. /**
  2136. * 获取指定时间区间的支付订单数量 管理员
  2137. * @param $start
  2138. * @param $stop
  2139. * @return float
  2140. */
  2141. public static function getOrderTimeBusinessVolumeNumber($start, $stop)
  2142. {
  2143. return self::where('is_del', 0)->where('paid', 1)->where('refund_status', 0)->where('add_time', '>=', $start)->where('add_time', '<', $stop)->count();
  2144. }
  2145. /**
  2146. * 获取当前时间到指定时间的支付金额 管理员
  2147. * @param $start 开始时间
  2148. * @param $stop 结束时间
  2149. * @return mixed
  2150. */
  2151. public static function chartTimePrice($start, $stop)
  2152. {
  2153. $model = new self;
  2154. $model = $model->field('sum(pay_price) as num,FROM_UNIXTIME(add_time, \'%Y-%m-%d\') as time');
  2155. $model = $model->where('is_del', 0);
  2156. $model = $model->where('paid', 1);
  2157. $model = $model->where('refund_status', 0);
  2158. $model = $model->where('add_time', '>=', $start);
  2159. $model = $model->where('add_time', '<', $stop);
  2160. $model = $model->group("FROM_UNIXTIME(add_time, '%Y-%m-%d')");
  2161. $model = $model->order('add_time ASC');
  2162. return $model->select();
  2163. }
  2164. /**
  2165. * 获取当前时间到指定时间的支付订单数 管理员
  2166. * @param $start 开始时间
  2167. * @param $stop 结束时间
  2168. * @return mixed
  2169. */
  2170. public static function chartTimeNumber($start, $stop)
  2171. {
  2172. $model = new self;
  2173. $model = $model->field('count(id) as num,FROM_UNIXTIME(add_time, \'%Y-%m-%d\') as time');
  2174. $model = $model->where('is_del', 0);
  2175. $model = $model->where('paid', 1);
  2176. $model = $model->where('refund_status', 0);
  2177. $model = $model->where('add_time', '>=', $start);
  2178. $model = $model->where('add_time', '<', $stop);
  2179. $model = $model->group("FROM_UNIXTIME(add_time, '%Y-%m-%d')");
  2180. $model = $model->order('add_time ASC');
  2181. return $model->select();
  2182. }
  2183. /**
  2184. * 修改支付方式为线下支付
  2185. * @param $orderId
  2186. * @return bool
  2187. */
  2188. public static function setOrderTypePayOffline($orderId)
  2189. {
  2190. return self::edit(['pay_type' => 'offline'], $orderId, 'order_id');
  2191. }
  2192. /**
  2193. * 线下付款
  2194. * @param $id
  2195. * @return $this
  2196. */
  2197. public static function updateOffline($id)
  2198. {
  2199. $count = self::where('id', $id)->count();
  2200. if (!$count) return self::setErrorInfo('订单不存在');
  2201. $count = self::where('id', $id)->where('paid', 0)->count();
  2202. if (!$count) return self::setErrorInfo('订单已支付');
  2203. $res = self::where('id', $id)->update(['paid' => 1, 'pay_time' => time()]);
  2204. return $res;
  2205. }
  2206. /**
  2207. * 向创建订单10分钟未付款的用户发送短信
  2208. */
  2209. public static function sendTen()
  2210. {
  2211. $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');
  2212. foreach ($list as $phone) {
  2213. ShortLetterRepositories::send(true, $phone, [], 'ORDER_PAY_FALSE');
  2214. }
  2215. }
  2216. public function productInfo()
  2217. {
  2218. return $this->hasMany(StoreProductReply::class, 'oid', 'id');
  2219. }
  2220. public static function setOrderProductReplyWhere($where)
  2221. {
  2222. $model = self::where('status', 3)->order('add_time desc')->whereIn('id', function ($query) {
  2223. $query->name('store_order')->alias('o')->join('store_product_reply a', 'a.oid = o.id')->group('o.id')->field('o.id')->select();
  2224. })->with('productInfo', function ($query) use ($where) {
  2225. $alias = '';
  2226. if (isset($where['title']) && $where['title'] != '')
  2227. $query->where("{$alias}comment", 'LIKE', "%$where[title]%");
  2228. if (isset($where['is_reply']) && $where['is_reply'] != '') {
  2229. if ($where['is_reply'] >= 0) {
  2230. $query->where("{$alias}is_reply", $where['is_reply']);
  2231. } else {
  2232. $query->where("{$alias}is_reply", '>', 0);
  2233. }
  2234. }
  2235. if (isset($where['producr_id']) && $where['producr_id'] != 0)
  2236. $query->where($alias . 'product_id', $where['producr_id']);
  2237. $query->where("{$alias}is_del", 0);
  2238. });
  2239. return $model;
  2240. }
  2241. public static function getOrderProductReplyList($where)
  2242. {
  2243. $list = self::setOrderProductReplyWhere($where)->page((int)$where['message_page'], (int)$where['limit'])->select();
  2244. $list = count($list) ? $list->toArray() : [];
  2245. foreach ($list as $key => $item) {
  2246. if (isset($item['productInfo']) && is_array($item['productInfo']) && count($item['productInfo'])) {
  2247. foreach ($item['productInfo'] as $k => $v) {
  2248. if (!$v['nickname'] && $v['uid']) {
  2249. $v['nickname'] = User::where('uid', $v['uid'])->value('nickname');
  2250. $v['avatar'] = User::where('uid', $v['uid'])->value('avatar');
  2251. }
  2252. $v['image'] = '';
  2253. $v['store_name'] = '';
  2254. if ($v['product_id']) {
  2255. $product = StoreProduct::where('id', $v['product_id'])->field(['image', 'store_name'])->find();
  2256. if ($product) {
  2257. $v['image'] = $product['image'];
  2258. $v['store_name'] = $product['store_name'];
  2259. }
  2260. }
  2261. $list[$key]['productInfo'][$k] = $v;
  2262. }
  2263. }
  2264. }
  2265. $count = self::setOrderProductReplyWhere($where)->count();
  2266. return compact('list', 'count');
  2267. }
  2268. public static function sendProductReturn()
  2269. {
  2270. $uids = self::where('status', '>=', 2)->where('paid', 1)
  2271. ->where('is_del', 0)->where('is_system_del', 0)
  2272. ->where('refund_status', 0)->group('uid')->field('uid,count(id)')->select();
  2273. try {
  2274. $res = true;
  2275. foreach ($uids as $v) {
  2276. if (StoreProductReturnLog::where('uid', $v['uid'])->whereTime('add_time', 'today')->find()) {
  2277. continue;
  2278. }
  2279. $send = [];
  2280. $orders = self::where('status', '>=', 2)->where('paid', 1)
  2281. ->where('is_del', 0)->where('is_system_del', 0)
  2282. ->where('refund_status', 0)->where('uid', $v['uid'])->column('id');
  2283. $store_cart_info = StoreOrderCartInfo::where('oid', 'in', $orders)->where('take', 1)->where('paid', 1)->select();
  2284. foreach ($store_cart_info as $vv) {
  2285. 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()))) {
  2286. continue;
  2287. }
  2288. if (isset($send[$vv['return_money_type']])) {
  2289. $send[$vv['return_money_type']] = bcadd($send[$vv['return_money_type']], bcdiv($vv['return_money'], $vv['return_day'], 8), 8);
  2290. } else {
  2291. $send[$vv['return_money_type']] = bcdiv($vv['return_money'], $vv['return_day'], 8);
  2292. }
  2293. $res = $res && StoreOrderCartInfo::where('oid', $vv['oid'])
  2294. ->where('cart_id', $vv['cart_id'])
  2295. ->inc('returned_day', 1)->update();
  2296. }
  2297. foreach ($send as $kk => $vv) {
  2298. if ($kk == 'now_money' || $kk == 'integral' || $kk == 'brokerage_price') {
  2299. $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, '商城每日返还');
  2300. $res = $res && User::where('uid', $v['uid'])->inc($kk, (float)$vv)->update();
  2301. } else {
  2302. $res = $res && UserMoney::incomeMoney($v['uid'], $kk, $vv, 'product_return', '商城返还', '商城每日返还');
  2303. }
  2304. }
  2305. $res = $res && StoreProductReturnLog::create(['uid' => $v['uid'], 'add_time' => time()]);
  2306. }
  2307. return $res;
  2308. } catch (\Exception $e) {
  2309. return self::setErrorInfo($e->getMessage());
  2310. }
  2311. }
  2312. public static function returnAreaPrice()
  2313. {
  2314. if (AreaReturnLog::whereTime('add_time', 'month')->find()) {
  2315. return true;
  2316. }
  2317. $uids = User::where('area_admin', '>', 0)->select();
  2318. $province_admin_ratio = sys_config('province_admin_ratio', 0);
  2319. $city_admin_ratio = sys_config('city_admin_ratio', 0);
  2320. $district_admin_ratio = sys_config('district_admin_ratio', 0);
  2321. $level_count = [];
  2322. $level_counts = User::where('area_admin', '>', 0)->group('area_admin')->field('area_admin,count(uid) as count')->select();
  2323. foreach ($level_counts as $v) {
  2324. $level_count[$v['area_admin']] = $v['count'];
  2325. }
  2326. try {
  2327. $res = true;
  2328. foreach ($uids as $v) {
  2329. $orders = self::where('status', '>=', 2)
  2330. ->where('paid', 1)
  2331. ->where('is_del', 0)
  2332. ->where('combination_id', 0)
  2333. ->where('seckill_id', 0)
  2334. ->where('bargain_id', 0)
  2335. ->where('exchange_id', 0)
  2336. ->where('shipping_type', 1)
  2337. ->where('is_system_del', 0)
  2338. ->whereTime('pay_time', 'last month')
  2339. ->where('refund_status', 0);
  2340. if (!in_array($v['area_admin'], [1, 2, 3])) continue;
  2341. $ratio = 0;
  2342. $name = 0;
  2343. switch ($v['area_admin']) {
  2344. case 1:
  2345. $orders = $orders->where('province', $v['area_province'])
  2346. ->where('city', $v['area_city'])
  2347. ->where('district', $v['area_district']);
  2348. $ratio = $district_admin_ratio;
  2349. $name = '区代';
  2350. break;
  2351. case 2:
  2352. $orders = $orders->where('province', $v['area_province'])
  2353. ->where('city', $v['area_city']);
  2354. $ratio = $city_admin_ratio;
  2355. $name = '市代';
  2356. break;
  2357. case 3:
  2358. $orders = $orders->where('province', $v['area_province']);
  2359. $ratio = $province_admin_ratio;
  2360. $name = '省代';
  2361. break;
  2362. default:
  2363. break;
  2364. }
  2365. if ($ratio <= 0) continue;
  2366. $orders = $orders->sum('pay_price');
  2367. $brokerage_ratio = bcdiv($ratio, 100, 3);
  2368. $brokerage = bcmul($brokerage_ratio, $orders, 3);
  2369. $brokerage = bcdiv($brokerage, $level_count[$v['area_admin']], 2);
  2370. if ($brokerage > 0) {
  2371. $res = $res && UserBill::income($name . '区域代理月分红', $v['uid'], 'now_money', 'brokerage', $brokerage, 0, bcadd($v['brokerage_price'], $brokerage, 2), $name . '区域代理分红');
  2372. $res = $res && User::where('uid', $v['uid'])->inc('brokerage_price', $brokerage)->update();
  2373. Message::addMessage($v['uid'], '本月' . $name . '区域代理分红已发放,请查收!', 200);
  2374. }
  2375. }
  2376. return $res && AreaReturnLog::create(['add_time' => time()]);
  2377. } catch (\Exception $e) {
  2378. return self::setErrorInfo($e->getMessage());
  2379. }
  2380. }
  2381. public static function returnPartnerPrice()
  2382. {
  2383. if (PartnerReturnLog::whereTime('add_time', 'month')->find()) {
  2384. return true;
  2385. }
  2386. $uids = User::where('partner_level', '>', 0)->select();
  2387. $partner = sys_data('partner_level');
  2388. $level_count = [];
  2389. $level_counts = User::where('partner_level', '>', 0)->group('partner_level')->field('partner_level,count(uid) as count')->select();
  2390. foreach ($level_counts as $v) {
  2391. $level_count[$v['partner_level']] = $v['count'];
  2392. }
  2393. try {
  2394. $res = true;
  2395. foreach ($uids as $v) {
  2396. $orders = self::where('status', '>=', 2)
  2397. ->where('paid', 1)
  2398. ->where('is_del', 0)
  2399. ->where('combination_id', 0)
  2400. ->where('seckill_id', 0)
  2401. ->where('bargain_id', 0)
  2402. ->where('exchange_id', 0)
  2403. ->where('shipping_type', 1)
  2404. ->where('is_system_del', 0)
  2405. ->whereTime('pay_time', 'last month')
  2406. ->where('refund_status', 0)
  2407. ->sum('pay_price');
  2408. $ratio = 0;
  2409. $name = '';
  2410. foreach ($partner as $vv) {
  2411. if ($vv['value'] == $v['partner_level']) {
  2412. $ratio = $vv['ratio'];
  2413. $name = $vv['name'];
  2414. }
  2415. }
  2416. if ($ratio <= 0) continue;
  2417. $brokerage_ratio = bcdiv($ratio, 100, 3);
  2418. $brokerage = bcmul($brokerage_ratio, $orders, 3);
  2419. $brokerage = bcdiv($brokerage, $level_count[$v['partner_level']], 2);
  2420. if ($brokerage > 0) {
  2421. $res = $res && UserBill::income($name . '月分红', $v['uid'], 'now_money', 'brokerage', $brokerage, 0, bcadd($v['brokerage_price'], $brokerage), $name . '分红');
  2422. $res = $res && User::where('uid', $v['uid'])->inc('brokerage_price', $brokerage)->update();
  2423. Message::addMessage($v['uid'], '本月' . $name . '分红已发放,请查收!', 200);
  2424. }
  2425. }
  2426. return $res && PartnerReturnLog::create(['add_time' => time()]);
  2427. } catch (\Exception $e) {
  2428. return self::setErrorInfo($e->getMessage());
  2429. }
  2430. }
  2431. }