StoreOrder.php 95 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116
  1. <?php
  2. /**
  3. *
  4. * @author: xaboy<365615158@qq.com>
  5. * @day: 2017/12/20
  6. */
  7. namespace app\models\store;
  8. use app\admin\model\system\ShippingTemplatesFree;
  9. use app\admin\model\system\ShippingTemplatesRegion;
  10. use crmeb\basic\BaseModel;
  11. use think\db\exception\DataNotFoundException;
  12. use think\db\exception\DbException;
  13. use think\db\exception\ModelNotFoundException;
  14. use think\facade\Cache;
  15. use crmeb\traits\ModelTrait;
  16. use think\facade\Log;
  17. use app\models\system\SystemStore;
  18. use app\models\routine\RoutineTemplate;
  19. use app\models\user\{User, UserAddress, UserBill, UserSpread, WechatUser};
  20. use crmeb\services\{
  21. SystemConfigService, WechatTemplateService, workerman\ChannelService
  22. };
  23. use crmeb\repositories\{
  24. GoodsRepository, PaymentRepositories, OrderRepository, ShortLetterRepositories, UserRepository
  25. };
  26. use app\admin\model\system\ShippingTemplates;
  27. /**
  28. * TODO 订单Model
  29. * Class StoreOrder
  30. * @package app\models\store
  31. */
  32. class StoreOrder extends BaseModel
  33. {
  34. /**
  35. * 数据表主键
  36. * @var string
  37. */
  38. protected $pk = 'id';
  39. /**
  40. * 模型名称
  41. * @var string
  42. */
  43. protected $name = 'store_order';
  44. use ModelTrait;
  45. protected $insert = ['add_time'];
  46. protected static $payType = ['weixin' => '微信支付', 'yue' => '余额支付', 'offline' => '线下支付'];
  47. protected static $deliveryType = ['send' => '商家配送', 'express' => '快递配送'];
  48. protected function setAddTimeAttr()
  49. {
  50. return time();
  51. }
  52. protected function setCartIdAttr($value)
  53. {
  54. return is_array($value) ? json_encode($value) : $value;
  55. }
  56. protected function getCartIdAttr($value)
  57. {
  58. return json_decode($value, true);
  59. }
  60. /**获取订单组信息
  61. * @param $cartInfo
  62. * @return array
  63. */
  64. public static function getOrderPriceGroup($cartInfo, $addr)
  65. {
  66. $storeFreePostage = floatval(sys_config('store_free_postage')) ?: 0;//满额包邮
  67. $totalPrice = self::getOrderSumPrice($cartInfo, 'truePrice');//获取订单总金额
  68. $costPrice = self::getOrderSumPrice($cartInfo, 'costPrice');//获取订单成本价
  69. $vipPrice = self::getOrderSumPrice($cartInfo, 'vip_truePrice');//获取订单会员优惠金额
  70. //如果满额包邮等于0
  71. if (!$storeFreePostage) {
  72. $storePostage = 0;
  73. } else {
  74. if ($addr) {
  75. //按照运费模板计算每个运费模板下商品的件数/重量/体积以及总金额 按照首重倒序排列
  76. $temp_num = [];
  77. foreach ($cartInfo as $cart) {
  78. $temp = ShippingTemplates::get($cart['productInfo']['temp_id']);
  79. if (!$temp) $temp = ShippingTemplates::get(1);
  80. if ($temp->getData('type') == 1) {
  81. $num = $cart['cart_num'];
  82. } elseif ($temp->getData('type') == 2) {
  83. $num = $cart['cart_num'] * $cart['productInfo']['attrInfo']['weight'];
  84. } else {
  85. $num = $cart['cart_num'] * $cart['productInfo']['attrInfo']['volume'];
  86. }
  87. $region = ShippingTemplatesRegion::where('temp_id', $cart['productInfo']['temp_id'])->where('city_id', $addr['city_id'])->find();
  88. if (!$region) $region = ShippingTemplatesRegion::where('temp_id', $cart['productInfo']['temp_id'])->where('city_id', 0)->find();
  89. if (!$region) $region = ShippingTemplatesRegion::where('temp_id', 1)->where('city_id', 0)->find();
  90. if (!$region) {
  91. return self::setErrorInfo('运费模板不存在');
  92. }
  93. if (!isset($temp_num[$cart['productInfo']['temp_id']])) {
  94. $temp_num[$cart['productInfo']['temp_id']]['number'] = $num;
  95. $temp_num[$cart['productInfo']['temp_id']]['price'] = bcmul($cart['cart_num'], $cart['truePrice'], 2);
  96. $temp_num[$cart['productInfo']['temp_id']]['first'] = $region['first'];
  97. $temp_num[$cart['productInfo']['temp_id']]['first_price'] = $region['first_price'];
  98. $temp_num[$cart['productInfo']['temp_id']]['continue'] = $region['continue'];
  99. $temp_num[$cart['productInfo']['temp_id']]['continue_price'] = $region['continue_price'];
  100. $temp_num[$cart['productInfo']['temp_id']]['temp_id'] = $cart['productInfo']['temp_id'];
  101. $temp_num[$cart['productInfo']['temp_id']]['city_id'] = $addr['city_id'];
  102. } else {
  103. $temp_num[$cart['productInfo']['temp_id']]['number'] += $num;
  104. $temp_num[$cart['productInfo']['temp_id']]['price'] += bcmul($cart['cart_num'], $cart['truePrice'], 2);
  105. }
  106. }
  107. array_multisort(array_column($temp_num, 'first_price'), SORT_DESC, $temp_num);
  108. $type = $storePostage = 0;
  109. foreach ($temp_num as $k => $v) {
  110. if (ShippingTemplatesFree::where('temp_id', $v['temp_id'])->where('city_id', $v['city_id'])->where('number', '<=', $v['number'])->where('price', '<=', $v['price'])->find()) {
  111. unset($temp_num[$k]);
  112. }
  113. }
  114. foreach ($temp_num as $v) {
  115. if ($type == 0) {
  116. if ($v['number'] <= $v['first']) {
  117. $storePostage = bcadd($storePostage, $v['first_price'], 2);
  118. } else {
  119. if ($v['continue'] <= 0) {
  120. $storePostage = $storePostage;
  121. } else {
  122. $storePostage = bcadd(bcadd($storePostage, $v['first_price'], 2), bcmul(ceil(bcdiv(bcsub($v['number'], $v['first']), $v['continue'] ?? 0, 2)), $v['continue_price']), 2);
  123. }
  124. }
  125. $type = 1;
  126. } else {
  127. if ($v['continue'] <= 0) {
  128. $storePostage = $storePostage;
  129. } else {
  130. $storePostage = bcadd($storePostage, bcmul(ceil(bcdiv($v['number'], $v['continue'] ?? 0, 2)), $v['continue_price']), 2);
  131. }
  132. }
  133. }
  134. } else {
  135. $storePostage = 0;
  136. }
  137. if ($storeFreePostage <= $totalPrice) $storePostage = 0;//如果总价大于等于满额包邮 邮费等于0
  138. }
  139. return compact('storePostage', 'storeFreePostage', 'totalPrice', 'costPrice', 'vipPrice');
  140. }
  141. /**获取某个字段总金额
  142. * @param $cartInfo
  143. * @param $key 键名
  144. * @return int|string
  145. */
  146. public static function getOrderSumPrice($cartInfo, $key = 'truePrice')
  147. {
  148. $SumPrice = 0;
  149. foreach ($cartInfo as $cart) {
  150. $SumPrice = bcadd($SumPrice, bcmul($cart['cart_num'], $cart[$key], 2), 2);
  151. }
  152. return $SumPrice;
  153. }
  154. /**
  155. * 拼团
  156. * @param $cartInfo
  157. * @return array
  158. */
  159. public static function getCombinationOrderPriceGroup($cartInfo)
  160. {
  161. $storePostage = floatval(sys_config('store_postage')) ?: 0;
  162. $storeFreePostage = floatval(sys_config('store_free_postage')) ?: 0;
  163. $totalPrice = self::getCombinationOrderTotalPrice($cartInfo);
  164. $costPrice = self::getCombinationOrderTotalPrice($cartInfo);
  165. if (!$storeFreePostage) {
  166. $storePostage = 0;
  167. } else {
  168. foreach ($cartInfo as $cart) {
  169. if (!StoreCombination::where('id', $cart['combination_id'])->value('is_postage'))
  170. $storePostage = bcadd($storePostage, StoreCombination::where('id', $cart['combination_id'])->value('postage'), 2);
  171. }
  172. if ($storeFreePostage <= $totalPrice) $storePostage = 0;
  173. }
  174. return compact('storePostage', 'storeFreePostage', 'totalPrice', 'costPrice');
  175. }
  176. /**
  177. * 拼团价格
  178. * @param $cartInfo
  179. * @return float
  180. */
  181. public static function getCombinationOrderTotalPrice($cartInfo)
  182. {
  183. $totalPrice = 0;
  184. foreach ($cartInfo as $cart) {
  185. if ($cart['combination_id']) {
  186. $totalPrice = bcadd($totalPrice, bcmul($cart['cart_num'], StoreCombination::where('id', $cart['combination_id'])->value('price'), 2), 2);
  187. }
  188. }
  189. return (float)$totalPrice;
  190. }
  191. /**
  192. * 缓存订单信息
  193. * @param $uid
  194. * @param $cartInfo
  195. * @param $priceGroup
  196. * @param array $other
  197. * @param int $cacheTime
  198. * @return string
  199. * @throws \Psr\SimpleCache\InvalidArgumentException
  200. */
  201. public static function cacheOrderInfo($uid, $cartInfo, $priceGroup, $other = [], $cacheTime = 600)
  202. {
  203. $key = md5(time());
  204. Cache::set('user_order_' . $uid . $key, compact('cartInfo', 'priceGroup', 'other'), $cacheTime);
  205. return $key;
  206. }
  207. /**
  208. * 获取订单缓存信息
  209. * @param $uid
  210. * @param $key
  211. * @return mixed|null
  212. * @throws \Psr\SimpleCache\InvalidArgumentException
  213. */
  214. public static function getCacheOrderInfo($uid, $key)
  215. {
  216. $cacheName = 'user_order_' . $uid . $key;
  217. if (!Cache::has($cacheName)) return null;
  218. return Cache::get($cacheName);
  219. }
  220. /**
  221. * 删除订单缓存
  222. * @param $uid
  223. * @param $key
  224. */
  225. public static function clearCacheOrderInfo($uid, $key)
  226. {
  227. Cache::delete('user_order_' . $uid . $key);
  228. }
  229. /**
  230. * 生成订单
  231. * @param $uid
  232. * @param $key
  233. * @param $addressId
  234. * @param $payType
  235. * @param bool $useIntegral
  236. * @param int $couponId
  237. * @param string $mark
  238. * @param int $combinationId
  239. * @param int $pinkId
  240. * @param int $seckill_id
  241. * @param int $bargain_id
  242. * @param bool $test
  243. * @param int $isChannel
  244. * @param int $shipping_type
  245. * @param string $real_name
  246. * @param string $phone
  247. * @return StoreOrder|bool|\think\Model
  248. * @throws \think\Exception
  249. * @throws DataNotFoundException
  250. * @throws ModelNotFoundException
  251. * @throws \think\exception\DbException
  252. */
  253. public static function cacheKeyCreateOrder($uid, $key, $addressId, $payType, $useIntegral = false, $couponId = 0, $mark = '', $combinationId = 0, $pinkId = 0, $seckill_id = 0, $bargain_id = 0, $test = false, $isChannel = 0, $shipping_type = 1, $real_name = '', $phone = '', $storeId = 0)
  254. {
  255. self::beginTrans();
  256. try {
  257. $shipping_type = (int)$shipping_type;
  258. $offlinePayStatus = (int)sys_config('offline_pay_status') ?? (int)2;
  259. if ($offlinePayStatus == 2) unset(self::$payType['offline']);
  260. if (!array_key_exists($payType, self::$payType)) return self::setErrorInfo('选择支付方式有误!', true);
  261. if (self::be(['unique' => $key, 'uid' => $uid])) return self::setErrorInfo('请勿重复提交订单', true);
  262. $userInfo = User::getUserInfo($uid);
  263. if (!$userInfo) return self::setErrorInfo('用户不存在!', true);
  264. $cartGroup = self::getCacheOrderInfo($uid, $key);
  265. if (!$cartGroup) return self::setErrorInfo('订单已过期,请刷新当前页面!', true);
  266. $cartInfo = $cartGroup['cartInfo'];
  267. $priceGroup = $cartGroup['priceGroup'];
  268. $other = $cartGroup['other'];
  269. $payPrice = (float)$priceGroup['totalPrice'];
  270. $addr = UserAddress::where('uid', $uid)->where('id', $addressId)->find();
  271. if ($payType == 'offline' && sys_config('offline_postage') == 1) {
  272. $payPostage = 0;
  273. } else {
  274. $payPostage = self::getOrderPriceGroup($cartInfo, $addr)['storePostage'];
  275. }
  276. if ($shipping_type === 1) {
  277. if (!$test && !$addressId) return self::setErrorInfo('请选择收货地址!', true);
  278. if (!$test && (!UserAddress::be(['uid' => $uid, 'id' => $addressId, 'is_del' => 0]) || !($addressInfo = UserAddress::find($addressId))))
  279. return self::setErrorInfo('地址选择有误!', true);
  280. } else {
  281. if ((!$real_name || !$phone) && !$test) return self::setErrorInfo('请填写姓名和电话', true);
  282. $addressInfo['real_name'] = $real_name;
  283. $addressInfo['phone'] = $phone;
  284. $addressInfo['province'] = '';
  285. $addressInfo['city'] = '';
  286. $addressInfo['district'] = '';
  287. $addressInfo['detail'] = '';
  288. }
  289. $cartIds = [];
  290. $totalNum = 0;
  291. $gainIntegral = 0;
  292. foreach ($cartInfo as $cart) {
  293. $cartIds[] = $cart['id'];
  294. $totalNum += $cart['cart_num'];
  295. if (!$seckill_id) $seckill_id = $cart['seckill_id'];
  296. if (!$bargain_id) $bargain_id = $cart['bargain_id'];
  297. if (!$combinationId) $combinationId = $cart['combination_id'];
  298. $cartInfoGainIntegral = isset($cart['productInfo']['give_integral']) ? bcmul($cart['cart_num'], $cart['productInfo']['give_integral'], 2) : 0;
  299. $gainIntegral = bcadd($gainIntegral, $cartInfoGainIntegral, 2);
  300. }
  301. $deduction = $seckill_id || $bargain_id || $combinationId;
  302. if ($deduction) {
  303. $couponId = 0;
  304. $useIntegral = false;
  305. if (!$test) {
  306. unset(self::$payType['offline']);
  307. if (!array_key_exists($payType, self::$payType)) return self::setErrorInfo('营销产品不能使用线下支付!', true);
  308. }
  309. }
  310. //使用优惠劵
  311. $res1 = true;
  312. if ($couponId) {
  313. $couponInfo = StoreCouponUser::validAddressWhere()->where('id', $couponId)->where('uid', $uid)->find();
  314. if (!$couponInfo) return self::setErrorInfo('选择的优惠劵无效!', true);
  315. $coupons = StoreCouponUser::getUsableCouponList($uid, ['valid' => $cartInfo], $payPrice);
  316. $flag = false;
  317. foreach ($coupons as $coupon) {
  318. if ($coupon['id'] == $couponId) {
  319. $flag = true;
  320. continue;
  321. }
  322. }
  323. if (!$flag)
  324. return self::setErrorInfo('不满足优惠劵的使用条件!', true);
  325. $payPrice = (float)bcsub($payPrice, $couponInfo['coupon_price'], 2);
  326. $res1 = StoreCouponUser::useCoupon($couponId);
  327. $couponPrice = $couponInfo['coupon_price'];
  328. } else {
  329. $couponId = 0;
  330. $couponPrice = 0;
  331. }
  332. if (!$res1) return self::setErrorInfo('使用优惠劵失败!', true);
  333. //$shipping_type = 1 快递发货 $shipping_type = 2 门店自提
  334. $store_self_mention = sys_config('store_self_mention') ?? 0;
  335. if (!$store_self_mention) $shipping_type = 1;
  336. if ($shipping_type === 1) {
  337. //是否包邮
  338. if ((isset($other['offlinePostage']) && $other['offlinePostage'] && $payType == 'offline')) $payPostage = 0;
  339. $payPrice = (float)bcadd($payPrice, $payPostage, 2);
  340. } else if ($shipping_type === 2) {
  341. //门店自提没有邮费支付
  342. $priceGroup['storePostage'] = 0;
  343. $payPostage = 0;
  344. if (!$storeId && !$test) {
  345. return self::setErrorInfo('请选择门店', true);
  346. }
  347. }
  348. //积分抵扣
  349. $res2 = true;
  350. $SurplusIntegral = 0;
  351. if ($useIntegral && $userInfo['integral'] > 0) {
  352. $deductionPrice = (float)bcmul($userInfo['integral'], $other['integralRatio'], 2);
  353. if ($deductionPrice < $payPrice) {
  354. $payPrice = bcsub($payPrice, $deductionPrice, 2);
  355. $usedIntegral = $userInfo['integral'];
  356. $SurplusIntegral = 0;
  357. $res2 = false !== User::edit(['integral' => 0], $userInfo['uid'], 'uid');
  358. } else {
  359. $deductionPrice = $payPrice;
  360. $usedIntegral = (float)bcdiv($payPrice, $other['integralRatio'], 2);
  361. $SurplusIntegral = bcsub($userInfo['integral'], $usedIntegral, 2);
  362. $res2 = false !== User::bcDec($userInfo['uid'], 'integral', $usedIntegral, 'uid');
  363. $payPrice = 0;
  364. }
  365. $res2 = $res2 && false != UserBill::expend('积分抵扣', $uid, 'integral', 'deduction', $usedIntegral, $key, $userInfo['integral'], '购买商品使用' . floatval($usedIntegral) . '积分抵扣' . floatval($deductionPrice) . '元');
  366. } else {
  367. $deductionPrice = 0;
  368. $usedIntegral = 0;
  369. }
  370. if (!$res2) return self::setErrorInfo('使用积分抵扣失败!', true);
  371. if ($payPrice <= 0) $payPrice = 0;
  372. if ($test) {
  373. self::rollbackTrans();
  374. return [
  375. 'total_price' => $priceGroup['totalPrice'],
  376. 'pay_price' => $payPrice,
  377. 'pay_postage' => $payPostage,
  378. 'coupon_price' => $couponPrice,
  379. 'deduction_price' => $deductionPrice,
  380. 'SurplusIntegral' => $SurplusIntegral,
  381. ];
  382. }
  383. $orderInfo = [
  384. 'uid' => $uid,
  385. 'order_id' => $test ? 0 : self::getNewOrderId(),
  386. 'real_name' => $addressInfo['real_name'],
  387. 'user_phone' => $addressInfo['phone'],
  388. 'user_address' => $addressInfo['province'] . ' ' . $addressInfo['city'] . ' ' . $addressInfo['district'] . ' ' . $addressInfo['detail'],
  389. 'cart_id' => $cartIds,
  390. 'total_num' => $totalNum,
  391. 'total_price' => $priceGroup['totalPrice'],
  392. 'total_postage' => $priceGroup['storePostage'],
  393. 'coupon_id' => $couponId,
  394. 'coupon_price' => $couponPrice,
  395. 'pay_price' => $payPrice,
  396. 'pay_postage' => $payPostage,
  397. 'deduction_price' => $deductionPrice,
  398. 'paid' => 0,
  399. 'pay_type' => $payType,
  400. 'use_integral' => $usedIntegral,
  401. 'gain_integral' => $gainIntegral,
  402. 'mark' => htmlspecialchars($mark),
  403. 'combination_id' => $combinationId,
  404. 'pink_id' => $pinkId,
  405. 'seckill_id' => $seckill_id,
  406. 'bargain_id' => $bargain_id,
  407. 'cost' => $priceGroup['costPrice'],
  408. 'is_channel' => $isChannel,
  409. 'add_time' => time(),
  410. 'unique' => $key,
  411. 'shipping_type' => $shipping_type,
  412. ];
  413. if ($shipping_type === 2) {
  414. $orderInfo['verify_code'] = self::getStoreCode();
  415. $orderInfo['store_id'] = SystemStore::getStoreDispose($storeId, 'id');
  416. if (!$orderInfo['store_id']) return self::setErrorInfo('暂无门店无法选择门店自提!', true);
  417. }
  418. $order = self::create($orderInfo);
  419. if (!$order) return self::setErrorInfo('订单生成失败!', true);
  420. $res5 = true;
  421. foreach ($cartInfo as $cart) {
  422. //减库存加销量
  423. if ($combinationId) $res5 = $res5 && StoreCombination::decCombinationStock($cart['cart_num'], $combinationId, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  424. else if ($seckill_id) $res5 = $res5 && StoreSeckill::decSeckillStock($cart['cart_num'], $seckill_id, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  425. else if ($bargain_id) $res5 = $res5 && StoreBargain::decBargainStock($cart['cart_num'], $bargain_id, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  426. else $res5 = $res5 && StoreProduct::decProductStock($cart['cart_num'], $cart['productInfo']['id'], isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  427. }
  428. //保存购物车商品信息
  429. $res4 = false !== StoreOrderCartInfo::setCartInfo($order['id'], $cartInfo);
  430. //购物车状态修改
  431. $res6 = false !== StoreCart::where('id', 'IN', $cartIds)->update(['is_pay' => 1]);
  432. if (!$res4 || !$res5 || !$res6) return self::setErrorInfo('订单生成失败!', true);
  433. //自动设置默认地址
  434. UserRepository::storeProductOrderCreateEbApi($order, compact('cartInfo', 'addressId'));
  435. self::clearCacheOrderInfo($uid, $key);
  436. self::commitTrans();
  437. StoreOrderStatus::status($order['id'], 'cache_key_create_order', '订单生成');
  438. return $order;
  439. } catch (\PDOException $e) {
  440. self::rollbackTrans();
  441. return self::setErrorInfo('生成订单时SQL执行错误错误原因:' . $e->getMessage());
  442. } catch (\Exception $e) {
  443. self::rollbackTrans();
  444. return self::setErrorInfo('生成订单时系统错误错误原因:' . $e->getMessage());
  445. }
  446. }
  447. /**
  448. * 回退积分
  449. * @param $order 订单信息
  450. * @return bool
  451. */
  452. public static function RegressionIntegral($order)
  453. {
  454. if ($order['paid'] || $order['status'] == -2 || $order['is_del']) return true;
  455. if ($order['use_integral'] <= 0) return true;
  456. if ((int)$order['status'] != -2 && (int)$order['refund_status'] != 2 && $order['back_integral'] >= $order['use_integral']) return true;
  457. $res = User::bcInc($order['uid'], 'integral', $order['use_integral']);
  458. if (!$res) return self::setErrorInfo('回退积分增加失败');
  459. UserBill::income('积分回退', $order['uid'], 'integral', 'deduction', $order['use_integral'], $order['unique'], User::where('uid', $order['uid'])->value('integral'), '购买商品失败,回退积分' . floatval($order['use_integral']));
  460. return false !== self::where('order_id', $order['order_id'])->update(['back_integral' => $order['use_integral']]);
  461. }
  462. /**
  463. * 回退库存和销量
  464. * @param $order 订单信息
  465. * @return bool
  466. * @throws DataNotFoundException
  467. * @throws ModelNotFoundException
  468. * @throws \think\exception\DbException
  469. */
  470. public static function RegressionStock($order)
  471. {
  472. if ($order['paid'] || $order['status'] == -2 || $order['is_del']) return true;
  473. $combinationId = $order['combination_id'];
  474. $seckill_id = $order['seckill_id'];
  475. $bargain_id = $order['bargain_id'];
  476. $res5 = true;
  477. $cartInfo = StoreOrderCartInfo::where('cart_id', 'in', $order['cart_id'])->select();
  478. foreach ($cartInfo as $cart) {
  479. //增库存减销量
  480. if ($combinationId) $res5 = $res5 && StoreCombination::incCombinationStock($cart['cart_info']['cart_num'], $combinationId);
  481. else if ($seckill_id) $res5 = $res5 && StoreSeckill::incSeckillStock($cart['cart_info']['cart_num'], $seckill_id);
  482. else if ($bargain_id) $res5 = $res5 && StoreBargain::incBargainStock($cart['cart_info']['cart_num'], $bargain_id);
  483. else $res5 = $res5 && StoreProduct::incProductStock($cart['cart_info']['cart_num'], $cart['cart_info']['productInfo']['id'], isset($cart['cart_info']['productInfo']['attrInfo']) ? $cart['cart_info']['productInfo']['attrInfo']['unique'] : '');
  484. }
  485. return $res5;
  486. }
  487. /**
  488. * 回退优惠卷
  489. * @param $order 订单信息
  490. * @return bool
  491. */
  492. public static function RegressionCoupon($order)
  493. {
  494. if ($order['paid'] || $order['status'] == -2 || $order['is_del']) return true;
  495. $res = true;
  496. if ($order['coupon_id'] && StoreCouponUser::be(['id' => $order['coupon_id'], 'uid' => $order['uid'], 'status' => 1])) {
  497. $res = $res && false !== StoreCouponUser::where('id', $order['coupon_id'])->where('uid', $order['uid'])->update(['status' => 0, 'use_time' => 0]);
  498. }
  499. return $res;
  500. }
  501. /**
  502. * 取消订单
  503. * @param string order_id 订单id
  504. * @param $uid
  505. * @return bool
  506. * @throws DataNotFoundException
  507. * @throws ModelNotFoundException
  508. * @throws \think\exception\DbException
  509. */
  510. public static function cancelOrder($order_id, $uid)
  511. {
  512. $order = self::where('order_id', $order_id)->where('uid', $uid)->find();
  513. if (!$order) return self::setErrorInfo('没有查到此订单');
  514. self::beginTrans();
  515. try {
  516. $res = self::RegressionIntegral($order) && self::RegressionStock($order) && self::RegressionCoupon($order);
  517. $order->is_del = 1;
  518. if ($res && $order->save()) {
  519. self::commitTrans();
  520. return true;
  521. } else
  522. return false;
  523. } catch (\Exception $e) {
  524. self::rollbackTrans();
  525. return self::setErrorInfo(['line' => $e->getLine(), 'message' => $e->getMessage()]);
  526. }
  527. }
  528. /**
  529. * 生成订单唯一id
  530. * @param $uid 用户uid
  531. * @return string
  532. */
  533. public static function getNewOrderId()
  534. {
  535. list($msec, $sec) = explode(' ', microtime());
  536. $msectime = number_format((floatval($msec) + floatval($sec)) * 1000, 0, '', '');
  537. $orderId = 'wx' . $msectime . mt_rand(10000, 99999);
  538. if (self::be(['order_id' => $orderId])) $orderId = 'wx' . $msectime . mt_rand(10000, 99999);
  539. return $orderId;
  540. }
  541. /**
  542. * 修改订单号
  543. * @param $orderId
  544. * @return string
  545. */
  546. public static function changeOrderId($orderId)
  547. {
  548. $ymd = substr($orderId, 2, 8);
  549. $key = substr($orderId, 16);
  550. return 'wx' . $ymd . date('His') . $key;
  551. }
  552. /**
  553. * 查找购物车里的所有产品标题
  554. * @param $cartId 购物车id
  555. * @return bool|string
  556. */
  557. public static function getProductTitle($cartId)
  558. {
  559. $title = '';
  560. try {
  561. $orderCart = StoreOrderCartInfo::where('cart_id', 'in', $cartId)->field('cart_info')->select();
  562. foreach ($orderCart as $item) {
  563. if (isset($item['cart_info']['productInfo']['store_name'])) {
  564. $title .= $item['cart_info']['productInfo']['store_name'] . '|';
  565. }
  566. }
  567. unset($item);
  568. if (!$title) {
  569. $productIds = StoreCart::where('id', 'in', $cartId)->column('product_id');
  570. $productlist = ($productlist = StoreProduct::getProductField($productIds, 'store_name')) ? $productlist->toArray() : [];
  571. foreach ($productlist as $item) {
  572. if (isset($item['store_name'])) $title .= $item['store_name'] . '|';
  573. }
  574. }
  575. if ($title) $title = substr($title, 0, strlen($title) - 1);
  576. unset($item);
  577. } catch (\Exception $e) {
  578. }
  579. return $title;
  580. }
  581. /**
  582. * 获取门店自提唯一核销码
  583. * @return bool|string
  584. */
  585. public static function getStoreCode()
  586. {
  587. list($msec, $sec) = explode(' ', microtime());
  588. $num = bcadd(time(), mt_rand(10, 999999), 0) . '' . substr($msec, 2, 3);//生成随机数
  589. if (strlen($num) < 12)
  590. $num = str_pad((string)$num, 12, 0, STR_PAD_RIGHT);
  591. else
  592. $num = substr($num, 0, 12);
  593. if (self::be(['verify_code' => $num])) return self::getStoreCode();
  594. return $num;
  595. }
  596. /**
  597. * 余额支付
  598. * @param $order_id
  599. * @param $uid
  600. * @param string $formId
  601. * @return bool
  602. * @throws \think\Exception
  603. * @throws DataNotFoundException
  604. * @throws ModelNotFoundException
  605. * @throws \think\exception\DbException
  606. */
  607. public static function yuePay($order_id, $uid, $formId = '')
  608. {
  609. $orderInfo = self::where('uid', $uid)->where('order_id', $order_id)->where('is_del', 0)->find();
  610. if (!$orderInfo) return self::setErrorInfo('订单不存在!');
  611. if ($orderInfo['paid']) return self::setErrorInfo('该订单已支付!');
  612. // if($orderInfo['pay_type'] != 'yue') return self::setErrorInfo('该订单不能使用余额支付!');
  613. $userInfo = User::getUserInfo($uid);
  614. if ($userInfo['now_money'] < $orderInfo['pay_price'])
  615. return self::setErrorInfo(['status' => 'pay_deficiency', 'msg' => '余额不足' . floatval($orderInfo['pay_price'])]);
  616. self::beginTrans();
  617. $res1 = false !== User::bcDec($uid, 'now_money', $orderInfo['pay_price'], 'uid');
  618. $res2 = UserBill::expend('购买商品', $uid, 'now_money', 'pay_product', $orderInfo['pay_price'], $orderInfo['id'], $userInfo['now_money'], '余额支付' . floatval($orderInfo['pay_price']) . '元购买商品');
  619. $res3 = self::paySuccess($order_id, 'yue', $formId);//余额支付成功
  620. try {
  621. PaymentRepositories::yuePayProduct($userInfo, $orderInfo);
  622. } catch (\Exception $e) {
  623. self::rollbackTrans();
  624. return self::setErrorInfo($e->getMessage());
  625. }
  626. $res = $res1 && $res2 && $res3;
  627. self::checkTrans($res);
  628. return $res;
  629. }
  630. /**
  631. * 微信支付 为 0元时
  632. * @param $order_id
  633. * @param $uid
  634. * @param string $formId
  635. * @return bool
  636. * @throws \think\Exception
  637. * @throws DataNotFoundException
  638. * @throws ModelNotFoundException
  639. * @throws \think\exception\DbException
  640. */
  641. public static function jsPayPrice($order_id, $uid, $formId = '')
  642. {
  643. $orderInfo = self::where('uid', $uid)->where('order_id', $order_id)->where('is_del', 0)->find();
  644. if (!$orderInfo) return self::setErrorInfo('订单不存在!');
  645. if ($orderInfo['paid']) return self::setErrorInfo('该订单已支付!');
  646. $userInfo = User::getUserInfo($uid);
  647. self::beginTrans();
  648. $res1 = UserBill::expend('购买商品', $uid, 'now_money', 'pay_product', $orderInfo['pay_price'], $orderInfo['id'], $userInfo['now_money'], '微信支付' . floatval($orderInfo['pay_price']) . '元购买商品');
  649. $res2 = self::paySuccess($order_id, 'weixin', $formId);//微信支付为0时
  650. $res = $res1 && $res2;
  651. self::checkTrans($res);
  652. return $res;
  653. }
  654. /**
  655. * 用户申请退款
  656. * @param $uni
  657. * @param $uid
  658. * @param string $refundReasonWap
  659. * @return bool
  660. */
  661. public static function orderApplyRefund($uni, $uid, $refundReasonWap = '', $refundReasonWapExplain = '', $refundReasonWapImg = [])
  662. {
  663. $order = self::getUserOrderDetail($uid, $uni);
  664. if (!$order) return self::setErrorInfo('支付订单不存在!');
  665. if ($order['refund_status'] == 2) return self::setErrorInfo('订单已退款!');
  666. if ($order['refund_status'] == 1) return self::setErrorInfo('正在申请退款中!');
  667. if ($order['status'] == 1) return self::setErrorInfo('订单当前无法退款!');
  668. self::beginTrans();
  669. $res1 = false !== StoreOrderStatus::status($order['id'], 'apply_refund', '用户申请退款,原因:' . $refundReasonWap);
  670. $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');
  671. $res = $res1 && $res2;
  672. self::checkTrans($res);
  673. if (!$res)
  674. return self::setErrorInfo('申请退款失败!');
  675. else {
  676. try {
  677. if (in_array($order['is_channel'], [0, 2])) {
  678. //公众号发送模板消息通知客服
  679. WechatTemplateService::sendAdminNoticeTemplate([
  680. 'first' => "亲,有个订单申请退款 \n订单号:{$order['order_id']}",
  681. 'keyword1' => '退款申请',
  682. 'keyword2' => '已支付',
  683. 'keyword3' => date('Y/m/d H:i', time()),
  684. 'remark' => '请及时处理'
  685. ]);
  686. }
  687. if (in_array($order['is_channel'], [1, 2])) {
  688. //小程序 发送模板消息
  689. RoutineTemplate::sendOrderRefundStatus($order, $refundReasonWap);
  690. }
  691. //通知后台消息提醒
  692. ChannelService::instance()->send('NEW_REFUND_ORDER', ['order_id' => $order['order_id']]);
  693. } catch (\Exception $e) {
  694. }
  695. //发送短信
  696. event('ShortMssageSend', [$order['order_id'], 'AdminRefund']);
  697. return true;
  698. }
  699. }
  700. /**
  701. * //TODO 支付成功后
  702. * @param $orderId
  703. * @param string $paytype
  704. * @param string $formId
  705. * @return bool
  706. * @throws DataNotFoundException
  707. * @throws DbException
  708. * @throws ModelNotFoundException
  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 && UserSpread::setSpreadSure($order['uid']) && User::backOrderBrokerage($order);
  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 DataNotFoundException
  754. * @throws 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 DataNotFoundException
  857. * @throws 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 DataNotFoundException
  1034. * @throws 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 DataNotFoundException
  1067. * @throws 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 DataNotFoundException
  1124. * @throws 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)->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 DataNotFoundException
  1376. * @throws 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', 'delivery_goods');
  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 DataNotFoundException
  1505. * @throws 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');
  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 DataNotFoundException
  1554. * @throws 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 DataNotFoundException
  1851. * @throws 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. $list = self::where('paid', 0)->where('is_del', 0)->where('is_system_del', 0)->where('add_time', '>', time() - 900)->where('add_time', '<', time() - 600)->column('user_phone');
  1945. foreach ($list as $phone) {
  1946. ShortLetterRepositories::send(true, $phone, [], 'ORDER_PAY_FALSE');
  1947. }
  1948. }
  1949. public function productInfo()
  1950. {
  1951. return $this->hasMany(StoreProductReply::class, 'oid', 'id');
  1952. }
  1953. public static function setOrderProductReplyWhere($where)
  1954. {
  1955. $model = self::where('status', 3)->order('add_time desc')->whereIn('id', function ($query) {
  1956. $query->name('store_order')->alias('o')->join('store_product_reply a', 'a.oid = o.id')->group('o.id')->field('o.id')->select();
  1957. })->with('productInfo', function ($query) use ($where) {
  1958. $alias = '';
  1959. if (isset($where['title']) && $where['title'] != '')
  1960. $query->where("{$alias}comment", 'LIKE', "%$where[title]%");
  1961. if (isset($where['is_reply']) && $where['is_reply'] != '') {
  1962. if ($where['is_reply'] >= 0) {
  1963. $query->where("{$alias}is_reply", $where['is_reply']);
  1964. } else {
  1965. $query->where("{$alias}is_reply", '>', 0);
  1966. }
  1967. }
  1968. if (isset($where['producr_id']) && $where['producr_id'] != 0)
  1969. $query->where($alias . 'product_id', $where['producr_id']);
  1970. $query->where("{$alias}is_del", 0);
  1971. });
  1972. return $model;
  1973. }
  1974. public static function getOrderProductReplyList($where)
  1975. {
  1976. $list = self::setOrderProductReplyWhere($where)->page((int)$where['message_page'], (int)$where['limit'])->select();
  1977. $list = count($list) ? $list->toArray() : [];
  1978. foreach ($list as $key => $item) {
  1979. if (isset($item['productInfo']) && is_array($item['productInfo']) && count($item['productInfo'])) {
  1980. foreach ($item['productInfo'] as $k => $v) {
  1981. if (!$v['nickname'] && $v['uid']) {
  1982. $v['nickname'] = User::where('uid', $v['uid'])->value('nickname');
  1983. $v['avatar'] = User::where('uid', $v['uid'])->value('avatar');
  1984. }
  1985. $v['image'] = '';
  1986. $v['store_name'] = '';
  1987. if ($v['product_id']) {
  1988. $product = StoreProduct::where('id', $v['product_id'])->field(['image', 'store_name'])->find();
  1989. if ($product) {
  1990. $v['image'] = $product['image'];
  1991. $v['store_name'] = $product['store_name'];
  1992. }
  1993. }
  1994. $list[$key]['productInfo'][$k] = $v;
  1995. }
  1996. }
  1997. }
  1998. $count = self::setOrderProductReplyWhere($where)->count();
  1999. return compact('list', 'count');
  2000. }
  2001. }