StoreOrder.php 123 KB

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