StoreOrder.php 101 KB

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