StoreOrder.php 106 KB

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