StoreOrder.php 121 KB

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