StoreOrder.php 109 KB

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