StoreOrder.php 95 KB

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