RecycleCommonServiceImpl.java 13.4 KB
Newer Older
shenggui.li committed
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 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 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

package com.reyun.service.impl;

import com.reyun.dic.LanguageTypeEnum;
import com.reyun.dic.RecycleChannelEnum;
import com.reyun.model.Account;
import com.reyun.model.AdvancedFunctionApply;
import com.reyun.model.RecycleChannelAccount;
import com.reyun.repository.AccountRepository;
import com.reyun.repository.RecycleChannelAccountRepository;
import com.reyun.service.AdvancedFunctionApplyService;
import com.reyun.service.RecycleHandleService;
import com.reyun.task.EmailThread;
import com.reyun.util.Constant;
import com.reyun.util.ResultModel;
import com.reyun.util.ResultStatus;
import com.reyun.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Lzz on 18/8/31.
 * 回本分析service实现类(公共处理)
 */
@Service
public class RecycleCommonServiceImpl{

    private Logger logger = LoggerFactory.getLogger(RecycleCommonServiceImpl.class);

    @Autowired
    private AccountRepository accountRepository;
    @Autowired
    private RecycleChannelAccountRepository recycleChannelAccountRepository;
    @Autowired
    private RecycleUcttServiceImpl ucttService;
    @Autowired
    private RecycleBaiduServiceImpl baiduService;
    @Autowired
    private AdvancedFunctionApplyService advancedFunctionApplyService;



    private  static ExecutorService threadPool = Executors.newFixedThreadPool(20);


    /**
     * @param recycleChannelAccount
     *
     * 不可用账号发送邮件推送
     */
    public  void sendDisableAcountEmail( RecycleChannelAccount recycleChannelAccount){
        if(recycleChannelAccount != null){
            String channelName = recycleChannelAccount.getChannelName();
            Account account = accountRepository.findOne(recycleChannelAccount.getRootAccount());
            String accountEmail = account != null ? account.getEmail() : "";
            String channelAccount = recycleChannelAccount.getUserName();
            String failMes = recycleChannelAccount.getLoginFailMes();
            String failCustomeMes = "账号授权被中止,如密码被修改或需要重新输入验证码";//用户的错误信息统一翻译

            String reyunTitle = channelName+"渠道客户授权失效";
            String reyunContent = "您好,客户"+accountEmail+"在回本分析功能中,绑定的"
                    +channelName+"渠道的投放账号:"+channelAccount+",身份验证失败。失败原因为"+failMes+",请判断原因并处理。";
            List<String> reyunReceiver = new ArrayList<>();
            reyunReceiver.add("wangpeiyang@reyun.com");
            reyunReceiver.add("support@reyun.com");//运营团队

            reyunReceiver.clear();
            reyunReceiver.add("kangxiaoshan@reyun.com");

            EmailThread reyunEmailThread = new EmailThread(reyunTitle, reyunContent, reyunReceiver);
            threadPool.execute(reyunEmailThread);

			String customerTitle = channelName+"渠道授权失效";
			String customerContent = "您好,您的"+accountEmail+"账号在回本分析功能中,绑定的"+channelName+"渠道的投放账号:"+channelAccount+",身份验证失败。失败原因为"+failCustomeMes+",请打开此链接http://www."+Constant.getDomainStr()+"/index.html#/manage/accountauth查看并及时处理(重新授权验证)。";
			List<String> customerReceiver = new ArrayList<>();
			customerReceiver.add(accountEmail);

            //处理国际化
            if(LanguageTypeEnum.ENGLISH.getCode().equals(account.getLanguageType())){
                customerTitle = "Authorization failure of partner " + channelName;

                customerContent = "Hi, a failed authentication was detected for the injecting account "+accountEmail+"of partner "+channelName
                        +", which was bound by account "+channelAccount+",in the payback analysis function. The cause of failure is "+
                        failCustomeMes+". Please click this link http://"+Constant.getDomainStr()+"/index.html#/manage/accountauth to check and timely process it (reauthorization)";
            }
            //end

            customerReceiver.clear();
            customerReceiver.add("kangxiaoshan@reyun.com");

            EmailThread emailThread = new EmailThread(customerTitle, customerContent, customerReceiver);
			threadPool.execute(emailThread);
        }
    }


    /**
     * @param advancedFunctionApply
     *
     * 回本分析付费用户过期提醒
     */
    public  void sendAdvancePastEmail( AdvancedFunctionApply advancedFunctionApply, int day){
        if(advancedFunctionApply != null){
            String title = "回本分析付费即将到期提醒";
            String content = "您好,你购买的“回本分析完整版”还有"+day+"天到期,到期后将选择"+RecycleChannelAccount.CHANNEL_LIMIT+"个渠道为您恢复为“普通版”,其他渠道投放账号停用。为了不影响您的使用,请及时续费。";
            Account account = accountRepository.findOne(advancedFunctionApply.getAccount());
            String customerEmail = account.getEmail();
            List<String> reyunReceiver = new ArrayList<>();
            reyunReceiver.add(customerEmail);



            //处理国际化
            if(LanguageTypeEnum.ENGLISH.getCode().equals(account.getLanguageType())){
                title = "Expiration reminder for paid payback analysis ";

                content = "Hi, your “full version payback analysis” will be expired in "+day
                        +"days. After expiration, you’ll return to the “basic version” with "+RecycleChannelAccount.CHANNEL_LIMIT
                        +" partners available and other partner injecting accounts disabled. To ensure your normal use, please renew timely.";

            }
            //end
            reyunReceiver.clear();
            reyunReceiver.add("kangxiaoshan@reyun.com");

            EmailThread reyunEmailThread = new EmailThread(title, content, reyunReceiver);
            threadPool.execute(reyunEmailThread);
        }
    }

    /**
     * @param account
     * @param recycleChannelAccount
     * @return  账号与账号别名唯一性校验(因为数据库中uniqueAccount(username与channel_account_id也是各自唯一)唯一索引,所以此处最多返回一个对象),校验成功返回null
     */
    public ResultModel usernameAndchannelAliasLimitOne(Account account, RecycleChannelAccount recycleChannelAccount){

        boolean usernameExist = recycleChannelAccount != null && !StringUtil.isEmpty(recycleChannelAccount.getUserName());
        boolean channelAliasExist = recycleChannelAccount != null && !StringUtil.isEmpty(recycleChannelAccount.getChannelAlias());

        boolean isUpdate = recycleChannelAccount != null && recycleChannelAccount.getId() != null;

        //校验账号唯一性
        if(usernameExist && !isUpdate){//修改不做账号校验(因为修改账号不会重置)
            RecycleChannelAccount channelAccount = recycleChannelAccountRepository.findByRootAccountIdAndUserNameAndCid(account.getRootParent(),recycleChannelAccount.getUserName(),recycleChannelAccount.getCid());

            if(channelAccount != null && account.getRootParent().equals(channelAccount.getRootAccount())){//创建主账户相同
                return  ResultModel.ERROR(ResultStatus.RECYCLE_USERNAME_NOT_UNIQUE);
            }
        }


        //校验账户别名唯一性
        if(channelAliasExist){
            List<RecycleChannelAccount> channelAccounts = recycleChannelAccountRepository.findRootAccountidAndChannelAliasAndCid(account.getRootParent(), recycleChannelAccount.getChannelAlias(),recycleChannelAccount.getCid());

            long currentAccount = account.getRootParent();
            RecycleChannelAccount channelAccount = channelAccounts != null && channelAccounts.size() > 0 ? channelAccounts.get(0) : null;
            long recordAccount = channelAccount  != null ? channelAccount.getRootAccount(): -2L;
            boolean accountIsOne = currentAccount == recordAccount;
            boolean recordIsOne = channelAccount != null && recycleChannelAccount != null ? channelAccount.getId().equals(recycleChannelAccount.getId()) :  false;//校验记录是不是一个
            boolean channelAliasNotUnique = channelAccounts != null && accountIsOne && !recordIsOne;
            if(channelAliasNotUnique){
                return  ResultModel.ERROR(ResultStatus.RECYCLE_CHANNELALIAS_NOT_UNIQUE);
            }
        }

        return  null;
    }


    /**
     * @param recycleChannelEnum
     * @return 获取真正的逻辑层对象
     */
    public RecycleHandleService getRealRecycleService(RecycleChannelEnum recycleChannelEnum){
        RecycleHandleService recycleHandleService = null;
        switch (recycleChannelEnum){
            case UCTT:
                recycleHandleService = ucttService;
                break;
            case BAIDUYS:
                recycleHandleService = baiduService;
                break;
            default: recycleHandleService = null;
        }

        return recycleHandleService;
    }


    /**
     * @param account
     * @return 校验渠道是否超限(免费版与付费过期以后均不显示全部渠道) true 超出限制  false 不超限制{
     *     备注:免费版最多3个渠道,每个渠道最多3个账号
     * }
     */
    public Boolean checkChannelNumberLimit(Account account, RecycleChannelAccount recycleChannelAccount) {

        Boolean result = false;

        List<BigInteger> cids = recycleChannelAccountRepository.findCidsByAccount(account.getRootParent());

        List<RecycleChannelAccount> channelAccounts = recycleChannelAccountRepository.findEnableAccount(account.getRootParent());
        Map<BigInteger, Integer> cidAndCountMap = operateAccountCountByCid(channelAccounts, cids);

        boolean isUpdate = recycleChannelAccount != null && recycleChannelAccount.getId() != null;

        long channelNumber = cidAndCountMap != null ? cidAndCountMap.size() : 0;
        Long cid = recycleChannelAccount != null ? recycleChannelAccount.getCid() : 0;//需要校验的cid
        boolean cidIsExist = cidAndCountMap != null ? checkCidExist(cidAndCountMap,cid) : false;
        boolean accountNumOver = checkChannelAccountNumOver(cidAndCountMap, cid, isUpdate);//单渠道账户数超限
        boolean channelNumOver = false;//渠道数超限


        if (channelNumber > 0) {
            //付费申请
            AdvancedFunctionApply advancedFunctionApply = advancedFunctionApplyService.listApplyByAccount(account);
            if (null != advancedFunctionApply) {

                if (advancedFunctionApply.getStatus().equals(0) ||  new Date().after(advancedFunctionApply.getPastDate())) {
                    //申请未审核 或者 已过期
                    channelNumOver = channelNumber > RecycleChannelAccount.CHANNEL_LIMIT ||
                            (cidIsExist && channelNumber == RecycleChannelAccount.CHANNEL_LIMIT && !isUpdate) || (!cidIsExist && channelNumber == RecycleChannelAccount.CHANNEL_LIMIT);
                }else{
                    accountNumOver = false;//付费用户不存在个数限制
                }
            }else{//免费版
                channelNumOver = channelNumber > RecycleChannelAccount.CHANNEL_LIMIT ||
                        (cidIsExist && channelNumber == RecycleChannelAccount.CHANNEL_LIMIT && !isUpdate) || (!cidIsExist && channelNumber == RecycleChannelAccount.CHANNEL_LIMIT);
            }
        }
        result = channelNumOver || accountNumOver;
        return result;
    }



    /**
     * @param cidAndCountMap
     * @param cid
     * @return 校验渠道是否是已有渠道 true是  false否
     */
    private boolean checkCidExist(Map<BigInteger, Integer> cidAndCountMap , long cid){
        boolean result = false;
        Set<BigInteger> cids = cidAndCountMap != null ? cidAndCountMap.keySet() : null;

        for(BigInteger singleCid : cids){
            if(singleCid.longValue() == cid){
                result = true;
                break;
            }
        }
        return  result;

    }

    /**
     * @param cidAndCountMap
     * @param cid
     * @return 校验单渠道个数是否超限 true超出限制  false没有超出限制
     */
    private boolean checkChannelAccountNumOver(Map<BigInteger, Integer> cidAndCountMap , long cid, boolean isUpdate){
        boolean result = false;
        if(cidAndCountMap != null && cidAndCountMap.size() > 0){
            Integer hasChannelAccountNum = cidAndCountMap.get(BigInteger.valueOf(cid)) != null ? cidAndCountMap.get(BigInteger.valueOf(cid)) : 0;
            if(hasChannelAccountNum >  RecycleChannelAccount.CHANNEL_LIMIT || hasChannelAccountNum == RecycleChannelAccount.CHANNEL_LIMIT && !isUpdate){
                result = true;
            }
        }
        return  result;
    }

    private Map<BigInteger, Integer> operateAccountCountByCid(List<RecycleChannelAccount> recycleChannelAccounts, List<BigInteger> cids){
        Map<BigInteger, Integer> cidAndCountMap = new HashMap<>();
        for(BigInteger cid : cids){
            int i = 0;
            for(RecycleChannelAccount recycleChannelAccount : recycleChannelAccounts){
                if(recycleChannelAccount.getCid() == cid.longValue()){
                    i++;
                }
            }
            cidAndCountMap.put(cid, i);
        }
        return  cidAndCountMap;
    }
}