StoreOrder.php 84 KB

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