审查视图

addons/shopro/library/traits/ActivityCache.php 13.4 KB
何书鹏 authored
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
<?php

namespace addons\shopro\library\traits;

use addons\shopro\exception\Exception;
use addons\shopro\library\Redis;
use addons\shopro\model\ActivityGoodsSkuPrice;
use addons\shopro\model\Goods;
use addons\shopro\model\GoodsSkuPrice;
use addons\shopro\model\OrderItem;
use addons\shopro\model\ScoreGoodsSkuPrice;

/**
 * 活动 redis 缓存
 */
trait ActivityCache
{
    protected $zsetKey = 'zset-activity';
    protected $hashPrefix = 'hash-activity:';
    protected $hashGoodsPrefix = 'goods-';
    protected $hashGrouponPrefix = 'groupon-';


    public function hasRedis($is_interrupt = false) {
        $error_msg = '';
        try {
            $redis = $this->getRedis();

            // 检测连接是否正常
            $redis->ping();
        } catch (\BadFunctionCallException $e) {
            // 缺少扩展
            $error_msg = $e->getMessage() ? $e->getMessage() : "缺少 redis 扩展";
        } catch (\RedisException $e) {
            // 连接拒绝
            \think\Log::write('redis connection redisException fail: ' . $e->getMessage());
            $error_msg = $e->getMessage() ? $e->getMessage() : "redis 连接失败";
        } catch (\Exception $e) {
            // 异常
            \think\Log::write('redis connection fail: ' . $e->getMessage());
            $error_msg = $e->getMessage() ? $e->getMessage() : "redis 连接异常";
        }

        if ($error_msg) {
            if ($is_interrupt) {
                throw new \Exception($error_msg);
            } else {
                return false;
            }
        }

        return true;
    }


    public function getRedis() {
        if (!isset($GLOBALS['SPREDIS'])) {
            $GLOBALS['SPREDIS'] = (new Redis())->getRedis();
        }

        return $GLOBALS['SPREDIS'];
    }


    // 将活动设置到缓存
    public function setActivity($activity, $goodsList = []) {
        $redis = $this->getRedis();

        // hash 键值
        $hashKey = $this->getHashKey($activity['id'], $activity['type']);

        // 删除旧的可变数据,需要排除销量 key 
        if ($redis->EXISTS($hashKey)) {
            // 如果 hashKey 存在,删除规格
            $hashs = $redis->HGETALL($hashKey);

            foreach ($hashs as $hashField => $hashValue) {
                // 是商品规格,并且不是销量
                if (strpos($hashField, $this->hashGoodsPrefix) !== false && strpos($hashField, '-sale') === false) {
                    // 商品规格信息,删掉
                    $redis->HDEL($hashKey, $hashField);
                }
            }
        }

        $redis->HMSET($hashKey, [
                            'id' => $activity['id'],
                            'title' => $activity['title'],
                            'type' => $activity['type'],
                            'richtext_id' => $activity['richtext_id'],
                            'richtext_title' => $activity['richtext_title'],
                            'starttime' => $activity['starttime'],
                            'endtime' => $activity['endtime'],
                            'rules' => is_array($activity['rules']) ? json_encode($activity['rules']) : $activity['rules'],
                            'goods_ids' => $activity['goods_ids']
                        ]
                    );

        foreach ($goodsList as $goods) {
            $redis->HSET($hashKey, $this->getHashGoodsKey($goods['goods_id'], $goods['sku_price_id']), json_encode($goods));
        }

        // 将 hash 键值存入 有序集合,score 为 id
        $redis->ZADD($this->zsetKey, $activity['starttime'], $hashKey);
    }


    // 获取所有活动
    public function getActivityList($activity_type = '', $status = 'all') {
        $redis = $this->getRedis();

        // 获取活动集合
        $hashList = $redis->ZRANGE($this->zsetKey, 0, 999999999);

        $activityList = [];
        if (!$hashList) {       // 没有获取到,返回空数组
            return $activityList;
        }

        foreach ($hashList as $hashKey) {
            // 查询活动状态
            if ($status != 'all') {
                $starttime = $redis->HGET($hashKey, 'starttime');
                $endtime = $redis->HGET($hashKey, 'endtime');
何书鹏 authored
125 126 127

                $tomorrow_start = strtotime(date('Y-m-d',strtotime('+1 day'))); //明日开始时间
                $tomorrow_end = strtotime(date('Y-m-d',strtotime('+1 day'))) + 86400; //明日结束时间
何书鹏 authored
128 129 130 131 132
                if ($status == 'ing') {
                    if (time() < $starttime || time() > $endtime) {
                        continue;
                    }
                } else if ($status == 'nostart') {
何书鹏 authored
133
                    if (time() > $starttime || $tomorrow_start < $starttime) {
何书鹏 authored
134 135 136 137 138 139
                        continue;
                    }
                } else if ($status == 'ended') {
                    if (time() < $endtime) {
                        continue;
                    }
何书鹏 authored
140
                } else if ($status == 'tomorrow') {
何书鹏 authored
141
                    if ($tomorrow_start > $starttime || $tomorrow_end < $starttime) {
何书鹏 authored
142 143
                        continue;
                    }
何书鹏 authored
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
                }
            }

            if ($activity_type) {
                $type = $redis->HGET($hashKey, 'type');

                if ($activity_type == $type) {
                    $activity = $this->getActivityByHashKey($hashKey);
                    if ($activity) {
                        $activityList[] = $activity;
                    }
                }
            } else {
                $activity = $this->getActivityByHashKey($hashKey);
                if ($activity) {
                    $activityList[] = $activity;
                }
            }
        }

        return $activityList;
    }


    // 获取商品对应的活动
    public function getGoodsActivity($goods_id, $activity_id = 0, $activity_type = '') {
        // 获取活动的 hash key
        $activityHashKey = $this->getActivityHashKey($goods_id, $activity_id, $activity_type);

        // 如果存在活动
        if ($activityHashKey) {
            return $this->getGoodsActivityByHashKey($goods_id, $activityHashKey);
        }

        return null;
    }



    // 删除活动缓存
    public function delActivity($activity) {
        $redis = $this->getRedis();

        $hashKey = $this->getHashKey($activity['id'], $activity['type']);

        // 删除 hash
        $redis->DEL($hashKey);

        // 删除集合
        $redis->ZREM($this->zsetKey, $hashKey);
    }


    // 通过 hash key 获取活动信息,商品信息获取商品相关活动信息
    private function getGoodsActivityByHashKey($goods_id, $activityHashKey) {
        $redis = $this->getRedis();

        // 取出整条 hash 记录
        $activityHash = $redis->HGETALL($activityHashKey);

        $activity = [];
        // 当前商品前缀
        $goodsPrefix = $this->hashGoodsPrefix . $goods_id . '-';

        foreach ($activityHash as $key => $value) {
            if (strpos($key, $goodsPrefix) !== false && strpos($key, '-sale') === false) {
                $goods = json_decode($value, true);

                // 计算销量库存数据
                $goods = $this->calcGoods($goods, $activityHashKey);

                // 商品规格项
                $activity['activity_goods_sku_price'][] = $goods;
            } else if (strpos($key, $this->hashGoodsPrefix) !== false) {
                // 活动里面别的商品规格项移除
                continue;
            } else if (strpos($key, $this->hashGrouponPrefix) !== false && (strpos($key, '-num') !== false || strpos($key, '-userlist') !== false)) {
                // 拼团的参团人数,团用户,移除
                continue;
            } else if ($key == 'rules') {
                $activity[$key] = json_decode($value, true);
            } else {
                // 普通键值
                $activity[$key] = $value;
            }
        }

        return $activity ? : null;
    }


    // 获取活动所有信息
    private function getActivityByHashKey($activityHashKey)
    {
        $redis = $this->getRedis();

        // 取出整条 hash 记录
        $activityHash = $redis->HGETALL($activityHashKey);

        $activity = [];

        foreach ($activityHash as $key => $value) {
            if (strpos($key, $this->hashGoodsPrefix) !== false && strpos($key, '-sale') === false) {
                $goods = json_decode($value, true);

                // 计算销量库存数据
                $goods = $this->calcGoods($goods, $activityHashKey);

                // 商品规格项
                $activity['activity_goods_sku_price'][] = $goods;
            } else if (strpos($key, $this->hashGoodsPrefix) !== false && strpos($key, '-sale') !== false) {
                // 活动里面 商品规格的销量,移除
                continue;
            } else if (strpos($key, $this->hashGrouponPrefix) !== false && (strpos($key, '-num') !== false || strpos($key, '-userlist') !== false)) {
                // 拼团的参团人数,团用户,移除
                continue;
            } else if ($key == 'rules') {
                $activity[$key] = json_decode($value, true);
            } else {
                // 普通键值
                $activity[$key] = $value;
            }
        }

        return $activity ?: null;
    }


    // 计算销量库存
    private function calcGoods($goods, $activityHashKey) {
        $redis = $this->getRedis();

        // 销量 key 
        $saleKey = $this->getHashGoodsKey($goods['goods_id'], $goods['sku_price_id'], true);
        
        // 缓存中的销量
        $cacheSale = $redis->HGET($activityHashKey, $saleKey);

        $stock = $goods['stock'] - $cacheSale; 
        $goods['stock'] = $stock > 0 ? $stock : 0;
        $goods['sales'] = $goods['sales'] + $cacheSale;

        return $goods;
    }


    // 从集合里面取出 当前要用的活动的 key
    private function getActivityHashKey($goods_id, $activity_id = 0, $activity_type = '') {
        $redis = $this->getRedis();

        // 获取活动集合
        $hashList = $redis->ZRANGE($this->zsetKey, 0, 999999999);

        $activityHashKey = '';
        if (!$hashList) {       // 没有获取到,返回空数组
            return $activityHashKey;
        }
        foreach ($hashList as $hashKey) {
            // 是否传入活动 id
            if ($activity_id && $activity_type) {
                $currentKey = $activity_type . ':' . $activity_id;

                // 判断是否是当前要找的活动
                if (strpos($hashKey, $currentKey) !== false) {
                    // 判断该活动中是否存在该商品
                    $goods_ids = explode(',', $redis->HGET($hashKey, 'goods_ids'));
                    if (in_array($goods_id, $goods_ids)) {
                        $activityHashKey = $hashKey;
                        break;
                    } else {
                        // 抛出异常, 活动不存在
                        throw new Exception('活动不存在');
                    }
                }

                // 接着找下一个活动
            } else {
                // 判断这条活动是否包含该商品
                $goods_ids = explode(',', $redis->HGET($hashKey, 'goods_ids'));
                if (in_array($goods_id, $goods_ids)) {
                    $activityHashKey = $hashKey;
                    break;
                }

                // 接着找下一个活动
            }
        }

        return $activityHashKey;
    }



    // 拼接 hash key
    private function getHashKey($activity_id, $activity_type) {
        return $this->hashPrefix . $activity_type . ':' . $activity_id;
    }


    // 拼接 hash 表中 goods 的 key
    private function getHashGoodsKey($goods_id, $sku_price_id, $is_sale = false)
    {
        return $this->hashGoodsPrefix . $goods_id . '-' . $sku_price_id . ($is_sale ? '-sale' : '');
    }



    // 拼接 hash 表中 groupon 的 key
    private function getHashGrouponKey($groupon_id, $goods_id, $type = '')
    {
        return $this->hashGrouponPrefix . $groupon_id . '-' . $goods_id . ($type ? '-' . $type : '');
    }


    // 获取 key 集合
    public function getKeys($detail, $activity)
    {
        // 获取 hash key
        $activityHashKey = $this->getHashKey($activity['activity_id'], $activity['activity_type']);

        $goodsSkuPriceKey = '';
        $saleKey = '';
        if (isset($detail['goods_sku_price_id']) && $detail['goods_sku_price_id']) {
            // 获取 hash 表中商品 sku 的 key
            $goodsSkuPriceKey = $this->getHashGoodsKey($detail['goods_id'], $detail['goods_sku_price_id']);
            // 获取 hash 表中商品 sku 的 销量的 key
            $saleKey = $this->getHashGoodsKey($detail['goods_id'], $detail['goods_sku_price_id'], true);
        }

        // 需要拼团的字段
        $grouponKey = '';
        $grouponNumKey = '';
        $grouponUserlistKey = '';
        if (isset($detail['groupon_id']) && $detail['groupon_id']) {
            // 获取 hash 表中团 key
            $grouponKey = $this->getHashGrouponKey($detail['groupon_id'], $detail['goods_id']);
            // 获取 hash 表中团当前人数 key
            $grouponNumKey = $this->getHashGrouponKey($detail['groupon_id'], $detail['goods_id'], 'num');
            // 获取 hash 表中团当前人员列表 key
            $grouponUserlistKey = $this->getHashGrouponKey($detail['groupon_id'], $detail['goods_id'], 'userlist');
        }

        return compact('activityHashKey', 'goodsSkuPriceKey', 'saleKey', 'grouponKey', 'grouponNumKey', 'grouponUserlistKey');
    }
}