StoreOrder.php 111 KB

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