code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
package cn.itedus.lottery.domain.strategy.service.draw; import cn.itedus.lottery.domain.strategy.model.aggregates.StrategyRich; import cn.itedus.lottery.domain.strategy.model.vo.AwardBriefVO; import cn.itedus.lottery.domain.strategy.repository.IStrategyRepository; import javax.annotation.Resource; /** * @description: 抽奖策略数据支撑,一些通用的数据服务 * @author:小傅哥,微信:fustack * @date: 2021/8/28 * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ public class DrawStrategySupport extends DrawConfig{ @Resource protected IStrategyRepository strategyRepository; /** * 查询策略配置信息 * * @param strategyId 策略ID * @return 策略配置信息 */ protected StrategyRich queryStrategyRich(Long strategyId){ return strategyRepository.queryStrategyRich(strategyId); } /** * 查询奖品详情信息 * * @param awardId 奖品ID * @return 中奖详情 */ protected AwardBriefVO queryAwardInfoByAwardId(String awardId){ return strategyRepository.queryAwardInfo(awardId); } }
2302_77879529/lottery
lottery-domain/src/main/java/cn/itedus/lottery/domain/strategy/service/draw/DrawStrategySupport.java
Java
apache-2.0
1,222
package cn.itedus.lottery.domain.strategy.service.draw; import cn.itedus.lottery.domain.strategy.model.req.DrawReq; import cn.itedus.lottery.domain.strategy.model.res.DrawResult; /** * @description: 抽奖执行接口 * @author:小傅哥,微信:fustack * @date: 2021/8/28 * @Copyright:公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ public interface IDrawExec { /** * 抽奖方法 * @param req 抽奖参数;用户ID、策略ID * @return 中奖结果 */ DrawResult doDrawExec(DrawReq req); }
2302_77879529/lottery
lottery-domain/src/main/java/cn/itedus/lottery/domain/strategy/service/draw/IDrawExec.java
Java
apache-2.0
626
package cn.itedus.lottery.domain.strategy.service.draw.impl; import cn.itedus.lottery.domain.strategy.service.algorithm.IDrawAlgorithm; import cn.itedus.lottery.domain.strategy.service.draw.AbstractDrawBase; import com.alibaba.fastjson.JSON; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import java.util.List; /** * @description: 抽奖过程方法实现 * @author:小傅哥,微信:fustack * @date: 2021/8/28 * @Copyright:公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ @Service("drawExec") public class DrawExecImpl extends AbstractDrawBase { private Logger logger = LoggerFactory.getLogger(DrawExecImpl.class); @Override protected List<String> queryExcludeAwardIds(Long strategyId) { List<String> awardList = strategyRepository.queryNoStockStrategyAwardList(strategyId); logger.info("执行抽奖策略 strategyId:{},无库存排除奖品列表ID集合 awardList:{}", strategyId, JSON.toJSONString(awardList)); return awardList; } @Override protected String drawAlgorithm(Long strategyId, IDrawAlgorithm drawAlgorithm, List<String> excludeAwardIds) { // 执行抽奖 String awardId = drawAlgorithm.randomDraw(strategyId, excludeAwardIds); // 判断抽奖结果 if (null == awardId) { return null; } /* * 扣减库存,暂时采用数据库行级锁的方式进行扣减库存,后续优化为 Redis 分布式锁扣减 decr/incr * 注意:通常数据库直接锁行记录的方式并不能支撑较大体量的并发,但此种方式需要了解,因为在分库分表下的正常数据流量下的个人数据记录中,是可以使用行级锁的,因为他只影响到自己的记录,不会影响到其他人 */ boolean isSuccess = strategyRepository.deductStock(strategyId, awardId); // 返回结果,库存扣减成功返回奖品ID,否则返回NULL 「在实际的业务场景中,如果中奖奖品库存为空,则会发送兜底奖品,比如各类券」 return isSuccess ? awardId : null; } }
2302_77879529/lottery
lottery-domain/src/main/java/cn/itedus/lottery/domain/strategy/service/draw/impl/DrawExecImpl.java
Java
apache-2.0
2,256
package cn.itedus.lottery.domain.support.ids; /** * @description: 生成ID接口 * @author: 小傅哥,微信:fustack * @date: 2021/9/20 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ public interface IIdGenerator { /** * 获取ID,目前有两种实现方式 * 1. 雪花算法,用于生成单号 * 2. 日期算法,用于生成活动编号类,特性是生成数字串较短,但指定时间内不能生成太多 * 3. 随机算法,用于生成策略ID * * @return ID */ long nextId(); }
2302_77879529/lottery
lottery-domain/src/main/java/cn/itedus/lottery/domain/support/ids/IIdGenerator.java
Java
apache-2.0
692
package cn.itedus.lottery.domain.support.ids; import cn.itedus.lottery.common.Constants; import cn.itedus.lottery.domain.support.ids.policy.RandomNumeric; import cn.itedus.lottery.domain.support.ids.policy.ShortCode; import cn.itedus.lottery.domain.support.ids.policy.SnowFlake; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.HashMap; import java.util.Map; /** * @description: Id 策略模式上下文配置「在正式的完整的系统架构中,ID 的生成会有单独的服务来完成,其他服务来调用 ID 生成接口即可」 * @author: 小傅哥,微信:fustack * @date: 2021/9/20 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ @Configuration public class IdContext { /** * 创建 ID 生成策略对象,属于策略设计模式的使用方式 * * @param snowFlake 雪花算法,长码,大量 * @param shortCode 日期算法,短码,少量,全局唯一需要自己保证 * @param randomNumeric 随机算法,短码,大量,全局唯一需要自己保证 * @return IIdGenerator 实现类 */ @Bean public Map<Constants.Ids, IIdGenerator> idGenerator(SnowFlake snowFlake, ShortCode shortCode, RandomNumeric randomNumeric) { Map<Constants.Ids, IIdGenerator> idGeneratorMap = new HashMap<>(8); idGeneratorMap.put(Constants.Ids.SnowFlake, snowFlake); idGeneratorMap.put(Constants.Ids.ShortCode, shortCode); idGeneratorMap.put(Constants.Ids.RandomNumeric, randomNumeric); return idGeneratorMap; } }
2302_77879529/lottery
lottery-domain/src/main/java/cn/itedus/lottery/domain/support/ids/IdContext.java
Java
apache-2.0
1,750
package cn.itedus.lottery.domain.support.ids.policy; import cn.itedus.lottery.domain.support.ids.IIdGenerator; import org.apache.commons.lang3.RandomStringUtils; import org.springframework.stereotype.Component; /** * @description: 工具类生成 org.apache.commons.lang3.RandomStringUtils * @author: 小傅哥,微信:fustack * @date: 2021/9/20 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ @Component public class RandomNumeric implements IIdGenerator { @Override public long nextId() { return Long.parseLong(RandomStringUtils.randomNumeric(11)); } }
2302_77879529/lottery
lottery-domain/src/main/java/cn/itedus/lottery/domain/support/ids/policy/RandomNumeric.java
Java
apache-2.0
728
package cn.itedus.lottery.domain.support.ids.policy; import cn.itedus.lottery.domain.support.ids.IIdGenerator; import org.springframework.stereotype.Component; import java.util.Calendar; import java.util.Random; /** * @description: 短码生成策略,仅支持很小的调用量,用于生成活动配置类编号,保证全局唯一 * @author: 小傅哥,微信:fustack * @date: 2021/9/20 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ @Component public class ShortCode implements IIdGenerator { @Override public synchronized long nextId() { Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); int week = calendar.get(Calendar.WEEK_OF_YEAR); int day = calendar.get(Calendar.DAY_OF_WEEK); int hour = calendar.get(Calendar.HOUR_OF_DAY); // 打乱排序:2020年为准 + 小时 + 周期 + 日 + 三位随机数 StringBuilder idStr = new StringBuilder(); idStr.append(year - 2020); idStr.append(hour); idStr.append(String.format("%02d", week)); idStr.append(day); idStr.append(String.format("%03d", new Random().nextInt(1000))); return Long.parseLong(idStr.toString()); } }
2302_77879529/lottery
lottery-domain/src/main/java/cn/itedus/lottery/domain/support/ids/policy/ShortCode.java
Java
apache-2.0
1,381
package cn.itedus.lottery.domain.support.ids.policy; import cn.hutool.core.lang.Snowflake; import cn.hutool.core.net.NetUtil; import cn.hutool.core.util.IdUtil; import cn.itedus.lottery.domain.support.ids.IIdGenerator; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; /** * @description: hutool 工具包下的雪花算法,15位雪花算法推荐:https://github.com/yitter/idgenerator/blob/master/Java/source/src/main/java/com/github/yitter/core/SnowWorkerM1.java * @author: 小傅哥,微信:fustack * @date: 2021/9/20 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ @Component public class SnowFlake implements IIdGenerator { private Snowflake snowflake; @PostConstruct public void init() { // 0 ~ 31 位,可以采用配置的方式使用 long workerId; try { workerId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr()); } catch (Exception e) { workerId = NetUtil.getLocalhostStr().hashCode(); } workerId = workerId >> 16 & 31; long dataCenterId = 1L; snowflake = IdUtil.createSnowflake(workerId, dataCenterId); } @Override public synchronized long nextId() { return snowflake.nextId(); } }
2302_77879529/lottery
lottery-domain/src/main/java/cn/itedus/lottery/domain/support/ids/policy/SnowFlake.java
Java
apache-2.0
1,417
package cn.itedus.lottery.domain.support.redis; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.*; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; /** * @description: Redis 配置类 * @author: 小傅哥,微信:fustack * @date: 2021/11/20 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ @Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport { /** * template 相关配置 * * @param factory RedisConnectionFactory * @return RedisTemplate */ @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); // 配置连接工厂 template.setConnectionFactory(factory); //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式) Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常 om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jacksonSeial.setObjectMapper(om); // 值采用json序列化 template.setValueSerializer(jacksonSeial); //使用StringRedisSerializer来序列化和反序列化redis的key值 template.setKeySerializer(new StringRedisSerializer()); // 设置hash key 和value序列化模式 template.setHashKeySerializer(new StringRedisSerializer()); template.setHashValueSerializer(jacksonSeial); template.afterPropertiesSet(); return template; } /** * 对 HASH 类型的数据操作 * * @param redisTemplate RedisTemplate * @return HashOperations */ @Bean public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) { return redisTemplate.opsForHash(); } /** * 对redis字符串类型数据操作 * * @param redisTemplate RedisTemplate * @return ValueOperations */ @Bean public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) { return redisTemplate.opsForValue(); } /** * 对链表类型的数据操作 * * @param redisTemplate RedisTemplate * @return ListOperations */ @Bean public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) { return redisTemplate.opsForList(); } /** * 对无序集合类型的数据操作 * * @param redisTemplate RedisTemplate * @return SetOperations */ @Bean public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) { return redisTemplate.opsForSet(); } /** * 对有序集合类型的数据操作 * * @param redisTemplate RedisTemplate * @return ZSetOperations */ @Bean public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) { return redisTemplate.opsForZSet(); } }
2302_77879529/lottery
lottery-domain/src/main/java/cn/itedus/lottery/domain/support/redis/RedisConfig.java
Java
apache-2.0
4,182
package cn.itedus.lottery.infrastructure.dao; import cn.itedus.lottery.domain.activity.model.req.ActivityInfoLimitPageReq; import cn.itedus.lottery.domain.activity.model.req.PartakeReq; import cn.itedus.lottery.domain.activity.model.vo.AlterStateVO; import cn.itedus.lottery.infrastructure.po.Activity; import org.apache.ibatis.annotations.Mapper; import java.util.List; import java.util.Map; /** * @description: 活动基础信息表DAO * @author: 小傅哥,微信:fustack * @date: 2021/9/4 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ @Mapper public interface IActivityDao { /** * 插入数据 * * @param req 入参 */ void insert(Activity req); /** * 根据活动号查询活动信息 * * @param activityId 活动号 * @return 活动信息 */ Activity queryActivityById(Long activityId); /** * 变更活动状态 * * @param alterStateVO [activityId、beforeState、afterState] * @return 更新数量 */ int alterState(AlterStateVO alterStateVO); /** * 扣减活动库存 * * @param activityId 活动ID * @return 更新数量 */ int subtractionActivityStock(Long activityId); /** * 扫描待处理的活动列表,状态为:通过、活动中 * * @param id ID * @return 待处理的活动集合 */ List<Activity> scanToDoActivityList(Long id); /** * 更新用户领取活动后,活动库存 * * @param activity 入参 */ void updateActivityStock(Activity activity); /** * 查询活动分页数据数量 * * @param req 入参 * @return 结果 */ Long queryActivityInfoCount(ActivityInfoLimitPageReq req); /** * 查询活动分页数据列表 * * @param req 入参 * @return 结果 */ List<Activity> queryActivityInfoList(ActivityInfoLimitPageReq req); }
2302_77879529/lottery
lottery-infrastructure/src/main/java/cn/itedus/lottery/infrastructure/dao/IActivityDao.java
Java
apache-2.0
2,090
package cn.itedus.lottery.infrastructure.dao; import cn.itedus.lottery.infrastructure.po.Award; import org.apache.ibatis.annotations.Mapper; import java.util.List; /** * @description: 奖品信息表DAO * @author: 小傅哥,微信:fustack * @date: 2021/9/4 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ @Mapper public interface IAwardDao { /** * 查询奖品信息 * * @param awardId 奖品ID * @return 奖品信息 */ Award queryAwardInfo(String awardId); /** * 插入奖品配置 * * @param list 奖品配置 */ void insertList(List<Award> list); }
2302_77879529/lottery
lottery-infrastructure/src/main/java/cn/itedus/lottery/infrastructure/dao/IAwardDao.java
Java
apache-2.0
777
package cn.itedus.lottery.infrastructure.dao; import cn.itedus.lottery.infrastructure.po.Strategy; import org.apache.ibatis.annotations.Mapper; /** * @description: 策略表DAO * @author: 小傅哥,微信:fustack * @date: 2021/9/4 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ @Mapper public interface IStrategyDao { /** * 查询策略配置 * * @param strategyId 策略ID * @return 策略配置信息 */ Strategy queryStrategy(Long strategyId); /** * 插入策略配置 * * @param req 策略配置 */ void insert(Strategy req); }
2302_77879529/lottery
lottery-infrastructure/src/main/java/cn/itedus/lottery/infrastructure/dao/IStrategyDao.java
Java
apache-2.0
759
package cn.itedus.lottery.infrastructure.dao; import cn.itedus.lottery.infrastructure.po.StrategyDetail; import org.apache.ibatis.annotations.Mapper; import java.util.List; /** * @description: 策略明细表DAO * @author: 小傅哥,微信:fustack * @date: 2021/9/4 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ @Mapper public interface IStrategyDetailDao { /** * 查询策略表详细配置 * @param strategyId 策略ID * @return 返回结果 */ List<StrategyDetail> queryStrategyDetailList(Long strategyId); /** * 查询无库存策略奖品ID * @param strategyId 策略ID * @return 返回结果 */ List<String> queryNoStockStrategyAwardList(Long strategyId); /** * 扣减库存 * @param strategyDetailReq 策略ID、奖品ID * @return 返回结果 */ int deductStock(StrategyDetail strategyDetailReq); /** * 插入策略配置组 * * @param list 策略配置组 */ void insertList(List<StrategyDetail> list); }
2302_77879529/lottery
lottery-infrastructure/src/main/java/cn/itedus/lottery/infrastructure/dao/IStrategyDetailDao.java
Java
apache-2.0
1,223
package cn.itedus.lottery.infrastructure.dao; import cn.bugstack.middleware.db.router.annotation.DBRouter; import cn.bugstack.middleware.db.router.annotation.DBRouterStrategy; import cn.itedus.lottery.infrastructure.po.UserStrategyExport; import org.apache.ibatis.annotations.Mapper; import java.util.List; /** * @description: 用户策略计算结果表DAO * @author: 小傅哥,微信:fustack * @date: 2021/9/30 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ @Mapper @DBRouterStrategy(splitTable = true) public interface IUserStrategyExportDao { /** * 新增数据 * @param userStrategyExport 用户策略 */ @DBRouter(key = "uId") void insert(UserStrategyExport userStrategyExport); /** * 查询数据 * @param uId 用户ID * @return 用户策略 */ @DBRouter UserStrategyExport queryUserStrategyExportByUId(String uId); /** * 更新发奖状态 * @param userStrategyExport 发奖信息 */ @DBRouter void updateUserAwardState(UserStrategyExport userStrategyExport); /** * 更新发送MQ状态 * @param userStrategyExport 发送消息 */ @DBRouter void updateInvoiceMqState(UserStrategyExport userStrategyExport); /** * 扫描发货单 MQ 状态,把未发送 MQ 的单子扫描出来,做补偿 * * @return 发货单 */ List<UserStrategyExport> scanInvoiceMqState(); }
2302_77879529/lottery
lottery-infrastructure/src/main/java/cn/itedus/lottery/infrastructure/dao/IUserStrategyExportDao.java
Java
apache-2.0
1,574
package cn.itedus.lottery.infrastructure.dao; import cn.bugstack.middleware.db.router.annotation.DBRouter; import cn.itedus.lottery.infrastructure.po.UserTakeActivityCount; import org.apache.ibatis.annotations.Mapper; /** * @description: 用户活动参与次数表Dao * @author: 小傅哥,微信:fustack * @date: 2021/10/1 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ @Mapper public interface IUserTakeActivityCountDao { /** * 查询用户领取次数信息 * * @param userTakeActivityCountReq 请求入参【活动号、用户ID】 * @return 领取结果 */ @DBRouter UserTakeActivityCount queryUserTakeActivityCount(UserTakeActivityCount userTakeActivityCountReq); /** * 插入领取次数信息 * * @param userTakeActivityCount 请求入参 */ void insert(UserTakeActivityCount userTakeActivityCount); /** * 更新领取次数信息 * * @param userTakeActivityCount 请求入参 * @return 更新数量 */ int updateLeftCount(UserTakeActivityCount userTakeActivityCount); }
2302_77879529/lottery
lottery-infrastructure/src/main/java/cn/itedus/lottery/infrastructure/dao/IUserTakeActivityCountDao.java
Java
apache-2.0
1,234
package cn.itedus.lottery.infrastructure.dao; import cn.bugstack.middleware.db.router.annotation.DBRouter; import cn.itedus.lottery.infrastructure.po.UserTakeActivity; import org.apache.ibatis.annotations.Mapper; /** * @description: 用户领取活动表DAO * @author: 小傅哥,微信:fustack * @date: 2021/9/22 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ @Mapper public interface IUserTakeActivityDao { /** * 插入用户领取活动信息 * * @param userTakeActivity 入参 */ void insert(UserTakeActivity userTakeActivity); /** * 锁定活动领取记录 * * @param userTakeActivity 入参 * @return 更新结果 */ int lockTackActivity(UserTakeActivity userTakeActivity); /** * 查询是否存在未执行抽奖领取活动单【user_take_activity 存在 state = 0,领取了但抽奖过程失败的,可以直接返回领取结果继续抽奖】 * 查询此活动ID,用户最早领取但未消费的一条记录【这部分一般会有业务流程限制,比如是否处理最先还是最新领取单,要根据自己的业务实际场景进行处理】 * * @param userTakeActivity 请求入参 * @return 领取结果 */ @DBRouter UserTakeActivity queryNoConsumedTakeActivityOrder(UserTakeActivity userTakeActivity); }
2302_77879529/lottery
lottery-infrastructure/src/main/java/cn/itedus/lottery/infrastructure/dao/IUserTakeActivityDao.java
Java
apache-2.0
1,528
package cn.itedus.lottery.infrastructure.dao; import cn.itedus.lottery.infrastructure.po.RuleTree; import org.apache.ibatis.annotations.Mapper; /** * @description: 规则树配置DAO * @author: 小傅哥,微信:fustack * @date: 2021/9/22 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ @Mapper public interface RuleTreeDao { /** * 规则树查询 * @param id ID * @return 规则树 */ RuleTree queryRuleTreeByTreeId(Long id); /** * 规则树简要信息查询 * @param treeId 规则树ID * @return 规则树 */ RuleTree queryTreeSummaryInfo(Long treeId); }
2302_77879529/lottery
lottery-infrastructure/src/main/java/cn/itedus/lottery/infrastructure/dao/RuleTreeDao.java
Java
apache-2.0
776
package cn.itedus.lottery.infrastructure.dao; import cn.itedus.lottery.infrastructure.po.RuleTreeNode; import org.apache.ibatis.annotations.Mapper; import java.util.List; /** * @description: 规则树节点DAO * @author: 小傅哥,微信:fustack * @date: 2021/9/22 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ @Mapper public interface RuleTreeNodeDao { /** * 查询规则树节点 * @param treeId 规则树ID * @return 规则树节点集合 */ List<RuleTreeNode> queryRuleTreeNodeList(Long treeId); /** * 查询规则树节点数量 * @param treeId 规则树ID * @return 节点数量 */ int queryTreeNodeCount(Long treeId); /** * 查询规则树节点 * * @param treeId 规则树ID * @return 节点集合 */ List<RuleTreeNode> queryTreeRulePoint(Long treeId); }
2302_77879529/lottery
lottery-infrastructure/src/main/java/cn/itedus/lottery/infrastructure/dao/RuleTreeNodeDao.java
Java
apache-2.0
1,047
package cn.itedus.lottery.infrastructure.dao; import cn.itedus.lottery.infrastructure.po.RuleTreeNodeLine; import org.apache.ibatis.annotations.Mapper; import java.util.List; /** * @description: 规则树节点连线DAO * @author: 小傅哥,微信:fustack * @date: 2021/9/22 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ @Mapper public interface RuleTreeNodeLineDao { /** * 查询规则树节点连线集合 * @param req 入参 * @return 规则树节点连线集合 */ List<RuleTreeNodeLine> queryRuleTreeNodeLineList(RuleTreeNodeLine req); /** * 查询规则树连线数量 * * @param treeId 规则树ID * @return 规则树连线数量 */ int queryTreeNodeLineCount(Long treeId); }
2302_77879529/lottery
lottery-infrastructure/src/main/java/cn/itedus/lottery/infrastructure/dao/RuleTreeNodeLineDao.java
Java
apache-2.0
921
package cn.itedus.lottery.infrastructure.po; import java.util.Date; /** * @description: 活动基础信息表 * @author: 小傅哥,微信:fustack * @date: 2021/9/4 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ public class Activity { /** * 自增ID */ private Long id; /** * 活动ID */ private Long activityId; /** * 活动名称 */ private String activityName; /** * 活动描述 */ private String activityDesc; /** * 开始时间 */ private Date beginDateTime; /** * 结束时间 */ private Date endDateTime; /** * 库存 */ private Integer stockCount; /** * 库存剩余 */ private Integer stockSurplusCount; /** * 每人可参与次数 */ private Integer takeCount; /** * 策略ID */ private Long strategyId; /** * 活动状态:1编辑、2提审、3撤审、4通过、5运行(审核通过后worker扫描状态)、6拒绝、7关闭、8开启 */ private Integer state; /** * 创建人 */ private String creator; /** * 创建时间 */ private Date createTime; /** * 修改时间 */ private Date updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getActivityId() { return activityId; } public void setActivityId(Long activityId) { this.activityId = activityId; } public String getActivityName() { return activityName; } public void setActivityName(String activityName) { this.activityName = activityName; } public String getActivityDesc() { return activityDesc; } public void setActivityDesc(String activityDesc) { this.activityDesc = activityDesc; } public Date getBeginDateTime() { return beginDateTime; } public void setBeginDateTime(Date beginDateTime) { this.beginDateTime = beginDateTime; } public Date getEndDateTime() { return endDateTime; } public void setEndDateTime(Date endDateTime) { this.endDateTime = endDateTime; } public Integer getStockCount() { return stockCount; } public void setStockCount(Integer stockCount) { this.stockCount = stockCount; } public Integer getStockSurplusCount() { return stockSurplusCount; } public void setStockSurplusCount(Integer stockSurplusCount) { this.stockSurplusCount = stockSurplusCount; } public Integer getTakeCount() { return takeCount; } public void setTakeCount(Integer takeCount) { this.takeCount = takeCount; } public Long getStrategyId() { return strategyId; } public void setStrategyId(Long strategyId) { this.strategyId = strategyId; } public Integer getState() { return state; } public void setState(Integer state) { this.state = state; } public String getCreator() { return creator; } public void setCreator(String creator) { this.creator = creator; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }
2302_77879529/lottery
lottery-infrastructure/src/main/java/cn/itedus/lottery/infrastructure/po/Activity.java
Java
apache-2.0
3,725
package cn.itedus.lottery.infrastructure.po; import java.util.Date; /** * @description: 奖品表 * @author: 小傅哥,微信:fustack * @date: 2021/9/4 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ public class Award { /** 自增ID */ private Long id; /** 奖品ID */ private String awardId; /** 奖品类型(1:文字描述、2:兑换码、3:优惠券、4:实物奖品) */ private Integer awardType; /** 奖品名称 */ private String awardName; /** 奖品内容「描述、奖品码、sku」 */ private String awardContent; /** 创建时间 */ private Date createTime; /** 修改时间 */ private Date updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getAwardId() { return awardId; } public void setAwardId(String awardId) { this.awardId = awardId; } public Integer getAwardType() { return awardType; } public void setAwardType(Integer awardType) { this.awardType = awardType; } public String getAwardName() { return awardName; } public void setAwardName(String awardName) { this.awardName = awardName; } public String getAwardContent() { return awardContent; } public void setAwardContent(String awardContent) { this.awardContent = awardContent; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }
2302_77879529/lottery
lottery-infrastructure/src/main/java/cn/itedus/lottery/infrastructure/po/Award.java
Java
apache-2.0
1,924
package cn.itedus.lottery.infrastructure.po; import java.util.Date; /** * @description: 规则树 * @author: 小傅哥,微信:fustack * @date: 2021/9/22 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ public class RuleTree { /** 主键ID */ private Long id; /** 规则树名称 */ private String treeName; /** 规则树描述 */ private String treeDesc; /** 规则树根ID */ private Long treeRootNodeId; /** 创建时间 */ private Date createTime; /** 更新时间 */ private Date updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTreeName() { return treeName; } public void setTreeName(String treeName) { this.treeName = treeName; } public String getTreeDesc() { return treeDesc; } public Long getTreeRootNodeId() { return treeRootNodeId; } public void setTreeRootNodeId(Long treeRootNodeId) { this.treeRootNodeId = treeRootNodeId; } public void setTreeDesc(String treeDesc) { this.treeDesc = treeDesc; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }
2302_77879529/lottery
lottery-infrastructure/src/main/java/cn/itedus/lottery/infrastructure/po/RuleTree.java
Java
apache-2.0
1,630
package cn.itedus.lottery.infrastructure.po; /** * @description: 规则树节点 * @author: 小傅哥,微信:fustack * @date: 2021/9/22 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ public class RuleTreeNode { /** 主键ID */ private Long id; /** 规则树ID */ private Long treeId; /** 节点类型;1子叶、2果实 */ private Integer nodeType; /** 节点值[nodeType=2];果实值 */ private String nodeValue; /** 规则Key */ private String ruleKey; /** 规则描述 */ private String ruleDesc; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getTreeId() { return treeId; } public void setTreeId(Long treeId) { this.treeId = treeId; } public Integer getNodeType() { return nodeType; } public void setNodeType(Integer nodeType) { this.nodeType = nodeType; } public String getNodeValue() { return nodeValue; } public void setNodeValue(String nodeValue) { this.nodeValue = nodeValue; } public String getRuleKey() { return ruleKey; } public void setRuleKey(String ruleKey) { this.ruleKey = ruleKey; } public String getRuleDesc() { return ruleDesc; } public void setRuleDesc(String ruleDesc) { this.ruleDesc = ruleDesc; } }
2302_77879529/lottery
lottery-infrastructure/src/main/java/cn/itedus/lottery/infrastructure/po/RuleTreeNode.java
Java
apache-2.0
1,576
package cn.itedus.lottery.infrastructure.po; /** * @description: 规则树节点连线 * @author: 小傅哥,微信:fustack * @date: 2021/9/22 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ public class RuleTreeNodeLine { /** 主键ID */ private Long id; /** 规则树ID */ private Long treeId; /** 节点From */ private Long nodeIdFrom; /** 节点To */ private Long nodeIdTo; /** 限定类型;1:=;2:>;3:<;4:>=;5<=;6:enum[枚举范围] */ private Integer ruleLimitType; /** 限定值 */ private String ruleLimitValue; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getTreeId() { return treeId; } public void setTreeId(Long treeId) { this.treeId = treeId; } public Long getNodeIdFrom() { return nodeIdFrom; } public void setNodeIdFrom(Long nodeIdFrom) { this.nodeIdFrom = nodeIdFrom; } public Long getNodeIdTo() { return nodeIdTo; } public void setNodeIdTo(Long nodeIdTo) { this.nodeIdTo = nodeIdTo; } public Integer getRuleLimitType() { return ruleLimitType; } public void setRuleLimitType(Integer ruleLimitType) { this.ruleLimitType = ruleLimitType; } public String getRuleLimitValue() { return ruleLimitValue; } public void setRuleLimitValue(String ruleLimitValue) { this.ruleLimitValue = ruleLimitValue; } }
2302_77879529/lottery
lottery-infrastructure/src/main/java/cn/itedus/lottery/infrastructure/po/RuleTreeNodeLine.java
Java
apache-2.0
1,662
package cn.itedus.lottery.infrastructure.po; import java.util.Date; /** * @description: 策略配置 * @author: 小傅哥,微信:fustack * @date: 2021/9/4 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ public class Strategy { /** * 自增ID */ private Long id; /** * 策略ID */ private Long strategyId; /** * 策略描述 */ private String strategyDesc; /** * 策略方式「1:单项概率、2:总体概率」 */ private Integer strategyMode; /** * 发放奖品方式「1:即时、2:定时[含活动结束]、3:人工」 */ private Integer grantType; /** * 发放奖品时间 */ private Date grantDate; /** * 扩展信息 */ private String extInfo; /** * 创建时间 */ private Date createTime; /** * 修改时间 */ private Date updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getStrategyId() { return strategyId; } public void setStrategyId(Long strategyId) { this.strategyId = strategyId; } public String getStrategyDesc() { return strategyDesc; } public void setStrategyDesc(String strategyDesc) { this.strategyDesc = strategyDesc; } public Integer getStrategyMode() { return strategyMode; } public void setStrategyMode(Integer strategyMode) { this.strategyMode = strategyMode; } public Integer getGrantType() { return grantType; } public void setGrantType(Integer grantType) { this.grantType = grantType; } public Date getGrantDate() { return grantDate; } public void setGrantDate(Date grantDate) { this.grantDate = grantDate; } public String getExtInfo() { return extInfo; } public void setExtInfo(String extInfo) { this.extInfo = extInfo; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }
2302_77879529/lottery
lottery-infrastructure/src/main/java/cn/itedus/lottery/infrastructure/po/Strategy.java
Java
apache-2.0
2,494
package cn.itedus.lottery.infrastructure.po; import java.math.BigDecimal; import java.util.Date; /** * @description: 策略明细 * @author: 小傅哥,微信:fustack * @date: 2021/9/25 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ public class StrategyDetail { /** * 自增ID */ private Long id; /** * 策略ID */ private Long strategyId; /** * 奖品ID */ private String awardId; /** * 奖品名称 */ private String awardName; /** * 奖品库存 */ private Integer awardCount; /** * 奖品剩余库存 */ private Integer awardSurplusCount; /** * 中奖概率 */ private BigDecimal awardRate; /** * 创建时间 */ private Date createTime; /** * 修改时间 */ private Date updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getStrategyId() { return strategyId; } public void setStrategyId(Long strategyId) { this.strategyId = strategyId; } public String getAwardId() { return awardId; } public void setAwardId(String awardId) { this.awardId = awardId; } public String getAwardName() { return awardName; } public void setAwardName(String awardName) { this.awardName = awardName; } public Integer getAwardCount() { return awardCount; } public void setAwardCount(Integer awardCount) { this.awardCount = awardCount; } public Integer getAwardSurplusCount() { return awardSurplusCount; } public void setAwardSurplusCount(Integer awardSurplusCount) { this.awardSurplusCount = awardSurplusCount; } public BigDecimal getAwardRate() { return awardRate; } public void setAwardRate(BigDecimal awardRate) { this.awardRate = awardRate; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }
2302_77879529/lottery
lottery-infrastructure/src/main/java/cn/itedus/lottery/infrastructure/po/StrategyDetail.java
Java
apache-2.0
2,469
package cn.itedus.lottery.infrastructure.po; import java.util.Date; /** * @description: 用户策略计算结果表 * @author: 小傅哥,微信:fustack * @date: 2021/9/30 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ public class UserStrategyExport { /** 自增ID */ private Long id; /** 用户ID */ private String uId; /** 活动ID */ private Long activityId; /** 订单ID */ private Long orderId; /** 策略ID */ private Long strategyId; /** 策略方式(1:单项概率、2:总体概率) */ private Integer strategyMode; /** 发放奖品方式(1:即时、2:定时[含活动结束]、3:人工) */ private Integer grantType; /** 发奖时间 */ private Date grantDate; /** 发奖状态 */ private Integer grantState; /** 发奖ID */ private String awardId; /** 奖品类型(1:文字描述、2:兑换码、3:优惠券、4:实物奖品) */ private Integer awardType; /** 奖品名称 */ private String awardName; /** 奖品内容「文字描述、Key、码」 */ private String awardContent; /** 防重ID */ private String uuid; /** 消息发送状态(0未发送、1发送成功、2发送失败) */ private Integer MqState; /** 创建时间 */ private Date createTime; /** 更新时间 */ private Date updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getuId() { return uId; } public void setuId(String uId) { this.uId = uId; } public Long getActivityId() { return activityId; } public void setActivityId(Long activityId) { this.activityId = activityId; } public Long getOrderId() { return orderId; } public void setOrderId(Long orderId) { this.orderId = orderId; } public Long getStrategyId() { return strategyId; } public void setStrategyId(Long strategyId) { this.strategyId = strategyId; } public Integer getStrategyMode() { return strategyMode; } public void setStrategyMode(Integer strategyMode) { this.strategyMode = strategyMode; } public Integer getGrantType() { return grantType; } public void setGrantType(Integer grantType) { this.grantType = grantType; } public Date getGrantDate() { return grantDate; } public void setGrantDate(Date grantDate) { this.grantDate = grantDate; } public Integer getGrantState() { return grantState; } public void setGrantState(Integer grantState) { this.grantState = grantState; } public String getAwardId() { return awardId; } public void setAwardId(String awardId) { this.awardId = awardId; } public Integer getAwardType() { return awardType; } public void setAwardType(Integer awardType) { this.awardType = awardType; } public String getAwardName() { return awardName; } public void setAwardName(String awardName) { this.awardName = awardName; } public String getAwardContent() { return awardContent; } public void setAwardContent(String awardContent) { this.awardContent = awardContent; } public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } public Integer getMqState() { return MqState; } public void setMqState(Integer mqState) { MqState = mqState; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }
2302_77879529/lottery
lottery-infrastructure/src/main/java/cn/itedus/lottery/infrastructure/po/UserStrategyExport.java
Java
apache-2.0
4,140
package cn.itedus.lottery.infrastructure.po; import java.util.Date; /** * @description: 用户领取活动表 * @author: 小傅哥,微信:fustack * @date: 2021/9/22 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ public class UserTakeActivity { /** * 自增ID */ private Long id; /** * 用户ID */ private String uId; /** * 活动领取ID */ private Long takeId; /** * 活动ID */ private Long activityId; /** * 活动名称 */ private String activityName; /** * 活动领取时间 */ private Date takeDate; /** * 领取次数 */ private Integer takeCount; /** * 策略ID */ private Long strategyId; /** * 活动单使用状态 0未使用、1已使用 * Constants.TaskState */ private Integer state; /** * 防重ID */ private String uuid; /** * 创建时间 */ private Date createTime; /** * 更新时间 */ private Date updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getuId() { return uId; } public void setuId(String uId) { this.uId = uId; } public Long getTakeId() { return takeId; } public void setTakeId(Long takeId) { this.takeId = takeId; } public Long getActivityId() { return activityId; } public void setActivityId(Long activityId) { this.activityId = activityId; } public String getActivityName() { return activityName; } public void setActivityName(String activityName) { this.activityName = activityName; } public Date getTakeDate() { return takeDate; } public void setTakeDate(Date takeDate) { this.takeDate = takeDate; } public Integer getTakeCount() { return takeCount; } public void setTakeCount(Integer takeCount) { this.takeCount = takeCount; } public Long getStrategyId() { return strategyId; } public void setStrategyId(Long strategyId) { this.strategyId = strategyId; } public Integer getState() { return state; } public void setState(Integer state) { this.state = state; } public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }
2302_77879529/lottery
lottery-infrastructure/src/main/java/cn/itedus/lottery/infrastructure/po/UserTakeActivity.java
Java
apache-2.0
2,995
package cn.itedus.lottery.infrastructure.po; import java.util.Date; /** * @description: 用户活动参与次数表 * @author: 小傅哥,微信:fustack * @date: 2021/10/1 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ public class UserTakeActivityCount { /** * 自增ID */ private Long id; /** * 用户ID */ private String uId; /** * 活动ID */ private Long activityId; /** * 总计可领次数 */ private Integer totalCount; /** * 剩余领取次数 */ private Integer leftCount; /** * 创建时间 */ private Date createTime; /** * 更新时间 */ private Date updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getuId() { return uId; } public void setuId(String uId) { this.uId = uId; } public Long getActivityId() { return activityId; } public void setActivityId(Long activityId) { this.activityId = activityId; } public Integer getTotalCount() { return totalCount; } public void setTotalCount(Integer totalCount) { this.totalCount = totalCount; } public Integer getLeftCount() { return leftCount; } public void setLeftCount(Integer leftCount) { this.leftCount = leftCount; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }
2302_77879529/lottery
lottery-infrastructure/src/main/java/cn/itedus/lottery/infrastructure/po/UserTakeActivityCount.java
Java
apache-2.0
1,912
package cn.itedus.lottery.infrastructure.repository; import cn.itedus.lottery.common.Constants; import cn.itedus.lottery.domain.activity.model.aggregates.ActivityInfoLimitPageRich; import cn.itedus.lottery.domain.activity.model.req.ActivityInfoLimitPageReq; import cn.itedus.lottery.domain.activity.model.req.PartakeReq; import cn.itedus.lottery.domain.activity.model.res.StockResult; import cn.itedus.lottery.domain.activity.model.vo.*; import cn.itedus.lottery.domain.activity.repository.IActivityRepository; import cn.itedus.lottery.infrastructure.dao.*; import cn.itedus.lottery.infrastructure.po.*; import cn.itedus.lottery.infrastructure.util.RedisUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanUtils; import org.springframework.stereotype.Component; import org.springframework.stereotype.Repository; import javax.annotation.Resource; import java.time.Duration; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * @description: * @author: 小傅哥,微信:fustack * @date: 2021/9/11 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ @Repository public class ActivityRepository implements IActivityRepository { private Logger logger = LoggerFactory.getLogger(ActivityRepository.class); @Resource private IActivityDao activityDao; @Resource private IAwardDao awardDao; @Resource private IStrategyDao strategyDao; @Resource private IStrategyDetailDao strategyDetailDao; @Resource private IUserTakeActivityCountDao userTakeActivityCountDao; @Resource private RedisUtil redisUtil; @Override public void addActivity(ActivityVO activity) { Activity req = new Activity(); req.setId(activity.getId()); req.setActivityId(activity.getActivityId()); req.setActivityName(activity.getActivityName()); req.setActivityDesc(activity.getActivityDesc()); req.setBeginDateTime(activity.getBeginDateTime()); req.setEndDateTime(activity.getEndDateTime()); req.setStockCount(activity.getStockCount()); req.setStockSurplusCount(activity.getStockSurplusCount()); req.setTakeCount(activity.getTakeCount()); req.setStrategyId(activity.getStrategyId()); req.setState(activity.getState()); req.setCreator(activity.getCreator()); req.setCreateTime(activity.getCreateTime()); req.setUpdateTime(activity.getUpdateTime()); activityDao.insert(req); // 设置活动库存 KEY redisUtil.set(Constants.RedisKey.KEY_LOTTERY_ACTIVITY_STOCK_COUNT(activity.getActivityId()), 0); } @Override public void addAward(List<AwardVO> awardList) { List<Award> req = new ArrayList<>(); for (AwardVO awardVO : awardList) { Award award = new Award(); award.setAwardId(awardVO.getAwardId()); award.setAwardType(awardVO.getAwardType()); award.setAwardName(awardVO.getAwardName()); award.setAwardContent(awardVO.getAwardContent()); req.add(award); } awardDao.insertList(req); } @Override public void addStrategy(StrategyVO strategy) { Strategy req = new Strategy(); req.setStrategyId(strategy.getStrategyId()); req.setStrategyDesc(strategy.getStrategyDesc()); req.setStrategyMode(strategy.getStrategyMode()); req.setGrantType(strategy.getGrantType()); req.setGrantDate(strategy.getGrantDate()); req.setExtInfo(strategy.getExtInfo()); strategyDao.insert(req); } @Override public void addStrategyDetailList(List<StrategyDetailVO> strategyDetailList) { List<StrategyDetail> req = new ArrayList<>(); for (StrategyDetailVO strategyDetailVO : strategyDetailList) { StrategyDetail strategyDetail = new StrategyDetail(); strategyDetail.setStrategyId(strategyDetailVO.getStrategyId()); strategyDetail.setAwardId(strategyDetailVO.getAwardId()); strategyDetail.setAwardName(strategyDetailVO.getAwardName()); strategyDetail.setAwardCount(strategyDetailVO.getAwardCount()); strategyDetail.setAwardSurplusCount(strategyDetailVO.getAwardSurplusCount()); strategyDetail.setAwardRate(strategyDetailVO.getAwardRate()); req.add(strategyDetail); } strategyDetailDao.insertList(req); } @Override public boolean alterStatus(Long activityId, Enum<Constants.ActivityState> beforeState, Enum<Constants.ActivityState> afterState) { AlterStateVO alterStateVO = new AlterStateVO(activityId, ((Constants.ActivityState) beforeState).getCode(), ((Constants.ActivityState) afterState).getCode()); int count = activityDao.alterState(alterStateVO); return 1 == count; } @Override public ActivityBillVO queryActivityBill(PartakeReq req) { // 查询活动信息 Activity activity = activityDao.queryActivityById(req.getActivityId()); // 从缓存中获取库存 Object usedStockCountObj = redisUtil.get(Constants.RedisKey.KEY_LOTTERY_ACTIVITY_STOCK_COUNT(req.getActivityId())); // 查询领取次数 UserTakeActivityCount userTakeActivityCountReq = new UserTakeActivityCount(); userTakeActivityCountReq.setuId(req.getuId()); userTakeActivityCountReq.setActivityId(req.getActivityId()); UserTakeActivityCount userTakeActivityCount = userTakeActivityCountDao.queryUserTakeActivityCount(userTakeActivityCountReq); // 封装结果信息 ActivityBillVO activityBillVO = new ActivityBillVO(); activityBillVO.setuId(req.getuId()); activityBillVO.setActivityId(req.getActivityId()); activityBillVO.setActivityName(activity.getActivityName()); activityBillVO.setBeginDateTime(activity.getBeginDateTime()); activityBillVO.setEndDateTime(activity.getEndDateTime()); activityBillVO.setTakeCount(activity.getTakeCount()); activityBillVO.setStockCount(activity.getStockCount()); activityBillVO.setStockSurplusCount(null == usedStockCountObj ? activity.getStockSurplusCount() : activity.getStockCount() - Integer.parseInt(String.valueOf(usedStockCountObj))); activityBillVO.setStrategyId(activity.getStrategyId()); activityBillVO.setState(activity.getState()); activityBillVO.setUserTakeLeftCount(null == userTakeActivityCount ? null : userTakeActivityCount.getLeftCount()); return activityBillVO; } @Override public int subtractionActivityStock(Long activityId) { return activityDao.subtractionActivityStock(activityId); } @Override public List<ActivityVO> scanToDoActivityList(Long id) { List<Activity> activityList = activityDao.scanToDoActivityList(id); List<ActivityVO> activityVOList = new ArrayList<>(activityList.size()); for (Activity activity : activityList) { ActivityVO activityVO = new ActivityVO(); activityVO.setId(activity.getId()); activityVO.setActivityId(activity.getActivityId()); activityVO.setActivityName(activity.getActivityName()); activityVO.setBeginDateTime(activity.getBeginDateTime()); activityVO.setEndDateTime(activity.getEndDateTime()); activityVO.setState(activity.getState()); activityVOList.add(activityVO); } return activityVOList; } @Override public StockResult subtractionActivityStockByRedis(String uId, Long activityId, Integer stockCount, Date endDateTime) { // 1. 获取抽奖活动库存 Key String stockKey = Constants.RedisKey.KEY_LOTTERY_ACTIVITY_STOCK_COUNT(activityId); // 2. 扣减库存,目前占用库存数。「给incr的结果加一层分段锁,在不影响性能的情况下,会可靠。以往压测tps 2500 ~ 5000 计算结果 1 + 100万,最终结果不是100万,不过可能因环境导致」 Integer stockUsedCount = (int) redisUtil.incr(stockKey, 1); // 3. 超出库存判断,进行恢复原始库存 if (stockUsedCount > stockCount) { redisUtil.decr(stockKey, 1); return new StockResult(Constants.ResponseCode.OUT_OF_STOCK.getCode(), Constants.ResponseCode.OUT_OF_STOCK.getInfo()); } // 4. 以活动库存占用编号,生成对应加锁Key,细化锁的颗粒度 String stockTokenKey = Constants.RedisKey.KEY_LOTTERY_ACTIVITY_STOCK_COUNT_TOKEN(activityId, stockUsedCount); // 5. 使用 Redis.setNx 加一个分布式锁;以活动结束时间,设定锁的有效时间。个人占用的锁,不需要被释放。 long milliseconds = endDateTime.getTime() - System.currentTimeMillis(); boolean lockToken = redisUtil.setNx(stockTokenKey, milliseconds); if (!lockToken) { logger.info("抽奖活动{}用户秒杀{}扣减库存,分布式锁失败:{}", activityId, uId, stockTokenKey); return new StockResult(Constants.ResponseCode.ERR_TOKEN.getCode(), Constants.ResponseCode.ERR_TOKEN.getInfo()); } return new StockResult(Constants.ResponseCode.SUCCESS.getCode(), Constants.ResponseCode.SUCCESS.getInfo(), stockTokenKey, stockCount - stockUsedCount); } @Override public void recoverActivityCacheStockByRedis(Long activityId, String tokenKey, String code) { if (null == tokenKey) { return; } // 删除分布式锁 Key redisUtil.del(tokenKey); } @Override public ActivityInfoLimitPageRich queryActivityInfoLimitPage(ActivityInfoLimitPageReq req) { Long count = activityDao.queryActivityInfoCount(req); List<Activity> list = activityDao.queryActivityInfoList(req); List<ActivityVO> activityVOList = new ArrayList<>(); for (Activity activity : list) { ActivityVO activityVO = new ActivityVO(); activityVO.setId(activity.getId()); activityVO.setActivityId(activity.getActivityId()); activityVO.setActivityName(activity.getActivityName()); activityVO.setActivityDesc(activity.getActivityDesc()); activityVO.setBeginDateTime(activity.getBeginDateTime()); activityVO.setEndDateTime(activity.getEndDateTime()); activityVO.setStockCount(activity.getStockCount()); activityVO.setStockSurplusCount(activity.getStockSurplusCount()); activityVO.setTakeCount(activity.getTakeCount()); activityVO.setStrategyId(activity.getStrategyId()); activityVO.setState(activity.getState()); activityVO.setCreator(activity.getCreator()); activityVO.setCreateTime(activity.getCreateTime()); activityVO.setUpdateTime(activity.getUpdateTime()); activityVOList.add(activityVO); } return new ActivityInfoLimitPageRich(count, activityVOList); } }
2302_77879529/lottery
lottery-infrastructure/src/main/java/cn/itedus/lottery/infrastructure/repository/ActivityRepository.java
Java
apache-2.0
11,214
package cn.itedus.lottery.infrastructure.repository; import cn.itedus.lottery.domain.award.repository.IOrderRepository; import cn.itedus.lottery.infrastructure.dao.IUserStrategyExportDao; import cn.itedus.lottery.infrastructure.po.UserStrategyExport; import org.springframework.stereotype.Component; import org.springframework.stereotype.Repository; import javax.annotation.Resource; import java.util.Date; /** * @description: 奖品表仓储服务 * @author: 小傅哥,微信:fustack * @date: 2021/9/4 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ @Repository public class OrderRepository implements IOrderRepository { @Resource private IUserStrategyExportDao userStrategyExportDao; @Override public void updateUserAwardState(String uId, Long orderId, String awardId, Integer grantState) { UserStrategyExport userStrategyExport = new UserStrategyExport(); userStrategyExport.setuId(uId); userStrategyExport.setOrderId(orderId); userStrategyExport.setAwardId(awardId); userStrategyExport.setGrantState(grantState); userStrategyExportDao.updateUserAwardState(userStrategyExport); } }
2302_77879529/lottery
lottery-infrastructure/src/main/java/cn/itedus/lottery/infrastructure/repository/OrderRepository.java
Java
apache-2.0
1,308
package cn.itedus.lottery.infrastructure.repository; import cn.itedus.lottery.common.Constants; import cn.itedus.lottery.domain.rule.model.aggregates.TreeRuleRich; import cn.itedus.lottery.domain.rule.model.vo.TreeNodeVO; import cn.itedus.lottery.domain.rule.model.vo.TreeNodeLineVO; import cn.itedus.lottery.domain.rule.model.vo.TreeRootVO; import cn.itedus.lottery.domain.rule.repository.IRuleRepository; import cn.itedus.lottery.infrastructure.dao.RuleTreeDao; import cn.itedus.lottery.infrastructure.dao.RuleTreeNodeDao; import cn.itedus.lottery.infrastructure.dao.RuleTreeNodeLineDao; import cn.itedus.lottery.infrastructure.po.RuleTree; import cn.itedus.lottery.infrastructure.po.RuleTreeNode; import cn.itedus.lottery.infrastructure.po.RuleTreeNodeLine; import org.springframework.stereotype.Repository; import javax.annotation.Resource; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @description: 规则信息仓储服务 * @author: 小傅哥,微信:fustack * @date: 2021/10/8 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ @Repository public class RuleRepository implements IRuleRepository { @Resource private RuleTreeDao ruleTreeDao; @Resource private RuleTreeNodeDao ruleTreeNodeDao; @Resource private RuleTreeNodeLineDao ruleTreeNodeLineDao; @Override public TreeRuleRich queryTreeRuleRich(Long treeId) { // 规则树 RuleTree ruleTree = ruleTreeDao.queryRuleTreeByTreeId(treeId); TreeRootVO treeRoot = new TreeRootVO(); treeRoot.setTreeId(ruleTree.getId()); treeRoot.setTreeRootNodeId(ruleTree.getTreeRootNodeId()); treeRoot.setTreeName(ruleTree.getTreeName()); // 树节点->树连接线 Map<Long, TreeNodeVO> treeNodeMap = new HashMap<>(); List<RuleTreeNode> ruleTreeNodeList = ruleTreeNodeDao.queryRuleTreeNodeList(treeId); for (RuleTreeNode treeNode : ruleTreeNodeList) { List<TreeNodeLineVO> treeNodeLineInfoList = new ArrayList<>(); if (Constants.NodeType.STEM.equals(treeNode.getNodeType())) { RuleTreeNodeLine ruleTreeNodeLineReq = new RuleTreeNodeLine(); ruleTreeNodeLineReq.setTreeId(treeId); ruleTreeNodeLineReq.setNodeIdFrom(treeNode.getId()); List<RuleTreeNodeLine> ruleTreeNodeLineList = ruleTreeNodeLineDao.queryRuleTreeNodeLineList(ruleTreeNodeLineReq); for (RuleTreeNodeLine nodeLine : ruleTreeNodeLineList) { TreeNodeLineVO treeNodeLineInfo = new TreeNodeLineVO(); treeNodeLineInfo.setNodeIdFrom(nodeLine.getNodeIdFrom()); treeNodeLineInfo.setNodeIdTo(nodeLine.getNodeIdTo()); treeNodeLineInfo.setRuleLimitType(nodeLine.getRuleLimitType()); treeNodeLineInfo.setRuleLimitValue(nodeLine.getRuleLimitValue()); treeNodeLineInfoList.add(treeNodeLineInfo); } } TreeNodeVO treeNodeInfo = new TreeNodeVO(); treeNodeInfo.setTreeId(treeNode.getTreeId()); treeNodeInfo.setTreeNodeId(treeNode.getId()); treeNodeInfo.setNodeType(treeNode.getNodeType()); treeNodeInfo.setNodeValue(treeNode.getNodeValue()); treeNodeInfo.setRuleKey(treeNode.getRuleKey()); treeNodeInfo.setRuleDesc(treeNode.getRuleDesc()); treeNodeInfo.setTreeNodeLineInfoList(treeNodeLineInfoList); treeNodeMap.put(treeNode.getId(), treeNodeInfo); } TreeRuleRich treeRuleRich = new TreeRuleRich(); treeRuleRich.setTreeRoot(treeRoot); treeRuleRich.setTreeNodeMap(treeNodeMap); return treeRuleRich; } }
2302_77879529/lottery
lottery-infrastructure/src/main/java/cn/itedus/lottery/infrastructure/repository/RuleRepository.java
Java
apache-2.0
3,923
package cn.itedus.lottery.infrastructure.repository; import cn.itedus.lottery.domain.strategy.model.aggregates.StrategyRich; import cn.itedus.lottery.domain.strategy.model.vo.AwardBriefVO; import cn.itedus.lottery.domain.strategy.model.vo.StrategyBriefVO; import cn.itedus.lottery.domain.strategy.model.vo.StrategyDetailBriefVO; import cn.itedus.lottery.domain.strategy.repository.IStrategyRepository; import cn.itedus.lottery.infrastructure.dao.IAwardDao; import cn.itedus.lottery.infrastructure.dao.IStrategyDao; import cn.itedus.lottery.infrastructure.dao.IStrategyDetailDao; import cn.itedus.lottery.infrastructure.po.Award; import cn.itedus.lottery.infrastructure.po.Strategy; import cn.itedus.lottery.infrastructure.po.StrategyDetail; import org.springframework.beans.BeanUtils; import org.springframework.stereotype.Component; import org.springframework.stereotype.Repository; import javax.annotation.Resource; import java.util.ArrayList; import java.util.List; /** * @description: 策略表仓储服务 * @author:小傅哥,微信:fustack * @date: 2021/8/28 * @Copyright:公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ @Repository public class StrategyRepository implements IStrategyRepository { @Resource private IStrategyDao strategyDao; @Resource private IStrategyDetailDao strategyDetailDao; @Resource private IAwardDao awardDao; @Override public StrategyRich queryStrategyRich(Long strategyId) { Strategy strategy = strategyDao.queryStrategy(strategyId); List<StrategyDetail> strategyDetailList = strategyDetailDao.queryStrategyDetailList(strategyId); StrategyBriefVO strategyBriefVO = new StrategyBriefVO(); strategyBriefVO.setStrategyId(strategy.getStrategyId()); strategyBriefVO.setStrategyDesc(strategy.getStrategyDesc()); strategyBriefVO.setStrategyMode(strategy.getStrategyMode()); strategyBriefVO.setGrantType(strategy.getGrantType()); strategyBriefVO.setGrantDate(strategy.getGrantDate()); strategyBriefVO.setExtInfo(strategy.getExtInfo()); List<StrategyDetailBriefVO> strategyDetailBriefVOList = new ArrayList<>(); for (StrategyDetail strategyDetail : strategyDetailList) { StrategyDetailBriefVO strategyDetailBriefVO = new StrategyDetailBriefVO(); strategyDetailBriefVO.setStrategyId(strategyDetail.getStrategyId()); strategyDetailBriefVO.setAwardId(strategyDetail.getAwardId()); strategyDetailBriefVO.setAwardName(strategyDetail.getAwardName()); strategyDetailBriefVO.setAwardCount(strategyDetail.getAwardCount()); strategyDetailBriefVO.setAwardSurplusCount(strategyDetail.getAwardSurplusCount()); strategyDetailBriefVO.setAwardRate(strategyDetail.getAwardRate()); strategyDetailBriefVOList.add(strategyDetailBriefVO); } return new StrategyRich(strategyId, strategyBriefVO, strategyDetailBriefVOList); } @Override public AwardBriefVO queryAwardInfo(String awardId) { Award award = awardDao.queryAwardInfo(awardId); // 可以使用 BeanUtils.copyProperties(award, awardBriefVO)、或者基于ASM实现的Bean-Mapping,但在效率上最好的依旧是硬编码 // 以使用自研 vo2dto 插件,帮助生成 x.set(y.get) 插件安装包:https://github.com/fuzhengwei/guide-idea-plugin/releases/tag/v2.0.2 AwardBriefVO awardBriefVO = new AwardBriefVO(); awardBriefVO.setAwardId(award.getAwardId()); awardBriefVO.setAwardType(award.getAwardType()); awardBriefVO.setAwardName(award.getAwardName()); awardBriefVO.setAwardContent(award.getAwardContent()); return awardBriefVO; } @Override public List<String> queryNoStockStrategyAwardList(Long strategyId) { return strategyDetailDao.queryNoStockStrategyAwardList(strategyId); } @Override public boolean deductStock(Long strategyId, String awardId) { StrategyDetail req = new StrategyDetail(); req.setStrategyId(strategyId); req.setAwardId(awardId); int count = strategyDetailDao.deductStock(req); return count == 1; } }
2302_77879529/lottery
lottery-infrastructure/src/main/java/cn/itedus/lottery/infrastructure/repository/StrategyRepository.java
Java
apache-2.0
4,300
package cn.itedus.lottery.infrastructure.repository; import cn.itedus.lottery.common.Constants; import cn.itedus.lottery.domain.activity.model.vo.ActivityPartakeRecordVO; import cn.itedus.lottery.domain.activity.model.vo.DrawOrderVO; import cn.itedus.lottery.domain.activity.model.vo.InvoiceVO; import cn.itedus.lottery.domain.activity.model.vo.UserTakeActivityVO; import cn.itedus.lottery.domain.activity.repository.IUserTakeActivityRepository; import cn.itedus.lottery.infrastructure.dao.IActivityDao; import cn.itedus.lottery.infrastructure.dao.IUserStrategyExportDao; import cn.itedus.lottery.infrastructure.dao.IUserTakeActivityCountDao; import cn.itedus.lottery.infrastructure.dao.IUserTakeActivityDao; import cn.itedus.lottery.infrastructure.po.Activity; import cn.itedus.lottery.infrastructure.po.UserStrategyExport; import cn.itedus.lottery.infrastructure.po.UserTakeActivity; import cn.itedus.lottery.infrastructure.po.UserTakeActivityCount; import org.springframework.stereotype.Component; import org.springframework.stereotype.Repository; import javax.annotation.Resource; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * @description: 用户参与活动仓储 * @author: 小傅哥,微信:fustack * @date: 2021/10/1 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ @Repository public class UserTakeActivityRepository implements IUserTakeActivityRepository { @Resource private IActivityDao activityDao; @Resource private IUserTakeActivityCountDao userTakeActivityCountDao; @Resource private IUserTakeActivityDao userTakeActivityDao; @Resource private IUserStrategyExportDao userStrategyExportDao; @Override public int subtractionLeftCount(Long activityId, String activityName, Integer takeCount, Integer userTakeLeftCount, String uId) { if (null == userTakeLeftCount) { UserTakeActivityCount userTakeActivityCount = new UserTakeActivityCount(); userTakeActivityCount.setuId(uId); userTakeActivityCount.setActivityId(activityId); userTakeActivityCount.setTotalCount(takeCount); userTakeActivityCount.setLeftCount(takeCount - 1); userTakeActivityCountDao.insert(userTakeActivityCount); return 1; } else { UserTakeActivityCount userTakeActivityCount = new UserTakeActivityCount(); userTakeActivityCount.setuId(uId); userTakeActivityCount.setActivityId(activityId); return userTakeActivityCountDao.updateLeftCount(userTakeActivityCount); } } @Override public void takeActivity(Long activityId, String activityName, Long strategyId, Integer takeCount, Integer userTakeLeftCount, String uId, Date takeDate, Long takeId) { UserTakeActivity userTakeActivity = new UserTakeActivity(); userTakeActivity.setuId(uId); userTakeActivity.setTakeId(takeId); userTakeActivity.setActivityId(activityId); userTakeActivity.setActivityName(activityName); userTakeActivity.setTakeDate(takeDate); if (null == userTakeLeftCount) { userTakeActivity.setTakeCount(1); } else { userTakeActivity.setTakeCount(takeCount - userTakeLeftCount + 1); } userTakeActivity.setStrategyId(strategyId); userTakeActivity.setState(Constants.TaskState.NO_USED.getCode()); String uuid = uId + "_" + activityId + "_" + userTakeActivity.getTakeCount(); userTakeActivity.setUuid(uuid); userTakeActivityDao.insert(userTakeActivity); } @Override public int lockTackActivity(String uId, Long activityId, Long takeId) { UserTakeActivity userTakeActivity = new UserTakeActivity(); userTakeActivity.setuId(uId); userTakeActivity.setActivityId(activityId); userTakeActivity.setTakeId(takeId); return userTakeActivityDao.lockTackActivity(userTakeActivity); } @Override public void saveUserStrategyExport(DrawOrderVO drawOrder) { UserStrategyExport userStrategyExport = new UserStrategyExport(); userStrategyExport.setuId(drawOrder.getuId()); userStrategyExport.setActivityId(drawOrder.getActivityId()); userStrategyExport.setOrderId(drawOrder.getOrderId()); userStrategyExport.setStrategyId(drawOrder.getStrategyId()); userStrategyExport.setStrategyMode(drawOrder.getStrategyMode()); userStrategyExport.setGrantType(drawOrder.getGrantType()); userStrategyExport.setGrantDate(drawOrder.getGrantDate()); userStrategyExport.setGrantState(drawOrder.getGrantState()); userStrategyExport.setAwardId(drawOrder.getAwardId()); userStrategyExport.setAwardType(drawOrder.getAwardType()); userStrategyExport.setAwardName(drawOrder.getAwardName()); userStrategyExport.setAwardContent(drawOrder.getAwardContent()); userStrategyExport.setUuid(String.valueOf(drawOrder.getTakeId())); userStrategyExport.setMqState(Constants.MQState.INIT.getCode()); userStrategyExportDao.insert(userStrategyExport); } @Override public UserTakeActivityVO queryNoConsumedTakeActivityOrder(Long activityId, String uId) { UserTakeActivity userTakeActivity = new UserTakeActivity(); userTakeActivity.setuId(uId); userTakeActivity.setActivityId(activityId); UserTakeActivity noConsumedTakeActivityOrder = userTakeActivityDao.queryNoConsumedTakeActivityOrder(userTakeActivity); // 未查询到符合的领取单,直接返回 NULL if (null == noConsumedTakeActivityOrder) { return null; } UserTakeActivityVO userTakeActivityVO = new UserTakeActivityVO(); userTakeActivityVO.setActivityId(noConsumedTakeActivityOrder.getActivityId()); userTakeActivityVO.setTakeId(noConsumedTakeActivityOrder.getTakeId()); userTakeActivityVO.setStrategyId(noConsumedTakeActivityOrder.getStrategyId()); userTakeActivityVO.setState(noConsumedTakeActivityOrder.getState()); return userTakeActivityVO; } @Override public void updateInvoiceMqState(String uId, Long orderId, Integer mqState) { UserStrategyExport userStrategyExport = new UserStrategyExport(); userStrategyExport.setuId(uId); userStrategyExport.setOrderId(orderId); userStrategyExport.setMqState(mqState); userStrategyExportDao.updateInvoiceMqState(userStrategyExport); } @Override public List<InvoiceVO> scanInvoiceMqState() { // 查询发送MQ失败和超时30分钟,未发送MQ的数据 List<UserStrategyExport> userStrategyExportList = userStrategyExportDao.scanInvoiceMqState(); // 转换对象 List<InvoiceVO> invoiceVOList = new ArrayList<>(userStrategyExportList.size()); for (UserStrategyExport userStrategyExport : userStrategyExportList) { InvoiceVO invoiceVO = new InvoiceVO(); invoiceVO.setuId(userStrategyExport.getuId()); invoiceVO.setOrderId(userStrategyExport.getOrderId()); invoiceVO.setAwardId(userStrategyExport.getAwardId()); invoiceVO.setAwardType(userStrategyExport.getAwardType()); invoiceVO.setAwardName(userStrategyExport.getAwardName()); invoiceVO.setAwardContent(userStrategyExport.getAwardContent()); invoiceVOList.add(invoiceVO); } return invoiceVOList; } @Override public void updateActivityStock(ActivityPartakeRecordVO activityPartakeRecordVO) { Activity activity = new Activity(); activity.setActivityId(activityPartakeRecordVO.getActivityId()); activity.setStockSurplusCount(activityPartakeRecordVO.getStockSurplusCount()); activityDao.updateActivityStock(activity); } }
2302_77879529/lottery
lottery-infrastructure/src/main/java/cn/itedus/lottery/infrastructure/repository/UserTakeActivityRepository.java
Java
apache-2.0
7,996
package cn.itedus.lottery.infrastructure.util; import org.springframework.data.redis.core.BoundListOperations; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import javax.annotation.Resource; import java.util.*; import java.util.concurrent.TimeUnit; /** * @description: Redis 工具类 * @author: 小傅哥,微信:fustack * @date: 2021/11/20 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ @Component public class RedisUtil { @Resource private RedisTemplate<String, Object> redisTemplate; public RedisUtil(RedisTemplate<String, Object> redisTemplate) { this.redisTemplate = redisTemplate; } /** * 指定缓存失效时间 * * @param key 键 * @param time 时间(秒) * @return */ public boolean expire(String key, long time) { try { if (time > 0) { redisTemplate.expire(key, time, TimeUnit.SECONDS); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 根据key 获取过期时间 * * @param key 键 不能为null * @return 时间(秒) 返回0代表为永久有效 */ public long getExpire(String key) { return redisTemplate.getExpire(key, TimeUnit.SECONDS); } /** * 判断key是否存在 * * @param key 键 * @return true 存在 false不存在 */ public boolean hasKey(String key) { try { return redisTemplate.hasKey(key); } catch (Exception e) { e.printStackTrace(); return false; } } /** * 删除缓存 * * @param key 可以传一个值 或多个 */ @SuppressWarnings("unchecked") public void del(String... key) { if (key != null && key.length > 0) { if (key.length == 1) { redisTemplate.delete(key[0]); } else { redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key)); } } } //============================String============================= /** * 普通缓存获取 * * @param key 键 * @return 值 */ public Object get(String key) { return key == null ? null : redisTemplate.opsForValue().get(key); } /** * 普通缓存放入 * * @param key 键 * @param value 值 * @return true成功 false失败 */ public boolean set(String key, Object value) { try { redisTemplate.opsForValue().set(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 普通缓存放入并设置时间 * * @param key 键 * @param value 值 * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期 * @return true成功 false 失败 */ public boolean set(String key, Object value, long time) { try { if (time > 0) { redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS); } else { set(key, value); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 分布式锁 * @param key 锁住的key * @param lockExpireMils 锁住的时长。如果超时未解锁,视为加锁线程死亡,其他线程可夺取锁 * @return */ public boolean setNx(String key, Long lockExpireMils) { return (boolean) redisTemplate.execute((RedisCallback) connection -> { //获取锁 return connection.setNX(key.getBytes(), String.valueOf(System.currentTimeMillis() + lockExpireMils + 1).getBytes()); }); } /** * 递增 * * @param key 键 * @param delta 要增加几(大于0) * @return */ public long incr(String key, long delta) { if (delta < 0) { throw new RuntimeException("递增因子必须大于0"); } return redisTemplate.opsForValue().increment(key, delta); } /** * 递减 * * @param key 键 * @param delta 要减少几(小于0) * @return */ public long decr(String key, long delta) { if (delta < 0) { throw new RuntimeException("递减因子必须大于0"); } return redisTemplate.opsForValue().increment(key, -delta); } //================================Map================================= /** * HashGet * * @param key 键 不能为null * @param item 项 不能为null * @return 值 */ public Object hget(String key, String item) { return redisTemplate.opsForHash().get(key, item); } /** * 获取hashKey对应的所有键值 * * @param key 键 * @return 对应的多个键值 */ public Map<Object, Object> hmget(String key) { return redisTemplate.opsForHash().entries(key); } /** * HashSet * * @param key 键 * @param map 对应多个键值 * @return true 成功 false 失败 */ public boolean hmset(String key, Map<String, Object> map) { try { redisTemplate.opsForHash().putAll(key, map); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * HashSet 并设置时间 * * @param key 键 * @param map 对应多个键值 * @param time 时间(秒) * @return true成功 false失败 */ public boolean hmset(String key, Map<String, Object> map, long time) { try { redisTemplate.opsForHash().putAll(key, map); if (time > 0) { expire(key, time); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 向一张hash表中放入数据,如果不存在将创建 * * @param key 键 * @param item 项 * @param value 值 * @return true 成功 false失败 */ public boolean hset(String key, String item, Object value) { try { redisTemplate.opsForHash().put(key, item, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 向一张hash表中放入数据,如果不存在将创建 * * @param key 键 * @param item 项 * @param value 值 * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间 * @return true 成功 false失败 */ public boolean hset(String key, String item, Object value, long time) { try { redisTemplate.opsForHash().put(key, item, value); if (time > 0) { expire(key, time); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 删除hash表中的值 * * @param key 键 不能为null * @param item 项 可以使多个 不能为null */ public void hdel(String key, Object... item) { redisTemplate.opsForHash().delete(key, item); } /** * 判断hash表中是否有该项的值 * * @param key 键 不能为null * @param item 项 不能为null * @return true 存在 false不存在 */ public boolean hHasKey(String key, String item) { return redisTemplate.opsForHash().hasKey(key, item); } /** * hash递增 如果不存在,就会创建一个 并把新增后的值返回 * * @param key 键 * @param item 项 * @param by 要增加几(大于0) * @return */ public double hincr(String key, String item, double by) { return redisTemplate.opsForHash().increment(key, item, by); } /** * hash递减 * * @param key 键 * @param item 项 * @param by 要减少记(小于0) * @return */ public double hdecr(String key, String item, double by) { return redisTemplate.opsForHash().increment(key, item, -by); } //============================set============================= /** * 根据key获取Set中的所有值 * * @param key 键 * @return */ public Set<Object> sGet(String key) { try { return redisTemplate.opsForSet().members(key); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 根据value从一个set中查询,是否存在 * * @param key 键 * @param value 值 * @return true 存在 false不存在 */ public boolean sHasKey(String key, Object value) { try { return redisTemplate.opsForSet().isMember(key, value); } catch (Exception e) { e.printStackTrace(); return false; } } /** * 将数据放入set缓存 * * @param key 键 * @param values 值 可以是多个 * @return 成功个数 */ public long sSet(String key, Object... values) { try { return redisTemplate.opsForSet().add(key, values); } catch (Exception e) { e.printStackTrace(); return 0; } } /** * 将set数据放入缓存 * * @param key 键 * @param time 时间(秒) * @param values 值 可以是多个 * @return 成功个数 */ public long sSetAndTime(String key, long time, Object... values) { try { Long count = redisTemplate.opsForSet().add(key, values); if (time > 0) { expire(key, time); } return count; } catch (Exception e) { e.printStackTrace(); return 0; } } /** * 获取set缓存的长度 * * @param key 键 * @return */ public long sGetSetSize(String key) { try { return redisTemplate.opsForSet().size(key); } catch (Exception e) { e.printStackTrace(); return 0; } } /** * 移除值为value的 * * @param key 键 * @param values 值 可以是多个 * @return 移除的个数 */ public long setRemove(String key, Object... values) { try { Long count = redisTemplate.opsForSet().remove(key, values); return count; } catch (Exception e) { e.printStackTrace(); return 0; } } //===============================list================================= /** * 获取list缓存的内容 * * @param key 键 * @param start 开始 * @param end 结束 0 到 -1代表所有值 * @return */ public List<Object> lGet(String key, long start, long end) { try { return redisTemplate.opsForList().range(key, start, end); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 获取list缓存的长度 * * @param key 键 * @return */ public long lGetListSize(String key) { try { return redisTemplate.opsForList().size(key); } catch (Exception e) { e.printStackTrace(); return 0; } } /** * 通过索引 获取list中的值 * * @param key 键 * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推 * @return */ public Object lGetIndex(String key, long index) { try { return redisTemplate.opsForList().index(key, index); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 将list放入缓存 * * @param key 键 * @param value 值 * @return */ public boolean lSet(String key, Object value) { try { redisTemplate.opsForList().rightPush(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 将list放入缓存 * * @param key 键 * @param value 值 * @param time 时间(秒) * @return */ public boolean lSet(String key, Object value, long time) { try { redisTemplate.opsForList().rightPush(key, value); if (time > 0) { expire(key, time); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 将list放入缓存 * * @param key 键 * @param value 值 * @return */ public boolean lSet(String key, List<Object> value) { try { redisTemplate.opsForList().rightPushAll(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 将list放入缓存 * * @param key 键 * @param value 值 * @param time 时间(秒) * @return */ public boolean lSet(String key, List<Object> value, long time) { try { redisTemplate.opsForList().rightPushAll(key, value); if (time > 0) { expire(key, time); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 根据索引修改list中的某条数据 * * @param key 键 * @param index 索引 * @param value 值 * @return */ public boolean lUpdateIndex(String key, long index, Object value) { try { redisTemplate.opsForList().set(key, index, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 移除N个值为value * * @param key 键 * @param count 移除多少个 * @param value 值 * @return 移除的个数 */ public long lRemove(String key, long count, Object value) { try { Long remove = redisTemplate.opsForList().remove(key, count, value); return remove; } catch (Exception e) { e.printStackTrace(); return 0; } } /** * 模糊查询获取key值 * * @param pattern * @return */ public Set keys(String pattern) { return redisTemplate.keys(pattern); } /** * 使用Redis的消息队列 * * @param channel * @param message 消息内容 */ public void convertAndSend(String channel, Object message) { redisTemplate.convertAndSend(channel, message); } //=========BoundListOperations 用法 start============ /** * 将数据添加到Redis的list中(从右边添加) * * @param listKey * @param timeout 有效时间 * @param unit 时间类型 * @param values 待添加的数据 */ public void addToListRight(String listKey, long timeout, TimeUnit unit, Object... values) { //绑定操作 BoundListOperations<String, Object> boundValueOperations = redisTemplate.boundListOps(listKey); //插入数据 boundValueOperations.rightPushAll(values); //设置过期时间 boundValueOperations.expire(timeout, unit); } /** * 根据起始结束序号遍历Redis中的list * * @param listKey * @param start 起始序号 * @param end 结束序号 * @return */ public List<Object> rangeList(String listKey, long start, long end) { //绑定操作 BoundListOperations<String, Object> boundValueOperations = redisTemplate.boundListOps(listKey); //查询数据 return boundValueOperations.range(start, end); } /** * 弹出右边的值 --- 并且移除这个值 * * @param listKey */ public Object rightPop(String listKey) { //绑定操作 BoundListOperations<String, Object> boundValueOperations = redisTemplate.boundListOps(listKey); return boundValueOperations.rightPop(); } //=========BoundListOperations 用法 End============ }
2302_77879529/lottery
lottery-infrastructure/src/main/java/cn/itedus/lottery/infrastructure/util/RedisUtil.java
Java
apache-2.0
17,100
package cn.itedus.lottery; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * @description: LotteryApplication * @author:小傅哥,微信:fustack * @date: 2021/8/28 * @Copyright:公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ @SpringBootApplication @Configurable @EnableDubbo public class LotteryApplication { public static void main(String[] args) { SpringApplication.run(LotteryApplication.class, args); } }
2302_77879529/lottery
lottery-interfaces/src/main/java/cn/itedus/lottery/LotteryApplication.java
Java
apache-2.0
739
package cn.itedus.lottery.interfaces.assembler; import cn.itedus.lottery.domain.activity.model.vo.ActivityVO; import cn.itedus.lottery.domain.strategy.model.vo.DrawAwardVO; import cn.itedus.lottery.rpc.activity.booth.dto.AwardDTO; import cn.itedus.lottery.rpc.activity.deploy.dto.ActivityDTO; import org.mapstruct.Mapper; import org.mapstruct.ReportingPolicy; import java.util.List; /** * @description: 活动对象转换配置 * @author: 小傅哥,微信:fustack * @date: 2021/12/11 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ @Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE, unmappedSourcePolicy = ReportingPolicy.IGNORE) public interface ActivityMapping extends IMapping<ActivityVO, ActivityDTO>{ @Override List<ActivityDTO> sourceToTarget(List<ActivityVO> var1); }
2302_77879529/lottery
lottery-interfaces/src/main/java/cn/itedus/lottery/interfaces/assembler/ActivityMapping.java
Java
apache-2.0
969
package cn.itedus.lottery.interfaces.assembler; import cn.itedus.lottery.domain.strategy.model.vo.DrawAwardVO; import cn.itedus.lottery.rpc.activity.booth.dto.AwardDTO; import org.mapstruct.Mapper; import org.mapstruct.Mapping; import org.mapstruct.ReportingPolicy; /** * @description: 对象转换配置 * @author: 小傅哥,微信:fustack * @date: 2021/10/16 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ @Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE, unmappedSourcePolicy = ReportingPolicy.IGNORE) public interface AwardMapping extends IMapping<DrawAwardVO, AwardDTO> { @Mapping(target = "userId", source = "uId") @Override AwardDTO sourceToTarget(DrawAwardVO var1); @Override DrawAwardVO targetToSource(AwardDTO var1); }
2302_77879529/lottery
lottery-interfaces/src/main/java/cn/itedus/lottery/interfaces/assembler/AwardMapping.java
Java
apache-2.0
937
package cn.itedus.lottery.interfaces.assembler; import org.mapstruct.InheritConfiguration; import org.mapstruct.InheritInverseConfiguration; import org.mapstruct.MapperConfig; import org.mapstruct.Mapping; import java.util.List; import java.util.stream.Stream; /** * @description: MapStruct 对象映射接口 * @author: 小傅哥,微信:fustack * @date: 2021/10/16 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ @MapperConfig public interface IMapping<SOURCE, TARGET> { /** * 映射同名属性 * @param var1 源 * @return 结果 */ @Mapping(target = "createTime", dateFormat = "yyyy-MM-dd HH:mm:ss") TARGET sourceToTarget(SOURCE var1); /** * 映射同名属性,反向 * @param var1 源 * @return 结果 */ @InheritInverseConfiguration(name = "sourceToTarget") SOURCE targetToSource(TARGET var1); /** * 映射同名属性,集合形式 * @param var1 源 * @return 结果 */ @InheritConfiguration(name = "sourceToTarget") List<TARGET> sourceToTarget(List<SOURCE> var1); /** * 反向,映射同名属性,集合形式 * @param var1 源 * @return 结果 */ @InheritConfiguration(name = "targetToSource") List<SOURCE> targetToSource(List<TARGET> var1); /** * 映射同名属性,集合流形式 * @param stream 源 * @return 结果 */ List<TARGET> sourceToTarget(Stream<SOURCE> stream); /** * 反向,映射同名属性,集合流形式 * @param stream 源 * @return 结果 */ List<SOURCE> targetToSource(Stream<TARGET> stream); }
2302_77879529/lottery
lottery-interfaces/src/main/java/cn/itedus/lottery/interfaces/assembler/IMapping.java
Java
apache-2.0
1,809
package cn.itedus.lottery.interfaces.facade; import cn.itedus.lottery.application.process.draw.IActivityDrawProcess; import cn.itedus.lottery.application.process.draw.req.DrawProcessReq; import cn.itedus.lottery.application.process.draw.res.DrawProcessResult; import cn.itedus.lottery.application.process.draw.res.RuleQuantificationCrowdResult; import cn.itedus.lottery.common.Constants; import cn.itedus.lottery.domain.rule.model.req.DecisionMatterReq; import cn.itedus.lottery.domain.strategy.model.vo.DrawAwardVO; import cn.itedus.lottery.interfaces.assembler.IMapping; import cn.itedus.lottery.rpc.activity.booth.ILotteryActivityBooth; import cn.itedus.lottery.rpc.activity.booth.dto.AwardDTO; import cn.itedus.lottery.rpc.activity.booth.req.DrawReq; import cn.itedus.lottery.rpc.activity.booth.req.QuantificationDrawReq; import cn.itedus.lottery.rpc.activity.booth.res.DrawRes; import com.alibaba.fastjson.JSON; import org.apache.dubbo.config.annotation.Service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Resource; /** * @description: 抽奖活动展台 * @author: 小傅哥,微信:fustack * @date: 2021/10/16 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ @Service public class LotteryActivityBooth implements ILotteryActivityBooth { private Logger logger = LoggerFactory.getLogger(LotteryActivityBooth.class); @Resource private IActivityDrawProcess activityProcess; @Resource private IMapping<DrawAwardVO, AwardDTO> awardMapping; @Override public DrawRes doDraw(DrawReq drawReq) { try { logger.info("抽奖,开始 uId:{} activityId:{}", drawReq.getuId(), drawReq.getActivityId()); // 1. 执行抽奖 DrawProcessResult drawProcessResult = activityProcess.doDrawProcess(new DrawProcessReq(drawReq.getuId(), drawReq.getActivityId())); if (!Constants.ResponseCode.SUCCESS.getCode().equals(drawProcessResult.getCode())) { logger.error("抽奖,失败(抽奖过程异常) uId:{} activityId:{}", drawReq.getuId(), drawReq.getActivityId()); return new DrawRes(drawProcessResult.getCode(), drawProcessResult.getInfo()); } // 2. 数据转换 DrawAwardVO drawAwardVO = drawProcessResult.getDrawAwardVO(); AwardDTO awardDTO = awardMapping.sourceToTarget(drawAwardVO); awardDTO.setActivityId(drawReq.getActivityId()); // 3. 封装数据 DrawRes drawRes = new DrawRes(Constants.ResponseCode.SUCCESS.getCode(), Constants.ResponseCode.SUCCESS.getInfo()); drawRes.setAwardDTO(awardDTO); logger.info("抽奖,完成 uId:{} activityId:{} drawRes:{}", drawReq.getuId(), drawReq.getActivityId(), JSON.toJSONString(drawRes)); return drawRes; } catch (Exception e) { logger.error("抽奖,失败 uId:{} activityId:{} reqJson:{}", drawReq.getuId(), drawReq.getActivityId(), JSON.toJSONString(drawReq), e); return new DrawRes(Constants.ResponseCode.UN_ERROR.getCode(), Constants.ResponseCode.UN_ERROR.getInfo()); } } @Override public DrawRes doQuantificationDraw(QuantificationDrawReq quantificationDrawReq) { try { logger.info("量化人群抽奖,开始 uId:{} treeId:{}", quantificationDrawReq.getuId(), quantificationDrawReq.getTreeId()); // 1. 执行规则引擎,获取用户可以参与的活动号 RuleQuantificationCrowdResult ruleQuantificationCrowdResult = activityProcess.doRuleQuantificationCrowd(new DecisionMatterReq(quantificationDrawReq.getuId(), quantificationDrawReq.getTreeId(), quantificationDrawReq.getValMap())); if (!Constants.ResponseCode.SUCCESS.getCode().equals(ruleQuantificationCrowdResult.getCode())) { logger.error("量化人群抽奖,失败(规则引擎执行异常) uId:{} treeId:{}", quantificationDrawReq.getuId(), quantificationDrawReq.getTreeId()); return new DrawRes(ruleQuantificationCrowdResult.getCode(), ruleQuantificationCrowdResult.getInfo()); } // 2. 执行抽奖 Long activityId = ruleQuantificationCrowdResult.getActivityId(); DrawProcessResult drawProcessResult = activityProcess.doDrawProcess(new DrawProcessReq(quantificationDrawReq.getuId(), activityId)); if (!Constants.ResponseCode.SUCCESS.getCode().equals(drawProcessResult.getCode())) { logger.error("量化人群抽奖,失败(抽奖过程异常) uId:{} treeId:{}", quantificationDrawReq.getuId(), quantificationDrawReq.getTreeId()); return new DrawRes(drawProcessResult.getCode(), drawProcessResult.getInfo()); } // 3. 数据转换 DrawAwardVO drawAwardVO = drawProcessResult.getDrawAwardVO(); AwardDTO awardDTO = awardMapping.sourceToTarget(drawAwardVO); awardDTO.setActivityId(activityId); // 4. 封装数据 DrawRes drawRes = new DrawRes(Constants.ResponseCode.SUCCESS.getCode(), Constants.ResponseCode.SUCCESS.getInfo()); drawRes.setAwardDTO(awardDTO); logger.info("量化人群抽奖,完成 uId:{} treeId:{} drawRes:{}", quantificationDrawReq.getuId(), quantificationDrawReq.getTreeId(), JSON.toJSONString(drawRes)); return drawRes; } catch (Exception e) { logger.error("量化人群抽奖,失败 uId:{} treeId:{} reqJson:{}", quantificationDrawReq.getuId(), quantificationDrawReq.getTreeId(), JSON.toJSONString(quantificationDrawReq), e); return new DrawRes(Constants.ResponseCode.UN_ERROR.getCode(), Constants.ResponseCode.UN_ERROR.getInfo()); } } }
2302_77879529/lottery
lottery-interfaces/src/main/java/cn/itedus/lottery/interfaces/facade/LotteryActivityBooth.java
Java
apache-2.0
5,946
package cn.itedus.lottery.interfaces.facade; import cn.itedus.lottery.application.process.deploy.IActivityDeployProcess; import cn.itedus.lottery.common.Result; import cn.itedus.lottery.domain.activity.model.aggregates.ActivityInfoLimitPageRich; import cn.itedus.lottery.domain.activity.model.req.ActivityInfoLimitPageReq; import cn.itedus.lottery.domain.activity.model.vo.ActivityVO; import cn.itedus.lottery.interfaces.assembler.IMapping; import cn.itedus.lottery.rpc.activity.deploy.ILotteryActivityDeploy; import cn.itedus.lottery.rpc.activity.deploy.dto.ActivityDTO; import cn.itedus.lottery.rpc.activity.deploy.req.ActivityPageReq; import cn.itedus.lottery.rpc.activity.deploy.res.ActivityRes; import com.alibaba.fastjson.JSON; import org.apache.dubbo.config.annotation.Service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Resource; import java.util.List; /** * @description: 抽奖活动部署 * @author: 小傅哥,微信:fustack * @date: 2021/12/11 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ @Service public class LotteryActivityDeploy implements ILotteryActivityDeploy { private Logger logger = LoggerFactory.getLogger(LotteryActivityBooth.class); @Resource private IActivityDeployProcess activityDeploy; @Resource private IMapping<ActivityVO, ActivityDTO> activityMapping; @Override public ActivityRes queryActivityListByPageForErp(ActivityPageReq req) { try { logger.info("活动部署分页数据查询开始 erpID:{}", req.getErpId()); // 1. 包装入参 ActivityInfoLimitPageReq activityInfoLimitPageReq = new ActivityInfoLimitPageReq(req.getPage(),req.getRows()); activityInfoLimitPageReq.setActivityId(req.getActivityId()); activityInfoLimitPageReq.setActivityName(req.getActivityName()); // 2. 查询结果 ActivityInfoLimitPageRich activityInfoLimitPageRich = activityDeploy.queryActivityInfoLimitPage(activityInfoLimitPageReq); Long count = activityInfoLimitPageRich.getCount(); List<ActivityVO> activityVOList = activityInfoLimitPageRich.getActivityVOList(); // 3. 转换对象 List<ActivityDTO> activityDTOList = activityMapping.sourceToTarget(activityVOList); // 4. 封装数据 ActivityRes activityRes = new ActivityRes(Result.buildSuccessResult()); activityRes.setCount(count); activityRes.setActivityDTOList(activityDTOList); logger.info("活动部署分页数据查询完成 erpID:{} count:{}", req.getErpId(), count); // 5. 返回结果 return activityRes; } catch (Exception e) { logger.error("活动部署分页数据查询失败 erpID:{} reqStr:{}", req.getErpId(), JSON.toJSON(req), e); return new ActivityRes(Result.buildErrorResult()); } } }
2302_77879529/lottery
lottery-interfaces/src/main/java/cn/itedus/lottery/interfaces/facade/LotteryActivityDeploy.java
Java
apache-2.0
3,087
package cn.itedus.lottery.test.model; public class User { }
2302_77879529/lottery
lottery-interfaces/src/test/java/cn/itedus/lottery/test/model/User.java
Java
apache-2.0
61
package cn.itedus.lottery.test.vo2dto; import cn.itedus.lottery.test.vo2dto.bbb.User; import org.springframework.beans.BeanUtils; import java.util.List; /** * @description: 普通对象转换 * @author: 小傅哥,微信:fustack * @date: 2022/1/16 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ public class ApiTest01 { public void test_vo2dto(User user) { UserDTO userDTO = new UserDTO(); } public void test_vo2dto(List<User> userList) { for (User user : userList) { UserDTO userDTO = new UserDTO(); BeanUtils.copyProperties(user, userDTO); } } public void test_vo2dto() { User user = this.queryUserById(); UserDTO userDTO = new UserDTO(); } private User queryUserById() { return null; } }
2302_77879529/lottery
lottery-interfaces/src/test/java/cn/itedus/lottery/test/vo2dto/ApiTest01.java
Java
apache-2.0
957
package cn.itedus.lottery.test.vo2dto; import cn.itedus.lottery.test.vo2dto.aaa.User; /** * @description: lombok 对象转换, * @author: 小傅哥,微信:fustack * @date: 2022/1/16 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ public class ApiTest02 { public void test_vo2dto(User user) { UserDTO userDTO = new UserDTO(); } }
2302_77879529/lottery
lottery-interfaces/src/test/java/cn/itedus/lottery/test/vo2dto/ApiTest02.java
Java
apache-2.0
504
package cn.itedus.lottery.test.vo2dto; import cn.itedus.lottery.test.vo2dto . bbb. User ; /** * @description: import * 引入转换 * @author: 小傅哥,微信:fustack * @date: 2022/1/16 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ public class ApiTest03 { public void test_vo2dto(User user) { UserDTO userDTO = new UserDTO(); } }
2302_77879529/lottery
lottery-interfaces/src/test/java/cn/itedus/lottery/test/vo2dto/ApiTest03.java
Java
apache-2.0
517
package cn.itedus.lottery.test.vo2dto; import cn.itedus.lottery.test.vo2dto.ccc.User; /** * @description: 继承对象转换 * @author: 小傅哥,微信:fustack * @date: 2022/1/16 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ public class ApiTest04 { public void test_vo2dto(User user) { UserDTO userDTO = new UserDTO(); userDTO.setUserId(user.getUserId()); userDTO.setUserNickName(user.getUserNickName()); userDTO.setUserHead(user.getUserHead()); userDTO.setPage(user.getPage()); userDTO.setRows(user.getRows()); } }
2302_77879529/lottery
lottery-interfaces/src/test/java/cn/itedus/lottery/test/vo2dto/ApiTest04.java
Java
apache-2.0
733
package cn.itedus.lottery.test.vo2dto; /** * @description: 同包下对象转换 * @author: 小傅哥,微信:fustack * @date: 2022/1/16 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ public class ApiTest05 { public void test_vo2dto(User user) { UserDTO userDTO = new UserDTO(); userDTO.setUserId(user.getUserId()); userDTO.setUserNickName(user.getUserNickName()); userDTO.setUserHead(user.getUserHead()); } }
2302_77879529/lottery
lottery-interfaces/src/test/java/cn/itedus/lottery/test/vo2dto/ApiTest05.java
Java
apache-2.0
606
package cn.itedus.lottery.test.vo2dto; /** * @description: 引入包名转换 * @author: 小傅哥,微信:fustack * @date: 2022/1/16 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ public class ApiTest06 { public void test_vo2dto(cn.itedus.lottery.test.vo2dto.bbb.User user) { UserDTO userDTO = new UserDTO(); userDTO.setUserId(user.getUserId()); userDTO.setUserNickName(user.getUserNickName()); userDTO.setUserHead(user.getUserHead()); } }
2302_77879529/lottery
lottery-interfaces/src/test/java/cn/itedus/lottery/test/vo2dto/ApiTest06.java
Java
apache-2.0
638
package cn.itedus.lottery.test.vo2dto; import javax.xml.crypto.Data; public class User { private Long id; private String userId; private String userNickName; private String userHead; private String userPassword; private Data createTime; private Data updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getUserNickName() { return userNickName; } public void setUserNickName(String userNickName) { this.userNickName = userNickName; } public String getUserHead() { return userHead; } public void setUserHead(String userHead) { this.userHead = userHead; } public String getUserPassword() { return userPassword; } public void setUserPassword(String userPassword) { this.userPassword = userPassword; } public Data getCreateTime() { return createTime; } public void setCreateTime(Data createTime) { this.createTime = createTime; } public Data getUpdateTime() { return updateTime; } public void setUpdateTime(Data updateTime) { this.updateTime = updateTime; } }
2302_77879529/lottery
lottery-interfaces/src/test/java/cn/itedus/lottery/test/vo2dto/User.java
Java
apache-2.0
1,385
package cn.itedus.lottery.test.vo2dto; public class UserDTO { private String userId; private String userNickName; private String userHead; private int page; private int rows; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getUserNickName() { return userNickName; } public void setUserNickName(String userNickName) { this.userNickName = userNickName; } public String getUserHead() { return userHead; } public void setUserHead(String userHead) { this.userHead = userHead; } public int getPage() { return page; } public void setPage(int page) { this.page = page; } public int getRows() { return rows; } public void setRows(int rows) { this.rows = rows; } }
2302_77879529/lottery
lottery-interfaces/src/test/java/cn/itedus/lottery/test/vo2dto/UserDTO.java
Java
apache-2.0
921
package cn.itedus.lottery.test.vo2dto.aaa; import javax.xml.crypto.Data; @lombok.Data public class User { private Long id; private String userId; private String userNickName; private String userHead; private String userPassword; private Data createTime; private Data updateTime; }
2302_77879529/lottery
lottery-interfaces/src/test/java/cn/itedus/lottery/test/vo2dto/aaa/User.java
Java
apache-2.0
313
package cn.itedus.lottery.test.vo2dto.bbb; import lombok.Data; @Data public class User { private static final long serialVersionUID = 1L; private String userId; private String userNickName; private String userHead; private String userPassword; private Data createTime; private Data updateTime; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getUserNickName() { return userNickName; } public void setUserNickName(String userNickName) { this.userNickName = userNickName; } public String getUserHead() { return userHead; } public void setUserHead(String userHead) { this.userHead = userHead; } public String getUserPassword() { return userPassword; } public void setUserPassword(String userPassword) { this.userPassword = userPassword; } public Data getCreateTime() { return createTime; } public void setCreateTime(Data createTime) { this.createTime = createTime; } public Data getUpdateTime() { return updateTime; } public void setUpdateTime(Data updateTime) { this.updateTime = updateTime; } }
2302_77879529/lottery
lottery-interfaces/src/test/java/cn/itedus/lottery/test/vo2dto/bbb/User.java
Java
apache-2.0
1,305
package cn.itedus.lottery.test.vo2dto.ccc; public class Page { /** * 开始 limit 第1个入参 */ private int pageBegin = 0; /** * 开始 limit 第2个入参 */ private int pageEnd = 0; /** * 页数 */ private int page; /** * 行数 */ private int rows; public Page() { } public Page(String page, String rows) { this.setPage(page, rows); } public Page(int page, int rows) { this.setPage(page, rows); } public void setPage(String page, String rows) { this.page = null == page ? 1 : Integer.parseInt(page); this.rows = null == page ? 10 : Integer.parseInt(rows); if (0 == this.page) { this.page = 1; } this.pageBegin = (this.page - 1) * this.rows; this.pageEnd = this.rows; } public void setPage(int page, int rows) { this.page = page; this.rows = rows; if (0 == this.page) { this.page = 1; } this.pageBegin = (this.page - 1) * this.rows; this.pageEnd = this.rows; } public int getPage() { return page; } public void setPage(int page) { this.page = page; } public int getRows() { return rows; } public void setRows(int rows) { this.rows = rows; } public int getPageBegin() { return pageBegin; } public void setPageBegin(int pageBegin) { this.pageBegin = pageBegin; } public int getPageEnd() { return pageEnd; } public void setPageEnd(int pageEnd) { this.pageEnd = pageEnd; } }
2302_77879529/lottery
lottery-interfaces/src/test/java/cn/itedus/lottery/test/vo2dto/ccc/Page.java
Java
apache-2.0
1,672
package cn.itedus.lottery.test.vo2dto.ccc; import javax.xml.crypto.Data; public class User extends Page { private Long id; private String userId; private String userNickName; private String userHead; private String userPassword; private Data createTime; private Data updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getUserNickName() { return userNickName; } public void setUserNickName(String userNickName) { this.userNickName = userNickName; } public String getUserHead() { return userHead; } public void setUserHead(String userHead) { this.userHead = userHead; } public String getUserPassword() { return userPassword; } public void setUserPassword(String userPassword) { this.userPassword = userPassword; } public Data getCreateTime() { return createTime; } public void setCreateTime(Data createTime) { this.createTime = createTime; } public Data getUpdateTime() { return updateTime; } public void setUpdateTime(Data updateTime) { this.updateTime = updateTime; } }
2302_77879529/lottery
lottery-interfaces/src/test/java/cn/itedus/lottery/test/vo2dto/ccc/User.java
Java
apache-2.0
1,402
package cn.itedus.lottery.rpc.activity.booth; import cn.itedus.lottery.rpc.activity.booth.req.DrawReq; import cn.itedus.lottery.rpc.activity.booth.req.QuantificationDrawReq; import cn.itedus.lottery.rpc.activity.booth.res.DrawRes; /** * @description: 抽奖活动展台接口 * @author: 小傅哥,微信:fustack * @date: 2021/10/16 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ public interface ILotteryActivityBooth { /** * 指定活动抽奖 * @param drawReq 请求参数 * @return 抽奖结果 */ DrawRes doDraw(DrawReq drawReq); /** * 量化人群抽奖 * @param quantificationDrawReq 请求参数 * @return 抽奖结果 */ DrawRes doQuantificationDraw(QuantificationDrawReq quantificationDrawReq); }
2302_77879529/lottery
lottery-rpc/src/main/java/cn/itedus/lottery/rpc/activity/booth/ILotteryActivityBooth.java
Java
apache-2.0
946
package cn.itedus.lottery.rpc.activity.booth.dto; import java.io.Serializable; import java.util.Date; /** * @description: 奖品信息 * @author: 小傅哥,微信:fustack * @date: 2021/10/16 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ public class AwardDTO implements Serializable { /** * 用户ID */ private String userId; /** * 活动ID */ private Long activityId; /** * 奖品ID */ private String awardId; /** * 奖品类型(1:文字描述、2:兑换码、3:优惠券、4:实物奖品) */ private Integer awardType; /** * 奖品名称 */ private String awardName; /** * 奖品内容「描述、奖品码、sku」 */ private String awardContent; /** * 策略方式(1:单项概率、2:总体概率) */ private Integer strategyMode; /** * 发放奖品方式(1:即时、2:定时[含活动结束]、3:人工) */ private Integer grantType; /** * 发奖时间 */ private Date grantDate; public AwardDTO() { } public AwardDTO(String userId) { this.userId = userId; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public Long getActivityId() { return activityId; } public void setActivityId(Long activityId) { this.activityId = activityId; } public String getAwardId() { return awardId; } public void setAwardId(String awardId) { this.awardId = awardId; } public Integer getAwardType() { return awardType; } public void setAwardType(Integer awardType) { this.awardType = awardType; } public String getAwardName() { return awardName; } public void setAwardName(String awardName) { this.awardName = awardName; } public String getAwardContent() { return awardContent; } public void setAwardContent(String awardContent) { this.awardContent = awardContent; } public Integer getStrategyMode() { return strategyMode; } public void setStrategyMode(Integer strategyMode) { this.strategyMode = strategyMode; } public Integer getGrantType() { return grantType; } public void setGrantType(Integer grantType) { this.grantType = grantType; } public Date getGrantDate() { return grantDate; } public void setGrantDate(Date grantDate) { this.grantDate = grantDate; } @Override public String toString() { return "AwardDTO{" + "userId='" + userId + '\'' + ", activityId=" + activityId + ", awardId='" + awardId + '\'' + ", awardType=" + awardType + ", awardName='" + awardName + '\'' + ", awardContent='" + awardContent + '\'' + ", strategyMode=" + strategyMode + ", grantType=" + grantType + ", grantDate=" + grantDate + '}'; } }
2302_77879529/lottery
lottery-rpc/src/main/java/cn/itedus/lottery/rpc/activity/booth/dto/AwardDTO.java
Java
apache-2.0
3,320
package cn.itedus.lottery.rpc.activity.booth.req; import java.io.Serializable; /** * @description: 抽奖请求 * @author: 小傅哥,微信:fustack * @date: 2021/10/16 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ public class DrawReq implements Serializable { /** 用户ID */ private String uId; /** 活动ID */ private Long activityId; public DrawReq() { } public DrawReq(String uId, Long activityId) { this.uId = uId; this.activityId = activityId; } public String getuId() { return uId; } public void setuId(String uId) { this.uId = uId; } public Long getActivityId() { return activityId; } public void setActivityId(Long activityId) { this.activityId = activityId; } }
2302_77879529/lottery
lottery-rpc/src/main/java/cn/itedus/lottery/rpc/activity/booth/req/DrawReq.java
Java
apache-2.0
946
package cn.itedus.lottery.rpc.activity.booth.req; import java.util.Map; /** * @description: 量化人群抽奖请求参数 * @author: 小傅哥,微信:fustack * @date: 2021/10/16 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ public class QuantificationDrawReq { /** 用户ID */ private String uId; /** 规则树ID */ private Long treeId; /** 决策值 */ private Map<String, Object> valMap; public Long getTreeId() { return treeId; } public void setTreeId(Long treeId) { this.treeId = treeId; } public String getuId() { return uId; } public void setuId(String uId) { this.uId = uId; } public Map<String, Object> getValMap() { return valMap; } public void setValMap(Map<String, Object> valMap) { this.valMap = valMap; } }
2302_77879529/lottery
lottery-rpc/src/main/java/cn/itedus/lottery/rpc/activity/booth/req/QuantificationDrawReq.java
Java
apache-2.0
1,003
package cn.itedus.lottery.rpc.activity.booth.res; import cn.itedus.lottery.common.Result; import cn.itedus.lottery.rpc.activity.booth.dto.AwardDTO; import java.io.Serializable; /** * @description: 抽奖结果 * @author: 小傅哥,微信:fustack * @date: 2021/10/16 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ public class DrawRes extends Result implements Serializable { private AwardDTO awardDTO; public DrawRes(String code, String info) { super(code, info); } public AwardDTO getAwardDTO() { return awardDTO; } public void setAwardDTO(AwardDTO awardDTO) { this.awardDTO = awardDTO; } }
2302_77879529/lottery
lottery-rpc/src/main/java/cn/itedus/lottery/rpc/activity/booth/res/DrawRes.java
Java
apache-2.0
803
package cn.itedus.lottery.rpc.activity.deploy; import cn.itedus.lottery.rpc.activity.deploy.req.ActivityPageReq; import cn.itedus.lottery.rpc.activity.deploy.res.ActivityRes; /** * @description: 抽奖活动部署服务接口 * @author: 小傅哥,微信:fustack * @date: 2021/12/11 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ public interface ILotteryActivityDeploy { /** * 通过分页查询活动列表信息,给ERP运营使用 * * @param req 查询参数 * @return 查询结果 */ ActivityRes queryActivityListByPageForErp(ActivityPageReq req); }
2302_77879529/lottery
lottery-rpc/src/main/java/cn/itedus/lottery/rpc/activity/deploy/ILotteryActivityDeploy.java
Java
apache-2.0
750
package cn.itedus.lottery.rpc.activity.deploy.dto; import java.io.Serializable; import java.util.Date; /** * @description: 活动信息 * @author: 小傅哥,微信:fustack * @date: 2021/12/11 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ public class ActivityDTO implements Serializable { /** * 自增ID */ private Long id; /** * 活动ID */ private Long activityId; /** * 活动名称 */ private String activityName; /** * 活动描述 */ private String activityDesc; /** * 开始时间 */ private Date beginDateTime; /** * 结束时间 */ private Date endDateTime; /** * 库存 */ private Integer stockCount; /** * 库存剩余 */ private Integer stockSurplusCount; /** * 每人可参与次数 */ private Integer takeCount; /** * 策略ID */ private Long strategyId; /** * 活动状态:1编辑、2提审、3撤审、4通过、5运行(审核通过后worker扫描状态)、6拒绝、7关闭、8开启 */ private Integer state; /** * 创建人 */ private String creator; /** * 创建时间 */ private Date createTime; /** * 修改时间 */ private Date updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getActivityId() { return activityId; } public void setActivityId(Long activityId) { this.activityId = activityId; } public String getActivityName() { return activityName; } public void setActivityName(String activityName) { this.activityName = activityName; } public String getActivityDesc() { return activityDesc; } public void setActivityDesc(String activityDesc) { this.activityDesc = activityDesc; } public Date getBeginDateTime() { return beginDateTime; } public void setBeginDateTime(Date beginDateTime) { this.beginDateTime = beginDateTime; } public Date getEndDateTime() { return endDateTime; } public void setEndDateTime(Date endDateTime) { this.endDateTime = endDateTime; } public Integer getStockCount() { return stockCount; } public void setStockCount(Integer stockCount) { this.stockCount = stockCount; } public Integer getStockSurplusCount() { return stockSurplusCount; } public void setStockSurplusCount(Integer stockSurplusCount) { this.stockSurplusCount = stockSurplusCount; } public Integer getTakeCount() { return takeCount; } public void setTakeCount(Integer takeCount) { this.takeCount = takeCount; } public Long getStrategyId() { return strategyId; } public void setStrategyId(Long strategyId) { this.strategyId = strategyId; } public Integer getState() { return state; } public void setState(Integer state) { this.state = state; } public String getCreator() { return creator; } public void setCreator(String creator) { this.creator = creator; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } @Override public String toString() { return "ActivityDTO{" + "id=" + id + ", activityId=" + activityId + ", activityName='" + activityName + '\'' + ", activityDesc='" + activityDesc + '\'' + ", beginDateTime=" + beginDateTime + ", endDateTime=" + endDateTime + ", stockCount=" + stockCount + ", stockSurplusCount=" + stockSurplusCount + ", takeCount=" + takeCount + ", strategyId=" + strategyId + ", state=" + state + ", creator='" + creator + '\'' + ", createTime=" + createTime + ", updateTime=" + updateTime + '}'; } }
2302_77879529/lottery
lottery-rpc/src/main/java/cn/itedus/lottery/rpc/activity/deploy/dto/ActivityDTO.java
Java
apache-2.0
4,561
package cn.itedus.lottery.rpc.activity.deploy.req; import cn.itedus.lottery.common.PageRequest; import java.io.Serializable; /** * @description: 分页查询活动 * @author: 小傅哥,微信:fustack * @date: 2021/12/11 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ public class ActivityPageReq extends PageRequest implements Serializable { /** * ERP ID,记录谁在操作 */ private String erpId; /** * 活动ID */ private Long activityId; /** * 活动名称 */ private String activityName; public ActivityPageReq(int page, int rows) { super(page, rows); } public ActivityPageReq(String page, String rows) { super(page, rows); } public String getErpId() { return erpId; } public void setErpId(String erpId) { this.erpId = erpId; } public Long getActivityId() { return activityId; } public void setActivityId(Long activityId) { this.activityId = activityId; } public String getActivityName() { return activityName; } public void setActivityName(String activityName) { this.activityName = activityName; } }
2302_77879529/lottery
lottery-rpc/src/main/java/cn/itedus/lottery/rpc/activity/deploy/req/ActivityPageReq.java
Java
apache-2.0
1,357
package cn.itedus.lottery.rpc.activity.deploy.res; import cn.itedus.lottery.common.Result; import cn.itedus.lottery.rpc.activity.deploy.dto.ActivityDTO; import java.io.Serializable; import java.util.List; /** * @description: 活动查询结果 * @author: 小傅哥,微信:fustack * @date: 2021/12/11 * @github: https://github.com/fuzhengwei * @Copyright: 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ public class ActivityRes implements Serializable { private Result result; private Long count; private List<ActivityDTO> activityDTOList; public ActivityRes() { } public ActivityRes(Result result) { this.result = result; } public ActivityRes(Result result, Long count, List<ActivityDTO> activityDTOList) { this.result = result; this.count = count; this.activityDTOList = activityDTOList; } public Result getResult() { return result; } public void setResult(Result result) { this.result = result; } public Long getCount() { return count; } public void setCount(Long count) { this.count = count; } public List<ActivityDTO> getActivityDTOList() { return activityDTOList; } public void setActivityDTOList(List<ActivityDTO> activityDTOList) { this.activityDTOList = activityDTOList; } }
2302_77879529/lottery
lottery-rpc/src/main/java/cn/itedus/lottery/rpc/activity/deploy/res/ActivityRes.java
Java
apache-2.0
1,457
import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'dart:convert'; void main() { runApp(const TodoApp()); } class TodoApp extends StatelessWidget { const TodoApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: '待办清单', theme: ThemeData( primarySwatch: Colors.indigo, brightness: Brightness.light, visualDensity: VisualDensity.adaptivePlatformDensity, cardTheme: CardTheme( elevation: 4, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), ), floatingActionButtonTheme: FloatingActionButtonThemeData( backgroundColor: Colors.indigo, ), ), home: const TodoHomePage(), ); } } // 待办事项类 class TodoItem { String title; bool isCompleted; final DateTime createdAt; TodoItem({ required this.title, this.isCompleted = false, DateTime? createdAt, }) : createdAt = createdAt ?? DateTime.now(); // 转换为JSON Map<String, dynamic> toJson() => { 'title': title, 'isCompleted': isCompleted, 'createdAt': createdAt.toIso8601String(), }; // 从JSON创建 factory TodoItem.fromJson(Map<String, dynamic> json) => TodoItem( title: json['title'], isCompleted: json['isCompleted'], createdAt: DateTime.parse(json['createdAt']), ); } class TodoHomePage extends StatefulWidget { const TodoHomePage({super.key}); @override _TodoHomePageState createState() => _TodoHomePageState(); } // 动画配置 const Duration _animationDuration = Duration(milliseconds: 300); class _TodoHomePageState extends State<TodoHomePage> { final List<TodoItem> _todos = []; final TextEditingController _textEditingController = TextEditingController(); bool _isLoading = true; bool _isAddingTodo = false; @override void initState() { super.initState(); _loadTodos(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text( '待办清单', style: TextStyle(fontWeight: FontWeight.bold), ), backgroundColor: Theme.of(context).colorScheme.inversePrimary, elevation: 4, shape: RoundedRectangleBorder( borderRadius: BorderRadius.vertical(bottom: Radius.circular(16)), ), ), body: Column( children: [ Padding( padding: const EdgeInsets.all(16.0), child: Card( child: Padding( padding: const EdgeInsets.all(8.0), child: Row( children: [ Expanded( child: TextField( controller: _textEditingController, decoration: InputDecoration( labelText: '添加新的待办事项', border: OutlineInputBorder( borderRadius: BorderRadius.circular(8), ), prefixIcon: Icon(Icons.add_task_outlined), ), onSubmitted: _addTodo, textInputAction: TextInputAction.done, ), ), SizedBox(width: 8), ElevatedButton( onPressed: () => _addTodo(_textEditingController.text), style: ElevatedButton.styleFrom( padding: EdgeInsets.symmetric(horizontal: 16, vertical: 16), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(8), ), ), child: Icon(Icons.add), ), ], ), ), ), ), Expanded( child: _isLoading ? const Center(child: CircularProgressIndicator()) : _todos.isEmpty ? Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon(Icons.check_circle_outline, size: 64, color: Colors.grey), SizedBox(height: 16), Text( '没有待办事项', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), ), SizedBox(height: 8), Text( '添加一些新的任务开始使用吧!', style: TextStyle(color: Colors.grey), ), ], ), ) : AnimatedList( initialItemCount: _todos.length, itemBuilder: (context, index, animation) { final todo = _todos[index]; return SizeTransition( sizeFactor: animation, child: FadeTransition( opacity: animation, child: Card( margin: EdgeInsets.symmetric(horizontal: 16, vertical: 4), child: ListTile( title: Text( todo.title, style: todo.isCompleted ? TextStyle( decoration: TextDecoration.lineThrough, color: Colors.grey, ) : TextStyle(fontWeight: FontWeight.w500), ), subtitle: Text( '创建于: ${todo.createdAt.toLocal().toString().substring(0, 16)}', style: TextStyle(fontSize: 12, color: Colors.grey), ), leading: Checkbox( value: todo.isCompleted, onChanged: (bool? value) { setState(() { todo.isCompleted = value ?? false; }); _saveTodos(); }, activeColor: Colors.indigo, ), trailing: IconButton( icon: Icon(Icons.delete_outline, color: Colors.red), onPressed: () { // 移除动画 final removedTodo = _todos[index]; setState(() { _todos.removeAt(index); }); _saveTodos(); }, tooltip: '删除', ), onTap: () { setState(() { todo.isCompleted = !todo.isCompleted; }); _saveTodos(); }, ), ), ), ); }, ), ), ], ), ); } Future<void> _loadTodos() async { try { final prefs = await SharedPreferences.getInstance(); final todosJson = prefs.getString('todos'); if (todosJson != null) { final List<dynamic> todosList = jsonDecode(todosJson); setState(() { _todos.clear(); _todos.addAll(todosList.map((item) => TodoItem.fromJson(item))); }); } } catch (e) { print('加载待办事项失败: $e'); } finally { setState(() { _isLoading = false; }); } } Future<void> _saveTodos() async { try { final prefs = await SharedPreferences.getInstance(); final todosJson = jsonEncode(_todos.map((todo) => todo.toJson()).toList()); await prefs.setString('todos', todosJson); } catch (e) { print('保存待办事项失败: $e'); } } void _addTodo(String title) { if (title.trim().isNotEmpty) { final newTodo = TodoItem(title: title.trim()); setState(() { _todos.add(newTodo); _textEditingController.clear(); _isAddingTodo = true; }); _saveTodos(); // 显示添加成功的提示 ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text('待办事项已添加'), duration: Duration(seconds: 2), action: SnackBarAction( label: '撤销', onPressed: () { setState(() { _todos.remove(newTodo); }); _saveTodos(); }, ), ), ); } } @override void dispose() { _textEditingController.dispose(); super.dispose(); } }
2302_80329073/Flutter_Small_Project
lib/main.dart
Dart
unknown
9,838
class Todo { String title; bool isDone; Todo({ required this.title, this.isDone = false, }); }
2302_80329073/Flutter_Small_Project
lib/models/todo.dart
Dart
unknown
112
import 'package:flutter/material.dart'; import '../models/todo.dart'; import '../widgets/todo_list.dart'; class HomeScreen extends StatefulWidget { @override _HomeScreenState createState() => _HomeScreenState(); } class _HomeScreenState extends State<HomeScreen> { final List<Todo> _todos = [ Todo(title: '示例任务 1'), Todo(title: '示例任务 2'), ]; void _addTodo(String title) { setState(() { _todos.add(Todo(title: title)); }); } void _toggleTodoStatus(int index) { setState(() { _todos[index].isDone = !_todos[index].isDone; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('代办事项'), ), body: TodoList(todos: _todos, toggleStatus: _toggleTodoStatus), floatingActionButton: FloatingActionButton( onPressed: () { _addTodoDialog(); }, child: Icon(Icons.add), ), ); } void _addTodoDialog() { TextEditingController _textController = TextEditingController(); showDialog( context: context, builder: (context) { return AlertDialog( title: Text('添加代办事项'), content: TextField( controller: _textController, decoration: InputDecoration(hintText: '输入任务内容'), ), actions: <Widget>[ TextButton( child: Text('取消'), onPressed: () { Navigator.of(context).pop(); }, ), TextButton( child: Text('添加'), onPressed: () { Navigator.of(context).pop(); _addTodo(_textController.text); }, ), ], ); }, ); } }
2302_80329073/Flutter_Small_Project
lib/screens/home_screen.dart
Dart
unknown
1,825
import 'package:flutter/material.dart'; import '../models/todo.dart'; class TodoItem extends StatelessWidget { final Todo todo; final Function toggleStatus; TodoItem({required this.todo, required this.toggleStatus}); @override Widget build(BuildContext context) { return ListTile( title: Text(todo.title, style: TextStyle( decoration: todo.isDone ? TextDecoration.lineThrough : TextDecoration.none, )), trailing: Checkbox( value: todo.isDone, onChanged: (value) { toggleStatus(); }, ), ); } }
2302_80329073/Flutter_Small_Project
lib/widgets/todo_item.dart
Dart
unknown
615
import 'package:flutter/material.dart'; import '../models/todo.dart'; import 'todo_item.dart'; class TodoList extends StatelessWidget { final List<Todo> todos; final Function(int) toggleStatus; TodoList({required this.todos, required this.toggleStatus}); @override Widget build(BuildContext context) { return ListView.builder( itemCount: todos.length, itemBuilder: (context, index) { return TodoItem( todo: todos[index], toggleStatus: () => toggleStatus(index), ); }, ); } }
2302_80329073/Flutter_Small_Project
lib/widgets/todo_list.dart
Dart
unknown
551
// Script for compiling build behavior. It is built in the build plug-in and cannot be modified currently. import { hapTasks } from '@ohos/hvigor-ohos-plugin'; export default { system: hapTasks, /* Built-in plugin of Hvigor. It cannot be modified. */ plugins: [] /* Custom plugin to extend the functionality of Hvigor. */ }
2302_80329073/Flutter_Small_Project
ohos/entry/hvigorfile.ts
TypeScript
unknown
341
import hilog from '@ohos.hilog'; import TestRunner from '@ohos.application.testRunner'; import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; var abilityDelegator = undefined var abilityDelegatorArguments = undefined async function onAbilityCreateCallback() { hilog.info(0x0000, 'testTag', '%{public}s', 'onAbilityCreateCallback'); } async function addAbilityMonitorCallback(err: any) { hilog.info(0x0000, 'testTag', 'addAbilityMonitorCallback : %{public}s', JSON.stringify(err) ?? ''); } export default class OpenHarmonyTestRunner implements TestRunner { constructor() { } onPrepare() { hilog.info(0x0000, 'testTag', '%{public}s', 'OpenHarmonyTestRunner OnPrepare '); } async onRun() { hilog.info(0x0000, 'testTag', '%{public}s', 'OpenHarmonyTestRunner onRun run'); abilityDelegatorArguments = AbilityDelegatorRegistry.getArguments() abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator() var testAbilityName = abilityDelegatorArguments.bundleName + '.TestAbility' let lMonitor = { abilityName: testAbilityName, onAbilityCreate: onAbilityCreateCallback, }; abilityDelegator.addAbilityMonitor(lMonitor, addAbilityMonitorCallback) var cmd = 'aa start -d 0 -a TestAbility' + ' -b ' + abilityDelegatorArguments.bundleName var debug = abilityDelegatorArguments.parameters['-D'] if (debug == 'true') { cmd += ' -D' } hilog.info(0x0000, 'testTag', 'cmd : %{public}s', cmd); abilityDelegator.executeShellCommand(cmd, (err: any, d: any) => { hilog.info(0x0000, 'testTag', 'executeShellCommand : err : %{public}s', JSON.stringify(err) ?? ''); hilog.info(0x0000, 'testTag', 'executeShellCommand : data : %{public}s', d.stdResult ?? ''); hilog.info(0x0000, 'testTag', 'executeShellCommand : data : %{public}s', d.exitCode ?? ''); }) hilog.info(0x0000, 'testTag', '%{public}s', 'OpenHarmonyTestRunner onRun end'); } }
2302_80329073/Flutter_Small_Project
ohos/entry/src/ohosTest/ets/testrunner/OpenHarmonyTestRunner.ts
TypeScript
unknown
2,120
import path from 'path' import { injectNativeModules } from 'flutter-hvigor-plugin'; injectNativeModules(__dirname, path.dirname(__dirname))
2302_80329073/Flutter_Small_Project
ohos/hvigorconfig.ts
TypeScript
unknown
141
import path from 'path' import { appTasks } from '@ohos/hvigor-ohos-plugin'; import { flutterHvigorPlugin } from 'flutter-hvigor-plugin'; export default { system: appTasks, /* Built-in plugin of Hvigor. It cannot be modified. */ plugins:[flutterHvigorPlugin(path.dirname(__dirname))] /* Custom plugin to extend the functionality of Hvigor. */ }
2302_80329073/Flutter_Small_Project
ohos/hvigorfile.ts
TypeScript
unknown
362
#!bin/bash if [ -d "/home/frappe/frappe-bench/apps/frappe" ]; then echo "Bench already exists, skipping init" cd frappe-bench bench start else echo "Creating new bench..." fi bench init --skip-redis-config-generation frappe-bench --version version-15 cd frappe-bench # Use containers instead of localhost bench set-mariadb-host mariadb bench set-redis-cache-host redis:6379 bench set-redis-queue-host redis:6379 bench set-redis-socketio-host redis:6379 # Remove redis, watch from Procfile sed -i '/redis/d' ./Procfile sed -i '/watch/d' ./Procfile bench get-app insights --branch main bench new-site insights.localhost \ --force \ --mariadb-root-password 123 \ --admin-password admin \ --no-mariadb-socket bench --site insights.localhost install-app insights bench --site insights.localhost set-config developer_mode 1 bench --site insights.localhost clear-cache bench --site insights.localhost set-config mute_emails 1 bench use insights.localhost bench start
2302_79757062/insights
docker/init.sh
Shell
agpl-3.0
984
<!DOCTYPE html> <html lang="en" class="h-full bg-gray-100"> <head> <meta charset="UTF-8" /> <link rel="icon" href="/favicon.png" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Frappe Insights</title> </head> <body class="h-full"> <div id="app" class="h-full"></div> <div id="modals"></div> <div id="popovers"></div> <script> window.csrf_token = '{{ csrf_token }}' window.site_name = '{{ site_name }}' </script> <!-- <script type="module" src="/src/main.js"></script> --> <script type="module" src="/src2/main.ts"></script> </body> </html>
2302_79757062/insights
frontend/index.html
HTML
agpl-3.0
608
<!DOCTYPE html> <html lang="en" class="h-full bg-gray-100"> <head> <meta charset="UTF-8" /> <link rel="icon" href="/favicon.png" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Frappe Insights</title> </head> <body class="h-full"> <div id="app" class="h-full"></div> <div id="modals"></div> <div id="popovers"></div> <script> window.csrf_token = '{{ csrf_token }}' window.site_name = '{{ site_name }}' </script> <script type="module" src="/src/main.js"></script> </body> </html>
2302_79757062/insights
frontend/index_v2.html
HTML
agpl-3.0
545
// @ts-check import { defineConfig, devices } from '@playwright/test' /** * Read environment variables from file. * https://github.com/motdotla/dotenv */ // require('dotenv').config(); /** * @see https://playwright.dev/docs/test-configuration */ export default defineConfig({ testDir: './tests', /* Run tests in files in parallel */ fullyParallel: true, /* Fail the build on CI if you accidentally left test.only in the source code. */ forbidOnly: !!process.env.CI, /* Retry on CI only */ retries: process.env.CI ? 2 : 0, /* Opt out of parallel tests on CI. */ workers: process.env.CI ? 1 : undefined, /* Reporter to use. See https://playwright.dev/docs/test-reporters */ reporter: 'html', /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */ use: { /* Base URL to use in actions like `await page.goto('/')`. */ // baseURL: 'http://127.0.0.1:3000', /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */ trace: 'on-first-retry', }, /* Configure projects for major browsers */ projects: [ { name: 'chromium', use: { ...devices['Desktop Chrome'] }, }, { name: 'firefox', use: { ...devices['Desktop Firefox'] }, }, { name: 'webkit', use: { ...devices['Desktop Safari'] }, }, /* Test against mobile viewports. */ // { // name: 'Mobile Chrome', // use: { ...devices['Pixel 5'] }, // }, // { // name: 'Mobile Safari', // use: { ...devices['iPhone 12'] }, // }, /* Test against branded browsers. */ // { // name: 'Microsoft Edge', // use: { ...devices['Desktop Edge'], channel: 'msedge' }, // }, // { // name: 'Google Chrome', // use: { ..devices['Desktop Chrome'], channel: 'chrome' }, // }, ], /* Run your local dev server before starting the tests */ // webServer: { // command: 'npm run start', // url: 'http://127.0.0.1:3000', // reuseExistingServer: !process.env.CI, // }, })
2302_79757062/insights
frontend/playwright.config.js
JavaScript
agpl-3.0
2,001
module.exports = { plugins: { tailwindcss: { config: './tailwind.config.js' }, autoprefixer: {}, }, }
2302_79757062/insights
frontend/postcss.config.js
JavaScript
agpl-3.0
108
<template> <div class="flex h-screen w-screen bg-white antialiased"> <RouterView v-if="isGuestView" /> <Suspense v-else> <AppShell /> </Suspense> <Toaster :visible-toasts="2" position="bottom-right" /> </div> </template> <script setup> import AppShell from '@/components/AppShell.vue' import sessionStore from '@/stores/sessionStore' import { computed, inject, onBeforeUnmount } from 'vue' import { useRoute } from 'vue-router' import { Toaster } from 'vue-sonner' const route = useRoute() const isGuestView = computed(() => route.meta.isGuestView) if (!isGuestView.value) { const $socket = inject('$socket') const $notify = inject('$notify') const session = sessionStore() $socket.on('insights_notification', (data) => { if (data.user == session.user.email) { $notify({ title: data.title || data.message, message: data.title ? data.message : '', variant: data.type, }) } }) onBeforeUnmount(() => { $socket.off('insights_notification') }) } </script>
2302_79757062/insights
frontend/src/App.vue
Vue
agpl-3.0
998
import { call, createDocumentResource, createListResource, createResource } from 'frappe-ui' import getWhitelistedMethods from './whitelistedMethods' export const login = (email: string, password: string): Promise<SessionUser> => { return call('login', { usr: email, pwd: password }) } export const logout = (): Promise<any> => call('logout') export const fetchUserInfo = (): Promise<any> => call('insights.api.get_user_info') export const trackActiveSite = (): Promise<any> => call('insights.api.telemetry.track_active_site') export const updateDefaultVersion = (version: 'v3' | 'v2' | ''): Promise<any> => { return call('insights.api.update_default_version', { version }) } export const createLastViewedLog = (recordType: string, recordName: string) => { return call('insights.api.home.create_last_viewed_log', { record_type: recordType, record_name: recordName, }) as Promise<any> } export const getListResource = (listResourceOption: ListResourceParams): ListResource => { return createListResource(listResourceOption) } export const createDataSource: Resource = createResource({ url: 'insights.api.setup.add_database' }) export const testDataSourceConnection: Resource = createResource({ url: 'insights.api.setup.test_database_connection', }) export const createQuery: Resource = createResource({ url: 'insights.api.queries.create_query' }) export const getDocumentResource = (doctype: string, docname?: string, options?: object) => { const resource = createDocumentResource({ doctype: doctype, name: docname || doctype, whitelistedMethods: getWhitelistedMethods(doctype), ...options, }) resource.fetchIfNeeded = async () => { if (!resource.get.loading) { await resource.get.fetch() } } return resource } export const fetchTableName = async (data_source: string, table: string) => { return call('insights.api.data_sources.get_table_name', { data_source: data_source, table: table, }) }
2302_79757062/insights
frontend/src/api/index.ts
TypeScript
agpl-3.0
1,935
const whitelistedMethods = { 'Insights Settings': { update_settings: 'update_settings', }, 'Insights Data Source': { enqueue_sync_tables: 'enqueue_sync_tables', get_tables: 'get_tables', get_queries: 'get_queries', update_table_link: 'update_table_link', delete_table_link: 'delete_table_link', }, 'Insights Table': { syncTable: 'sync_table', updateVisibility: 'update_visibility', getPreview: 'get_preview', update_column_type: 'update_column_type', }, } export default function getWhitelistedMethods(doctype: string) { return whitelistedMethods[doctype as keyof typeof whitelistedMethods] || {} }
2302_79757062/insights
frontend/src/api/whitelistedMethods.ts
TypeScript
agpl-3.0
626
@font-face { font-family: 'Fira Code'; src: url('FiraCode-Light.woff2') format('woff2'), url("FiraCode-Light.woff") format("woff"); font-weight: 300; font-style: normal; } @font-face { font-family: 'Fira Code'; src: url('FiraCode-Regular.woff2') format('woff2'), url("FiraCode-Regular.woff") format("woff"); font-weight: 400; font-style: normal; } @font-face { font-family: 'Fira Code'; src: url('FiraCode-Medium.woff2') format('woff2'), url("FiraCode-Medium.woff") format("woff"); font-weight: 500; font-style: normal; } @font-face { font-family: 'Fira Code'; src: url('FiraCode-SemiBold.woff2') format('woff2'), url("FiraCode-SemiBold.woff") format("woff"); font-weight: 600; font-style: normal; } @font-face { font-family: 'Fira Code'; src: url('FiraCode-Bold.woff2') format('woff2'), url("FiraCode-Bold.woff") format("woff"); font-weight: 700; font-style: normal; } @font-face { font-family: 'Fira Code VF'; src: url('FiraCode-VF.woff2') format('woff2-variations'), url('FiraCode-VF.woff') format('woff-variations'); /* font-weight requires a range: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Fonts/Variable_Fonts_Guide#Using_a_variable_font_font-face_changes */ font-weight: 300 700; font-style: normal; }
2302_79757062/insights
frontend/src/assets/FiraCode/fira_code.css
CSS
agpl-3.0
1,302
@font-face { font-family: 'Inter'; font-style: normal; font-weight: 100; font-display: swap; src: url("Inter-Thin.woff2?v=3.12") format("woff2"), url("Inter-Thin.woff?v=3.12") format("woff"); } @font-face { font-family: 'Inter'; font-style: italic; font-weight: 100; font-display: swap; src: url("Inter-ThinItalic.woff2?v=3.12") format("woff2"), url("Inter-ThinItalic.woff?v=3.12") format("woff"); } @font-face { font-family: 'Inter'; font-style: normal; font-weight: 200; font-display: swap; src: url("Inter-ExtraLight.woff2?v=3.12") format("woff2"), url("Inter-ExtraLight.woff?v=3.12") format("woff"); } @font-face { font-family: 'Inter'; font-style: italic; font-weight: 200; font-display: swap; src: url("Inter-ExtraLightItalic.woff2?v=3.12") format("woff2"), url("Inter-ExtraLightItalic.woff?v=3.12") format("woff"); } @font-face { font-family: 'Inter'; font-style: normal; font-weight: 300; font-display: swap; src: url("Inter-Light.woff2?v=3.12") format("woff2"), url("Inter-Light.woff?v=3.12") format("woff"); } @font-face { font-family: 'Inter'; font-style: italic; font-weight: 300; font-display: swap; src: url("Inter-LightItalic.woff2?v=3.12") format("woff2"), url("Inter-LightItalic.woff?v=3.12") format("woff"); } @font-face { font-family: 'Inter'; font-style: normal; font-weight: 400; font-display: swap; src: url("Inter-Regular.woff2?v=3.12") format("woff2"), url("Inter-Regular.woff?v=3.12") format("woff"); } @font-face { font-family: 'Inter'; font-style: italic; font-weight: 400; font-display: swap; src: url("Inter-Italic.woff2?v=3.12") format("woff2"), url("Inter-Italic.woff?v=3.12") format("woff"); } @font-face { font-family: 'Inter'; font-style: normal; font-weight: 500; font-display: swap; src: url("Inter-Medium.woff2?v=3.12") format("woff2"), url("Inter-Medium.woff?v=3.12") format("woff"); } @font-face { font-family: 'Inter'; font-style: italic; font-weight: 500; font-display: swap; src: url("Inter-MediumItalic.woff2?v=3.12") format("woff2"), url("Inter-MediumItalic.woff?v=3.12") format("woff"); } @font-face { font-family: 'Inter'; font-style: normal; font-weight: 600; font-display: swap; src: url("Inter-SemiBold.woff2?v=3.12") format("woff2"), url("Inter-SemiBold.woff?v=3.12") format("woff"); } @font-face { font-family: 'Inter'; font-style: italic; font-weight: 600; font-display: swap; src: url("Inter-SemiBoldItalic.woff2?v=3.12") format("woff2"), url("Inter-SemiBoldItalic.woff?v=3.12") format("woff"); } @font-face { font-family: 'Inter'; font-style: normal; font-weight: 700; font-display: swap; src: url("Inter-Bold.woff2?v=3.12") format("woff2"), url("Inter-Bold.woff?v=3.12") format("woff"); } @font-face { font-family: 'Inter'; font-style: italic; font-weight: 700; font-display: swap; src: url("Inter-BoldItalic.woff2?v=3.12") format("woff2"), url("Inter-BoldItalic.woff?v=3.12") format("woff"); } @font-face { font-family: 'Inter'; font-style: normal; font-weight: 800; font-display: swap; src: url("Inter-ExtraBold.woff2?v=3.12") format("woff2"), url("Inter-ExtraBold.woff?v=3.12") format("woff"); } @font-face { font-family: 'Inter'; font-style: italic; font-weight: 800; font-display: swap; src: url("Inter-ExtraBoldItalic.woff2?v=3.12") format("woff2"), url("Inter-ExtraBoldItalic.woff?v=3.12") format("woff"); } @font-face { font-family: 'Inter'; font-style: normal; font-weight: 900; font-display: swap; src: url("Inter-Black.woff2?v=3.12") format("woff2"), url("Inter-Black.woff?v=3.12") format("woff"); } @font-face { font-family: 'Inter'; font-style: italic; font-weight: 900; font-display: swap; src: url("Inter-BlackItalic.woff2?v=3.12") format("woff2"), url("Inter-BlackItalic.woff?v=3.12") format("woff"); }
2302_79757062/insights
frontend/src/assets/Inter/inter.css
CSS
agpl-3.0
4,006
<script setup> import Code from '@/components/Controls/Code.vue' import useQuery from '@/query/resources/useQuery' import { createResource } from 'frappe-ui' import { TextEditor } from 'frappe-ui' import { computed, reactive, inject } from 'vue' const emit = defineEmits(['update:show']) const props = defineProps({ show: Boolean, queryName: String, }) const show = computed({ get: () => props.show, set: (value) => { emit('update:show', value) }, }) let query = inject('query') if (!query) query = useQuery(props.queryName) const alert = reactive({ title: '', query: props.queryName, frequency: 'Daily', cron: null, channel: 'Email', recipients: '', telegram_chat_id: null, condition: { isAdvanced: false, left: '', operator: '=', right: null, advanceCondition: null, }, message: null, }) const frequencyOptions = [ { value: 'Hourly', label: 'Check once an hour' }, { value: 'Daily', label: 'Check once a day' }, { value: 'Weekly', label: 'Check once a week' }, { value: 'Monthly', label: 'Check once a month' }, { value: 'Custom', label: 'Custom' }, ] const channelOptions = [ { label: 'Email', value: 'Email' }, { label: 'Telegram', value: 'Telegram' }, ] const operatorOptions = ['=', '!=', '>', '>=', '<', '<='] const createAlertDisabled = computed(() => { if (!alert.title) return true if (!alert.frequency) return true if (alert.frequency === 'Custom' && !alert.cron) return true if (!alert.channel) return true if (alert.channel === 'Email' && !alert.recipients) return true if (alert.channel === 'Telegram' && !alert.telegram_chat_id) return true if (alert.condition.isAdvanced && !alert.condition.advanceCondition) return true if (!alert.condition.isAdvanced && !alert.condition.left) return true if (!alert.condition.isAdvanced && !alert.condition.operator) return true if (!alert.condition.isAdvanced && !alert.condition.right) return true return false }) const createAlertResource = createResource({ url: 'insights.api.alerts.create_alert' }) function makeCondition() { return alert.condition.isAdvanced ? alert.condition.advanceCondition : `any(results['${alert.condition.left}'] ${alert.condition.operator} ${alert.condition.right})` } function createAlert() { if (createAlertDisabled.value) return const _alert = { ...alert } _alert.condition = makeCondition() createAlertResource .submit({ alert: _alert, }) .then((res) => { console.log(res) show.value = false }) } const testAlertResource = createResource({ url: 'insights.api.alerts.test_alert' }) function testSendAlert() { if (createAlertDisabled.value) return const _alert = { ...alert } _alert.condition = makeCondition() testAlertResource .submit({ alert: _alert, }) .then((res) => { console.log(res) }) } </script> <template> <Dialog :options="{ title: 'Create Alert' }" v-model="show" :dismissable="true"> <template #body-content> <div class="space-y-4 text-base"> <div class="flex gap-4"> <div class="flex flex-1 flex-col space-y-4"> <Input type="text" label="Alert Name" v-model="alert.title" placeholder="e.g. Low Inventory" /> <Input type="select" label="Frequency" v-model="alert.frequency" :options="frequencyOptions" /> <Input v-if="alert.frequency === 'Custom'" type="text" label="Cron" v-model="alert.cron" placeholder="e.g. 0 0 12 * * ?" /> </div> <div class="flex flex-1 flex-col space-y-4"> <Input type="select" label="Channel" v-model="alert.channel" :options="channelOptions" /> <Input v-if="alert.channel === 'Email'" type="text" label="Recipients" v-model="alert.recipients" placeholder="e.g. john@example.com, henry@example.com" /> <Input v-if="alert.channel === 'Telegram'" type="text" label="Telegram Chat ID" v-model="alert.telegram_chat_id" placeholder="e.g. 123456789" /> </div> </div> <div class="space-y-4"> <p class="text-lg font-medium text-gray-800">Send alert when</p> <div class="!mt-2 flex gap-4" v-if="!alert.condition.isAdvanced"> <Input type="select" class="flex-1" v-model="alert.condition.left" :options=" query.results.columns.map((c) => ({ label: c.label, value: c.label, description: c.type, })) " /> <Input type="select" class="flex-1" v-model="alert.condition.operator" :options="operatorOptions" /> <Input type="text" class="flex-1" v-model="alert.condition.right" placeholder="e.g. 100" /> </div> <div v-else class="!mt-2"> <div class="form-textarea h-20"> <Code v-model="alert.condition.advanceCondition" placeholder="Write a python expression..." /> </div> <p class="font-code mt-1 text-sm text-gray-600"> Example: results["Count of Records"][0] > 100 </p> </div> <Input type="checkbox" label="Use Advanced Condition" v-model="alert.condition.isAdvanced" /> </div> <div> <p class="text-lg font-medium text-gray-800"> Message <span class="text-sm font-normal">(Optional)</span> </p> <Input type="textarea" class="mt-1 h-40" v-model="alert.message" :placeholder="`e.g. Hey, We have **low inventory** for **{{ title }}**. Please order more. Thanks, `" /> <p class="mt-2 text-sm text-gray-600"> You can use all the fields from the query like <span class="font-code px-1"> title, data_source </span> etc. like this <span class="font-code px-1" v-html="'{{ title }}'"></span> </p> </div> </div> </template> <template #actions> <Button variant="solid" :disabled="createAlertDisabled" :loading="createAlertResource.loading" class="mr-2" @click="createAlert" > Create </Button> <Button :disabled="createAlertDisabled" :loading="testSendAlert.loading" @click="testSendAlert" > Test </Button> </template> </Dialog> </template>
2302_79757062/insights
frontend/src/components/AlertDialog.vue
Vue
agpl-3.0
6,286
<template> <div class="flex flex-1 overflow-hidden text-base"> <Sidebar v-if="!hideSidebar" /> <RouterView v-slot="{ Component }"> <Suspense> <div class="flex flex-1 flex-col overflow-hidden"> <component :is="Component" :key="$route.fullPath" /> </div> <template #fallback> <SuspenseFallback /> </template> </Suspense> </RouterView> </div> </template> <script setup> import Sidebar from '@/components/Sidebar.vue' import SuspenseFallback from '@/components/SuspenseFallback' import sessionStore from '@/stores/sessionStore' import settingsStore from '@/stores/settingsStore' import { ref, onMounted, watch } from 'vue' import { useRoute } from 'vue-router' const session = sessionStore() const route = useRoute() const hideSidebar = ref(true) watch( route, (newRoute) => { hideSidebar.value = newRoute.meta.hideSidebar || !session.isLoggedIn }, { immediate: true } ) onMounted(() => session.isLoggedIn && settingsStore()) </script>
2302_79757062/insights
frontend/src/components/AppShell.vue
Vue
agpl-3.0
980
<template> <div class="flex flex-1 flex-col overflow-hidden bg-white p-5"> <Breadcrumbs /> <header class="flex h-10 flex-shrink-0 overflow-visible"> <slot name="header" /> </header> <main class="flex flex-1 overflow-hidden"> <slot name="main" /> </main> </div> </template> <script setup> import Breadcrumbs from '@/components/Breadcrumbs.vue' </script>
2302_79757062/insights
frontend/src/components/BasePage.vue
Vue
agpl-3.0
372
<template> <nav> <ol role="list" class="flex h-5 flex-shrink-0 items-center space-x-1 font-light text-gray-800" > <li class="flex items-center"> <router-link to="/" class="mr-1"> <HomeIcon class="h-4 w-4" /> </router-link> <FeatherIcon name="chevron-right" class="h-4 w-4 flex-shrink-0" aria-hidden="true" /> </li> <li v-for="(page, idx) in items" :key="page.label"> <div class="flex items-center"> <router-link :to="idx === items.length - 1 ? '#' : page.href" class="mr-1 hover:underline" :class="{ 'cursor-default hover:no-underline': idx === items.length - 1, }" > {{ page.label }} </router-link> <FeatherIcon v-if="idx !== items.length - 1" name="chevron-right" class="h-4 w-4 flex-shrink-0" aria-hidden="true" /> </div> </li> </ol> </nav> </template> <script setup> import HomeIcon from '@/components/Icons/HomeIcon.vue' const props = defineProps({ items: Array }) </script>
2302_79757062/insights
frontend/src/components/Breadcrumbs.vue
Vue
agpl-3.0
1,039
<script setup> import { areDeeplyEqual } from '@/utils' import * as echarts from 'echarts' import { onBeforeUnmount, onMounted, ref, watch } from 'vue' import ChartTitle from './ChartTitle.vue' const props = defineProps({ title: { type: String, required: false }, subtitle: { type: String, required: false }, options: { type: Object, required: true }, }) let eChart = null const chartRef = ref(null) onMounted(() => { eChart = echarts.init(chartRef.value, 'light', { renderer: 'svg' }) Object.keys(props.options).length && eChart.setOption(props.options) const resizeObserver = new ResizeObserver(() => eChart.resize()) setTimeout(() => chartRef.value && resizeObserver.observe(chartRef.value), 1000) onBeforeUnmount(() => chartRef.value && resizeObserver.unobserve(chartRef.value)) }) watch( () => props.options, (newOptions, oldOptions) => { if (!eChart) return if (JSON.stringify(newOptions) === JSON.stringify(oldOptions)) return if (areDeeplyEqual(newOptions, oldOptions)) return eChart.clear() eChart.setOption(props.options) }, { deep: true } ) defineExpose({ downloadChart }) function downloadChart() { const image = new Image() const type = 'png' image.src = eChart.getDataURL({ type, pixelRatio: 2, backgroundColor: '#fff', }) const link = document.createElement('a') link.href = image.src link.download = `${props.title}.${type}` link.click() } </script> <template> <div class="flex h-full w-full flex-col rounded"> <ChartTitle v-if="title" :title="title" /> <div ref="chartRef" class="w-full flex-1 overflow-hidden"> <slot></slot> </div> </div> </template>
2302_79757062/insights
frontend/src/components/Charts/BaseChart.vue
Vue
agpl-3.0
1,622
<script setup> const props = defineProps({ title: { type: String, required: false }, }) </script> <template> <div class="px-4 py-2 text-lg font-medium leading-6 text-gray-800"> {{ title }} </div> </template>
2302_79757062/insights
frontend/src/components/Charts/ChartTitle.vue
Vue
agpl-3.0
214
<template> <transition name="fade"> <div v-show="show" class="absolute z-10 flex h-full w-full justify-center bg-gray-50/60 pt-20 text-base backdrop-blur-sm backdrop-grayscale" > <div class="max-h-[28rem] w-[38rem] rounded border bg-white shadow-md"> <div class="flex items-center border-b px-3"> <FeatherIcon name="search" class="absolute h-4 w-4 text-gray-600" /> <input ref="searchInput" v-model="searchTerm" class="ml-2 flex h-12 w-full items-center rounded-t-md px-4 focus:outline-none" placeholder="Search..." /> </div> <div class="mt-2 flex flex-col px-2"> <div v-if="commands.length > 0"> <div class="text-sm text-gray-600">Navigation</div> <div v-for="(command, idx) in commands" class="-mx-2 flex h-10 cursor-pointer items-center space-x-2 px-2" @mouseenter="activeIndex = idx" :class="[activeIndex === idx ? 'bg-gray-50' : '']" @click=" () => { commandPalette.close() command.action() } " > <FeatherIcon :name="command.icon || 'arrow-right'" class="h-4 w-4 text-gray-600" /> <div class="flex items-baseline"> <span>{{ command.title }}</span> <span class="ml-2 text-sm text-gray-600"> {{ command.description }} </span> </div> </div> </div> <div v-else class="text-sm text-gray-600">No results found</div> </div> </div> </div> </transition> </template> <script setup> import { ref, watch, computed, nextTick } from 'vue' import { useMagicKeys } from '@vueuse/core' import useCommandPalette from '@/utils/commandPalette' const commandPalette = useCommandPalette() const keys = useMagicKeys() const cmdK = keys['Meta+K'] const escape = keys['Escape'] const searchInput = ref() const show = computed(() => commandPalette.isOpen) watch(cmdK, (pressed) => { if (pressed) { commandPalette.open() } }) watch(escape, (pressed) => { if (pressed && show.value) { commandPalette.close() } }) watch(show, (value) => { if (value) { nextTick(() => { searchInput.value.focus() }) } }) const searchTerm = ref('') const commands = computed(() => { return commandPalette.search(searchTerm.value) }) const activeIndex = ref(0) const ArrowDown = keys['ArrowDown'] const ArrowUp = keys['ArrowUp'] watch(ArrowDown, (pressed) => { if (pressed && show.value) { activeIndex.value = Math.min(commands.value.length - 1, activeIndex.value + 1) } }) watch(ArrowUp, (pressed) => { if (pressed && show.value) { activeIndex.value = Math.max(0, activeIndex.value - 1) } }) const enter = keys['Enter'] watch(enter, (pressed) => { if (pressed && show.value) { commandPalette.close() commands.value[activeIndex.value].action() } }) </script> <style> .fade-enter-active, .fade-leave-active { transition: opacity 0.2s ease-out; } .fade-enter-from, .fade-leave-to { opacity: 0; } </style>
2302_79757062/insights
frontend/src/components/CommandPalette.vue
Vue
agpl-3.0
2,971
<template> <component :is="tag" class="contenteditable align-middle outline-none transition-all before:text-gray-500" :contenteditable="disabled ? false : contenteditable" :placeholder="placeholder" @input="update" @blur="update('blur')" @paste="onPaste" @keypress="onKeypress" ref="element" spellcheck="false" > </component> </template> <script setup> import { onMounted, ref, watch } from 'vue' function replaceAll(str, search, replacement) { return str.split(search).join(replacement) } const emit = defineEmits(['returned', 'update:modelValue', 'change', 'blur']) const props = defineProps({ tag: { type: String, default: 'div', }, contenteditable: { type: [Boolean, String], default: true, }, disabled: { type: Boolean, default: false, }, modelValue: String | Number, value: String | Number, placeholder: String, noHtml: { type: Boolean, default: true, }, noNl: { type: Boolean, default: true, }, }) const element = ref() function currentContent() { return props.noHtml ? element.value?.innerText : element.value?.innerHTML } function updateContent(newcontent) { if (props.noHtml) { element.value.innerText = newcontent } else { element.value.innerHTML = newcontent } } function valuePropPresent() { return props.value != undefined } function update(event) { if (event == 'blur') emit('blur', currentContent()) if (valuePropPresent()) { emit('change', currentContent()) } else { emit('update:modelValue', currentContent()) } } function onPaste(event) { event.preventDefault() let text = (event.originalEvent || event).clipboardData.getData('text/plain') if (props.noNl) { text = replaceAll(text, '\r\n', ' ') text = replaceAll(text, '\n', ' ') text = replaceAll(text, '\r', ' ') } window.document.execCommand('insertText', false, text) } function onKeypress(event) { if (event.key == 'Enter' && props.noNl) { event.preventDefault() emit('returned', currentContent()) } } onMounted(() => { updateContent(valuePropPresent() ? props.value : props.modelValue ?? '') }) watch( () => props.modelValue ?? props.value, (newval, oldval) => { if (newval != currentContent()) { updateContent(newval ?? '') } } ) watch( () => props.noHtml, (newval, oldval) => { updateContent(props.modelValue ?? '') } ) watch( () => props.tag, (newval, oldval) => { updateContent(props.modelValue ?? '') }, { flush: 'post' } ) </script> <style lang="scss"> .contenteditable:empty:before { content: attr(placeholder); pointer-events: none; display: block; /* For Firefox */ } </style>
2302_79757062/insights
frontend/src/components/ContentEditable.vue
Vue
agpl-3.0
2,591
<template> <div class="flex flex-col overflow-hidden text-base"> <span class="mb-2 block text-sm leading-4 text-gray-700"> {{ label || 'Attach File' }} </span> <input ref="fileInput" id="attachment" type="file" :accept="fileType" class="hidden" :disabled="!!file" @input="selectFile" /> <!-- Upload Button --> <Button v-if="!file?.name" @click="upload" :loading="uploading"> <FeatherIcon name="upload" class="mr-1 inline-block h-3 w-3" /> {{ placeholder || 'Upload a file' }} </Button> <!-- Clear Button --> <Button v-else iconRight="x" @click="clear"> <span class="truncate">{{ file.file_name }}</span> </Button> </div> </template> <script setup> import FileUploadHandler from 'frappe-ui/src/utils/fileUploadHandler' import { computed, ref } from 'vue' const emit = defineEmits(['update:modelValue']) const props = defineProps({ modelValue: Object | null, placeholder: String, label: String, fileType: String, }) const file = computed({ get: () => props.modelValue, set: (val) => emit('update:modelValue', val), }) const fileInput = ref(null) function upload() { fileInput.value.click() } function clear() { fileInput.value.value = '' file.value = null } const uploading = ref(false) async function selectFile(e) { const newFile = e.target.files?.[0] if (!newFile) return uploading.value = true const uploader = new FileUploadHandler() uploader .upload(newFile, {}) .then((data) => { file.value = data }) .catch((error) => { file.value = null console.error(error) }) .finally(() => { uploading.value = false }) } </script>
2302_79757062/insights
frontend/src/components/Controls/Attachment.vue
Vue
agpl-3.0
1,627
<template> <Combobox v-model="selectedValue" :multiple="multiple" nullable v-slot="{ open: isComboboxOpen }" > <Popover class="w-full" v-model:show="showOptions" :placement="placement"> <template #target="{ open: openPopover, togglePopover, close: closePopover }"> <slot name="target" v-bind="{ open: openPopover, close: closePopover, togglePopover, isOpen: isComboboxOpen, }" > <div class="w-full space-y-1.5"> <label v-if="$props.label" class="block text-xs text-gray-600"> {{ $props.label }} </label> <button class="flex h-7 w-full items-center justify-between gap-2 rounded bg-gray-100 py-1 px-2 transition-colors hover:bg-gray-200 focus:ring-2 focus:ring-gray-400" :class="[isComboboxOpen ? 'bg-gray-200' : '', $props.buttonClasses]" @click="() => togglePopover()" > <div class="flex flex-1 items-center gap-2 overflow-hidden"> <slot name="prefix" /> <span v-if="selectedValue" class="flex-1 truncate text-left text-base leading-5" > {{ displayValue(selectedValue) }} </span> <span v-else class="text-base leading-5 text-gray-600"> {{ placeholder || '' }} </span> <slot name="suffix" /> </div> <FeatherIcon v-show="!$props.loading" name="chevron-down" class="h-4 w-4 text-gray-600" aria-hidden="true" /> <LoadingIndicator class="h-4 w-4 text-gray-600" v-show="$props.loading" /> </button> </div> </slot> </template> <template #body="{ isOpen, togglePopover }"> <div v-show="isOpen"> <div class="relative mt-1 overflow-hidden rounded-lg bg-white text-base shadow-2xl" :class="bodyClasses" > <ComboboxOptions class="flex max-h-[15rem] flex-col overflow-hidden p-1.5" static > <div v-if="!hideSearch" class="relative mb-1 w-full flex-shrink-0"> <ComboboxInput ref="searchInput" class="form-input w-full" type="text" :value="query" @change="query = $event.target.value" autocomplete="off" placeholder="Search" /> <button class="absolute right-0 inline-flex h-7 w-7 items-center justify-center" @click="selectedValue = null" > <FeatherIcon name="x" class="w-4" /> </button> </div> <div class="w-full flex-1 overflow-y-auto"> <div v-for="group in groups" :key="group.key" v-show="group.items.length > 0" > <div v-if="group.group && !group.hideLabel" class="sticky top-0 truncate bg-white px-2.5 py-1.5 text-sm font-medium text-gray-600" > {{ group.group }} </div> <ComboboxOption as="template" v-for="(option, idx) in group.items.slice(0, 50)" :key="option?.value || idx" :value="option" v-slot="{ active, selected }" > <li :class="[ 'flex h-7 cursor-pointer items-center justify-between rounded px-2.5 text-base', { 'bg-gray-100': active }, ]" > <div class="flex flex-1 items-center gap-2 overflow-hidden" > <div v-if="$slots['item-prefix'] || $props.multiple" class="flex-shrink-0" > <slot name="item-prefix" v-bind="{ active, selected, option }" > <Square v-show="!isOptionSelected(option)" class="h-4 w-4 text-gray-700" /> <CheckSquare v-show="isOptionSelected(option)" class="h-4 w-4 text-gray-700" /> </slot> </div> <span class="flex-1 truncate"> {{ getLabel(option) }} </span> </div> <div v-if="$slots['item-suffix'] || option?.description" class="ml-2 flex-shrink-0" > <slot name="item-suffix" v-bind="{ active, selected, option }" > <div v-if="option?.description" class="text-sm text-gray-600" > {{ option.description }} </div> </slot> </div> </li> </ComboboxOption> </div> </div> <li v-if="groups.length == 0" class="rounded-md px-2.5 py-1.5 text-base text-gray-600" > No results found </li> </ComboboxOptions> <div v-if="$slots.footer || showFooter || multiple" class="border-t p-1"> <slot name="footer" v-bind="{ togglePopover }"> <div v-if="multiple" class="flex items-center justify-end"> <Button v-if="!areAllOptionsSelected" label="Select All" @click.stop="selectAll" /> <Button v-if="areAllOptionsSelected" label="Clear All" @click.stop="clearAll" /> </div> <div v-else class="flex items-center justify-end"> <Button label="Clear" @click.stop="selectedValue = null" /> </div> </slot> </div> </div> </div> </template> </Popover> </Combobox> </template> <script> import { fuzzySearch } from '@/utils' import { Combobox, ComboboxButton, ComboboxInput, ComboboxOption, ComboboxOptions, } from '@headlessui/vue' import { LoadingIndicator } from 'frappe-ui' import { CheckSquare, Square } from 'lucide-vue-next' import { nextTick } from 'vue' import Popover from '../Popover.vue' export default { name: 'Autocomplete', props: [ 'label', 'modelValue', 'options', 'placeholder', 'bodyClasses', 'multiple', 'loading', 'hideSearch', 'autoFocus', 'placement', 'showFooter', 'buttonClasses', ], emits: ['update:modelValue', 'update:query', 'change'], components: { Popover, Combobox, ComboboxInput, ComboboxOptions, ComboboxOption, ComboboxButton, CheckSquare, Square, }, expose: ['togglePopover'], data() { return { query: '', showOptions: false, } }, computed: { selectedValue: { get() { let _selectedOptions if (!this.multiple) { _selectedOptions = this.findOption(this.modelValue) if (this.modelValue && !_selectedOptions) { _selectedOptions = this.sanitizeOption(this.modelValue) } return _selectedOptions } _selectedOptions = this.modelValue?.map((v) => { const option = this.findOption(v) if (option) return option return this.sanitizeOption(v) }) if (this.modelValue && !_selectedOptions.length) { _selectedOptions = this.sanitizeOptions(this.modelValue) } return _selectedOptions }, set(val) { this.query = '' if (val && !this.multiple) this.showOptions = false this.$emit('update:modelValue', val) }, }, groups() { if (!this.options || this.options.length == 0) return [] let groups = this.options[0]?.group ? this.options : [{ group: '', items: this.sanitizeOptions(this.options) }] return groups .map((group, i) => { return { key: i, group: group.group, hideLabel: group.hideLabel || false, items: this.filterOptions(this.sanitizeOptions(group.items)), } }) .filter((group) => group.items.length > 0) }, allOptions() { return this.groups.flatMap((group) => group.items) }, areAllOptionsSelected() { if (!this.multiple) return false return this.allOptions.length === this.selectedValue?.length }, }, watch: { query(q) { this.$emit('update:query', q) }, showOptions(val) { if (val) nextTick(() => this.$refs.searchInput?.$el?.focus()) }, }, methods: { togglePopover(val) { this.showOptions = val ?? !this.showOptions }, findOption(option) { if (!option) return option return this.allOptions.find((o) => o.value === (option.value || option)) }, filterOptions(options) { if (!this.query) return options return fuzzySearch(options, { term: this.query, keys: ['label', 'value'], }) }, displayValue(option) { if (!option) return '' if (!this.multiple) { if (typeof option === 'object') { return this.getLabel(option) } let selectedOption = this.allOptions.find((o) => o.value === option) return this.getLabel(selectedOption) } if (!Array.isArray(option)) return '' if (option.length === 0) return '' if (option.length === 1) return this.getLabel(option[0]) return `${option.length} selected` // in case of `multiple`, option is an array of values // so the display value should be comma separated labels // return option // .map((v) => { // if (typeof v === 'object') { // return this.getLabel(v) // } // let selectedOption = this.allOptions.find((o) => o.value === v) // return this.getLabel(selectedOption) // }) // .join(', ') }, getLabel(option) { if (typeof option !== 'object') return option return option?.label || option?.value || 'No label' }, sanitizeOptions(options) { if (!options) return [] // in case the options are just strings, convert them to objects return options.map((option) => this.sanitizeOption(option)) }, sanitizeOption(option) { return typeof option === 'string' ? { label: option, value: option } : option }, isOptionSelected(option) { if (!this.multiple) { return this.selectedValue?.value === option.value } return this.selectedValue?.find((v) => v && v.value === option.value) }, selectAll() { this.selectedValue = this.allOptions }, clearAll() { this.selectedValue = [] }, }, } </script>
2302_79757062/insights
frontend/src/components/Controls/Autocomplete.vue
Vue
agpl-3.0
9,956
<template> <SwitchGroup v-bind="$attrs"> <div class="flex items-center justify-between text-sm"> <SwitchLabel class="mr-4 select-none text-base font-medium text-gray-800"> {{ $props.label }} </SwitchLabel> <Switch v-model="enabled" class="relative inline-flex items-center rounded-full transition-colors" :class="[ enabled ? 'bg-gray-900' : 'bg-gray-300', props.size === 'sm' ? 'h-4 w-6' : 'h-4.5 w-8', ]" > <span :class="[ enabled ? props.size == 'sm' ? 'translate-x-2.5' : 'translate-x-4' : 'translate-x-1', props.size == 'sm' ? 'h-2.5 w-2.5' : ' h-3 w-3 ', ]" class="inline-block transform rounded-full bg-white transition-transform" /> </Switch> </div> </SwitchGroup> </template> <script setup> import { Switch, SwitchGroup, SwitchLabel } from '@headlessui/vue' const props = defineProps(['label', 'size']) const enabled = defineModel({ type: Boolean }) </script>
2302_79757062/insights
frontend/src/components/Controls/Checkbox.vue
Vue
agpl-3.0
986
<template> <codemirror :tab-size="2" :disabled="readOnly" v-model="code" class="font-[400]" :autofocus="autofocus" :indent-with-tab="true" :extensions="extensions" :placeholder="placeholder" @update="onUpdate" @focus="emit('focus')" @blur="emit('blur')" @ready="codeMirror = $event" /> </template> <script setup> import { autocompletion, closeBrackets } from '@codemirror/autocomplete' import { javascript } from '@codemirror/lang-javascript' import { python } from '@codemirror/lang-python' import { MySQL, sql } from '@codemirror/lang-sql' import { HighlightStyle, syntaxHighlighting, syntaxTree } from '@codemirror/language' import { EditorView } from '@codemirror/view' import { tags } from '@lezer/highlight' import { onMounted, ref, watch } from 'vue' import { Codemirror } from 'vue-codemirror' const props = defineProps({ modelValue: String, readOnly: { type: Boolean, default: false, }, autofocus: { type: Boolean, default: true, }, placeholder: { type: String, default: 'Enter an expression...', }, completions: { type: Function, default: null, }, language: { type: String, default: 'javascript', }, tables: { type: Array, default: () => [], }, schema: { type: Object, default: () => ({}), }, hideLineNumbers: { type: Boolean, default: false, }, disableAutocompletions: { type: Boolean, default: false, }, }) const emit = defineEmits(['inputChange', 'viewUpdate', 'focus', 'blur']) onMounted(() => { if (props.hideLineNumbers) { document.querySelectorAll('.cm-gutters').forEach((gutter) => { gutter.style.display = 'none' }) } }) const onUpdate = (viewUpdate) => { emit('viewUpdate', { cursorPos: viewUpdate.state.selection.ranges[0].to, syntaxTree: syntaxTree(viewUpdate.state), state: viewUpdate.state, }) } const codeMirror = ref(null) const code = defineModel() watch(code, (value, oldValue) => { if (value !== oldValue) { emit('inputChange', value) } }) const language = props.language === 'javascript' ? javascript() : props.language === 'python' ? python() : sql({ dialect: MySQL, upperCaseKeywords: true, schema: props.schema, tables: props.tables, }) const extensions = [language, closeBrackets(), EditorView.lineWrapping] const autocompletionOptions = { activateOnTyping: true, closeOnBlur: false, maxRenderedOptions: 10, icons: false, optionClass: () => 'flex h-7 !px-2 items-center rounded !text-gray-600', } if (props.completions) { autocompletionOptions.override = [ (context) => { return props.completions(context, syntaxTree(context.state)) }, ] } extensions.push(autocompletion(autocompletionOptions)) const chalky = '#e5a05b', coral = '#b04a54', cyan = '#45a5b1', invalid = '#ffffff', ivory = '#6a6a6a', stone = '#7d8799', // Brightened compared to original to increase contrast malibu = '#61afef', sage = '#76c457', whiskey = '#d19a66', violet = '#c678dd' const getHighlighterStyle = () => HighlightStyle.define([ { tag: tags.keyword, color: violet }, { tag: [tags.name, tags.deleted, tags.character, tags.propertyName, tags.macroName], color: coral, }, { tag: [tags.function(tags.variableName), tags.labelName], color: malibu, }, { tag: [tags.color, tags.constant(tags.name), tags.standard(tags.name)], color: whiskey, }, { tag: [tags.definition(tags.name), tags.separator], color: ivory }, { tag: [ tags.typeName, tags.className, tags.number, tags.changed, tags.annotation, tags.modifier, tags.self, tags.namespace, ], color: chalky, }, { tag: [ tags.operator, tags.operatorKeyword, tags.url, tags.escape, tags.regexp, tags.link, tags.special(tags.string), ], color: cyan, }, { tag: [tags.meta, tags.comment], color: stone }, { tag: tags.strong, fontWeight: 'bold' }, { tag: tags.emphasis, fontStyle: 'italic' }, { tag: tags.strikethrough, textDecoration: 'line-through' }, { tag: tags.link, color: stone, textDecoration: 'underline' }, { tag: tags.heading, fontWeight: 'bold', color: coral }, { tag: [tags.atom, tags.bool, tags.special(tags.variableName)], color: whiskey, }, { tag: [tags.processingInstruction, tags.string, tags.inserted], color: sage, }, { tag: tags.invalid, color: invalid }, ]) extensions.push(syntaxHighlighting(getHighlighterStyle())) defineExpose({ get cursorPos() { return codeMirror.value.view.state.selection.ranges[0].to }, focus: () => codeMirror.value.view.focus(), setCursorPos: (pos) => { const _pos = Math.min(pos, code.value.length) codeMirror.value.view.dispatch({ selection: { anchor: _pos, head: _pos } }) }, }) </script>
2302_79757062/insights
frontend/src/components/Controls/Code.vue
Vue
agpl-3.0
4,723
<template> <ColorPicker :modelValue="value" @update:modelValue="handleColorChange" :placement="placement"> <template #target="{ togglePopover }"> <div class="relative flex items-center justify-between"> <div class="absolute left-2 top-[6px] z-10 h-4 w-4 rounded shadow-sm" @click="togglePopover" :style="{ background: value ? value : `linear-gradient(217deg, rgba(255,0,0,.8), rgba(255,0,0,0) 70.71%), linear-gradient(127deg, rgba(0,255,0,.8), rgba(0,255,0,0) 70.71%), linear-gradient(336deg, rgba(0,0,255,.8), rgba(0,0,255,0) 70.71%)`, }" ></div> <Input type="text" class="dark:border-zinc-700 dark:bg-zinc-800 dark:text-zinc-300 dark:focus:bg-zinc-700 w-full rounded-md text-sm text-gray-700" placeholder="Select Color" inputClass="pl-8 pr-6" :modelValue="value" @update:modelValue="handleColorChange" ></Input> <div class="dark:text-zinc-300 absolute right-1 top-[3px] cursor-pointer p-1 text-gray-700" @click="clearValue" v-show="value" > <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" > <path fill="currentColor" d="M18.3 5.71a.996.996 0 0 0-1.41 0L12 10.59L7.11 5.7A.996.996 0 1 0 5.7 7.11L10.59 12L5.7 16.89a.996.996 0 1 0 1.41 1.41L12 13.41l4.89 4.89a.996.996 0 1 0 1.41-1.41L13.41 12l4.89-4.89c.38-.38.38-1.02 0-1.4z" /> </svg> </div> </div> </template> </ColorPicker> </template> <script setup> import { getRGB } from '@/utils/colors' import { computed } from 'vue' import ColorPicker from './ColorPicker.vue' const props = defineProps({ modelValue: String, placement: String }) const emit = defineEmits(['update:modelValue']) const value = computed({ get: () => props.modelValue, set: (value) => emit('update:modelValue', value), }) const handleColorChange = (v) => { value.value = getRGB(v) } const clearValue = () => { value.value = '' } </script>
2302_79757062/insights
frontend/src/components/Controls/ColorInput.vue
Vue
agpl-3.0
2,013
<template> <div> <label class="mb-1.5 block text-xs text-gray-600">Color Palette</label> <Autocomplete v-model="selectedPalette" :options="colorPaletteOptions" placeholder="Color palette" > </Autocomplete> <div class="mt-1.5 flex flex-wrap gap-1 px-1"> <template v-for="(color, index) in getPaletteColors(selectedPalette.value)" :key="index" > <ColorPicker :modelValue="color" @update:modelValue="handleColorChange($event, index)" > <template #target="{ togglePopover }"> <div class="h-5 w-5 rounded-sm" :class="selectedPalette.value === 'custom' ? 'cursor-pointer' : ''" :style="{ backgroundColor: color }" @click="togglePopover" @click.meta="removeColor(index)" ></div> </template> </ColorPicker> </template> <ColorPicker :modelValue="newColor" @update:modelValue="handleColorChange($event, newColorIndex)" > <template #target="{ togglePopover }"> <div class="flex h-5 w-5 cursor-pointer items-center justify-center rounded-sm border border-dashed border-gray-500 text-gray-500 hover:border-gray-700 hover:text-gray-700" @click=" () => { togglePopover() newColor = '#000000' newColorIndex = getPaletteColors(selectedPalette.value).length } " > <Plus class="h-3 w-3" /> </div> </template> </ColorPicker> </div> </div> </template> <script setup> import { generateColorPalette, getColors } from '@/utils/colors' import { Plus } from 'lucide-vue-next' import { computed, ref, watch } from 'vue' import ColorPicker from './ColorPicker.vue' const colorPaletteOptions = [ { label: 'Default', value: 'default' }, { label: 'Blues', value: 'blue' }, { label: 'Greens', value: 'green' }, { label: 'Yellows', value: 'yellow' }, { label: 'Teals', value: 'teal' }, { label: 'Custom', value: 'custom' }, ] const paletteColors = colorPaletteOptions.reduce((acc, option) => { if (option.value !== 'custom') { acc[option.value] = generateColorPalette(option.value) } if (option.value === 'default') { acc[option.value] = getColors().slice(0, 10) } return acc }, {}) const selectedPalette = ref() watch(selectedPalette, () => (colors.value = selectedPaletteColors.value)) const selectedPaletteColors = computed(() => getPaletteColors(selectedPalette.value.value)) const colors = defineModel() if (!colors.value?.length) { selectedPalette.value = colorPaletteOptions.at(0) } else if (isCustomPalette(colors.value)) { selectedPalette.value = colorPaletteOptions.at(-1) } else { selectedPalette.value = guessPredefinedPalette(colors.value) } function getPaletteColors(palette) { if (palette === 'custom') { return colors.value?.length ? colors.value : getPaletteColors('default') } return paletteColors[palette] ?? [] } function guessPredefinedPalette(colors) { if (!colors?.length) return false return colorPaletteOptions.find((palette) => colors.every((color) => paletteColors[palette.value]?.includes(color)) ) } function isCustomPalette(colors) { const isPredefinedPalette = guessPredefinedPalette(colors) return !isPredefinedPalette && colors.length > 0 } function handleColorChange(color, index) { if (selectedPalette.value.value !== 'custom') { selectedPalette.value = colorPaletteOptions[1] colors.value = selectedPaletteColors.value.length ? selectedPaletteColors.value : getPaletteColors('default') } colors.value[index] = color } const newColor = ref('#000000') const newColorIndex = ref(0) function removeColor(index) { if (selectedPalette.value.value !== 'custom') return colors.value.splice(index, 1) } </script>
2302_79757062/insights
frontend/src/components/Controls/ColorPalette.vue
Vue
agpl-3.0
3,682
<template> <Popover transition="default" :placement="placement" class="!block w-full" popoverClass="!min-w-fit" > <template #target="{ togglePopover, isOpen }"> <slot name="target" :togglePopover=" () => { togglePopover() setSelectorPosition(modelColor) } " :isOpen="isOpen" ></slot> </template> <template #body> <div ref="colorPicker" class="dark:bg-zinc-900 rounded-lg bg-white p-3 shadow-lg"> <div ref="colorMap" :style="{ background: ` linear-gradient(0deg, black, transparent), linear-gradient(90deg, white, transparent), hsl(${hue}, 100%, 50%) `, }" @mousedown.stop="handleSelectorMove" class="relative m-auto h-24 w-44 rounded-md" @click.prevent="setColor" > <div ref="colorSelector" @mousedown.stop="handleSelectorMove" class="absolute rounded-full border border-black border-opacity-20 before:absolute before:h-full before:w-full before:rounded-full before:border-2 before:border-white before:bg-[currentColor] after:absolute after:left-[2px] after:top-[2px] after:h-[calc(100%-4px)] after:w-[calc(100%-4px)] after:rounded-full after:border after:border-black after:border-opacity-20 after:bg-transparent" :style="{ height: '12px', width: '12px', left: `calc(${colorSelectorPosition.x}px - 6px)`, top: `calc(${colorSelectorPosition.y}px - 6px)`, color: modelColor, background: 'transparent', } as StyleValue" ></div> </div> <div ref="hueMap" class="relative m-auto mt-2 h-3 w-44 rounded-md" @click="setHue" @mousedown.stop="handleHueSelectorMove" :style="{ background: ` linear-gradient(90deg, hsl(0, 100%, 50%), hsl(60, 100%, 50%), hsl(120, 100%, 50%), hsl(180, 100%, 50%), hsl(240, 100%, 50%), hsl(300, 100%, 50%), hsl(360, 100%, 50%)) `, }" > <div ref="hueSelector" @mousedown.stop="handleHueSelectorMove" class="absolute rounded-full border border-[rgba(0,0,0,.2)] before:absolute before:h-full before:w-full before:rounded-full before:border-2 before:border-white before:bg-[currentColor] after:absolute after:left-[2px] after:top-[2px] after:h-[calc(100%-4px)] after:w-[calc(100%-4px)] after:rounded-full after:border after:border-[rgba(0,0,0,.2)] after:bg-transparent" :style="{ height: '12px', width: '12px', left: `calc(${hueSelectorPosition.x}px - 6px)`, color: `hsl(${hue}, 100%, 50%)`, background: 'transparent', }" ></div> </div> <div ref="colorPalette"> <div class="mt-3 flex flex-wrap gap-1.5"> <div v-for="color in colors" :key="color" class="h-3.5 w-3.5 cursor-pointer rounded-full shadow-sm" @click=" () => { setSelectorPosition(color) updateColor() } " :style="{ background: color, }" ></div> <svg v-if="isSupported" class="dark:text-zinc-300 text-gray-700" @click="() => open()" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" > <g fill="none" fill-rule="evenodd"> <path d="M24 0v24H0V0h24ZM12.593 23.258l-.011.002l-.071.035l-.02.004l-.014-.004l-.071-.035c-.01-.004-.019-.001-.024.005l-.004.01l-.017.428l.005.02l.01.013l.104.074l.015.004l.012-.004l.104-.074l.012-.016l.004-.017l-.017-.427c-.002-.01-.009-.017-.017-.018Zm.265-.113l-.013.002l-.185.093l-.01.01l-.003.011l.018.43l.005.012l.008.007l.201.093c.012.004.023 0 .029-.008l.004-.014l-.034-.614c-.003-.012-.01-.02-.02-.022Zm-.715.002a.023.023 0 0 0-.027.006l-.006.014l-.034.614c0 .012.007.02.017.024l.015-.002l.201-.093l.01-.008l.004-.011l.017-.43l-.003-.012l-.01-.01l-.184-.092Z" /> <path fill="currentColor" d="M20.477 3.511a3 3 0 0 0-4.243 0l-1.533 1.533a2.991 2.991 0 0 0-3.41.581l-.713.714a2 2 0 0 0 0 2.829l-6.486 6.485a3 3 0 0 0-.878 2.122v1.8a1.2 1.2 0 0 0 1.2 1.2h1.8a3 3 0 0 0 2.12-.88l6.486-6.484a2 2 0 0 0 2.829 0l.714-.715a2.991 2.991 0 0 0 .581-3.41l1.533-1.532a3 3 0 0 0 0-4.243ZM5.507 17.067l6.485-6.485l1.414 1.414l-6.485 6.486a1 1 0 0 1-.707.293h-1v-1a1 1 0 0 1 .293-.707Z" /> </g> </svg> </div> </div> </div> </template> </Popover> </template> <script setup lang="ts"> import { HSVToHex, HexToHSV, getRGB } from '@/utils/colors' import { clamp, useEyeDropper } from '@vueuse/core' import { Popover } from 'frappe-ui' import { PropType, Ref, StyleValue, computed, nextTick, ref, watch } from 'vue' const hueMap = ref(null) as unknown as Ref<HTMLDivElement> const colorMap = ref(null) as unknown as Ref<HTMLDivElement> const hueSelector = ref(null) as unknown as Ref<HTMLDivElement> const colorSelector = ref(null) as unknown as Ref<HTMLDivElement> const colorSelectorPosition = ref({ x: 0, y: 0 }) const hueSelectorPosition = ref({ x: 0, y: 0 }) let currentColor = '#FFF' as HashString const { isSupported, sRGBHex, open } = useEyeDropper() const props = defineProps({ placement: { type: String, default: 'bottom-start', }, modelValue: { type: String as PropType<HashString | RGBString | null>, default: null, }, }) const modelColor = computed(() => { return getRGB(props.modelValue) }) const emit = defineEmits(['update:modelValue']) const colors = [ '#FF6633', '#FFB399', '#FF33FF', '#00B3E6', '#E6B333', '#3366E6', '#999966', '#99FF99', ] as HashString[] if (!isSupported.value) { colors.push('#B34D4D') } const setColorSelectorPosition = (color: HashString) => { const { width, height } = colorMap.value.getBoundingClientRect() const { s, v } = HexToHSV(color) let x = clamp(s * width, 0, width) let y = clamp((1 - v) * height, 0, height) colorSelectorPosition.value = { x, y } } const setHueSelectorPosition = (color: HashString) => { const { width } = hueMap.value.getBoundingClientRect() const { h } = HexToHSV(color) const left = (h / 360) * width hueSelectorPosition.value = { x: left, y: 0 } } const handleSelectorMove = (ev: MouseEvent) => { setColor(ev) const mouseMove = (mouseMoveEvent: MouseEvent) => { mouseMoveEvent.preventDefault() setColor(mouseMoveEvent) } document.addEventListener('mousemove', mouseMove) document.addEventListener( 'mouseup', (mouseUpEvent) => { document.removeEventListener('mousemove', mouseMove) mouseUpEvent.preventDefault() }, { once: true } ) } const handleHueSelectorMove = (ev: MouseEvent) => { setHue(ev) const mouseMove = (mouseMoveEvent: MouseEvent) => { mouseMoveEvent.preventDefault() setHue(mouseMoveEvent) } document.addEventListener('mousemove', mouseMove) document.addEventListener( 'mouseup', (mouseUpEvent) => { document.removeEventListener('mousemove', mouseMove) mouseUpEvent.preventDefault() }, { once: true } ) } function setColor(ev: MouseEvent) { const clickPointX = ev.clientX const clickPointY = ev.clientY const colorMapBounds = colorMap.value.getBoundingClientRect() let pointX = clickPointX - colorMapBounds.left let pointY = clickPointY - colorMapBounds.top pointX = clamp(pointX, 0, colorMapBounds.width) pointY = clamp(pointY, 0, colorMapBounds.height) colorSelectorPosition.value = { x: pointX, y: pointY } updateColor() } function setHue(ev: MouseEvent) { const hueMapBounds = hueMap.value.getBoundingClientRect() const { clientX } = ev let point = clientX - hueMapBounds.left point = clamp(point, 0, hueMapBounds.width) hueSelectorPosition.value = { x: point, y: 0 } updateColor() } function setSelectorPosition(color: HashString | null) { if (!color) return nextTick(() => { setColorSelectorPosition(color) setHueSelectorPosition(color) }) } const hue = computed(() => { if (!hueMap.value) return 0 const positionX = hueSelectorPosition.value.x || 0 const width = hueMap.value.getBoundingClientRect().width || 1 return Math.round((positionX / width) * 360) }) const updateColor = () => { nextTick(() => { const colorMapBounds = colorMap.value.getBoundingClientRect() const s = Math.round((colorSelectorPosition.value.x / colorMapBounds.width) * 100) const v = 100 - Math.round((colorSelectorPosition.value.y / colorMapBounds.height) * 100) const h = hue.value currentColor = HSVToHex(h, s, v) emit('update:modelValue', currentColor) }) } watch(sRGBHex, () => { if (!isSupported.value || !sRGBHex.value) return emit('update:modelValue', sRGBHex.value) }) watch( () => props.modelValue, (color) => { if (color === currentColor) return setSelectorPosition(getRGB(color)) }, { immediate: true } ) </script>
2302_79757062/insights
frontend/src/components/Controls/ColorPicker.vue
Vue
agpl-3.0
8,705
<template> <Popover @open="selectCurrentMonthYear" class="flex w-full [&>div:first-child]:w-full"> <template #target="{ togglePopover }"> <input readonly type="text" :placeholder="placeholder" :value="value && formatter ? formatter(value) : value" @focus="!readonly ? togglePopover() : null" :class="[ 'form-input block h-7 w-full cursor-pointer select-none rounded border-gray-400 text-sm placeholder-gray-500', inputClass, ]" /> </template> <template #body="{ togglePopover }"> <div class="my-2 w-fit select-none space-y-3 rounded border border-gray-50 bg-white p-3 text-base shadow" > <div class="flex items-center text-gray-700"> <div class="flex h-6 w-6 cursor-pointer items-center justify-center rounded hover:bg-gray-100" > <FeatherIcon @click="prevMonth" name="chevron-left" class="h-5 w-5" /> </div> <div class="flex-1 text-center text-lg font-medium text-blue-500"> {{ formatMonth }} </div> <div class="flex h-6 w-6 cursor-pointer items-center justify-center rounded hover:bg-gray-100" > <FeatherIcon @click="nextMonth" name="chevron-right" class="h-5 w-5" /> </div> </div> <div class="flex space-x-2"> <Input type="text" :value="value" @change="selectDate(getDate($event)) || togglePopover()" ></Input> <Button class="h-7" @click="selectDate(getDate()) || togglePopover()"> Today </Button> </div> <div class="mt-2 flex flex-col items-center justify-center text-base"> <div class="flex w-full items-center space-x-1 text-gray-600"> <div class="flex h-[30px] w-[30px] items-center justify-center text-center" v-for="(d, i) in ['S', 'M', 'T', 'W', 'T', 'F', 'S']" :key="i" > {{ d }} </div> </div> <div v-for="(week, i) in datesAsWeeks" :key="i" class="mt-1"> <div class="flex w-full items-center"> <div v-for="date in week" :key="toValue(date)" class="mr-1 flex h-[30px] w-[30px] cursor-pointer items-center justify-center rounded last:mr-0 hover:bg-blue-50 hover:text-blue-500" :class="{ 'text-gray-600': date.getMonth() !== currentMonth - 1, 'text-blue-500': toValue(date) === toValue(today), 'bg-blue-50 font-semibold text-blue-500': toValue(date) === value, }" @click=" () => { selectDate(date) togglePopover() } " > {{ date.getDate() }} </div> </div> </div> </div> <div class="mt-1 flex w-full justify-end"> <div class="cursor-pointer rounded px-2 py-1 hover:bg-gray-100" @click=" () => { selectDate('') togglePopover() } " > Clear </div> </div> </div> </template> </Popover> </template> <script> export default { name: 'DatePicker', props: ['value', 'placeholder', 'formatter', 'readonly', 'inputClass'], emits: ['change'], data() { return { currentYear: null, currentMonth: null, } }, created() { this.selectCurrentMonthYear() }, computed: { today() { return this.getDate() }, datesAsWeeks() { let datesAsWeeks = [] let dates = this.dates.slice() while (dates.length) { let week = dates.splice(0, 7) datesAsWeeks.push(week) } return datesAsWeeks }, dates() { if (!(this.currentYear && this.currentMonth)) { return [] } let monthIndex = this.currentMonth - 1 let year = this.currentYear let firstDayOfMonth = this.getDate(year, monthIndex, 1) let lastDayOfMonth = this.getDate(year, monthIndex + 1, 0) let leftPaddingCount = firstDayOfMonth.getDay() let rightPaddingCount = 6 - lastDayOfMonth.getDay() let leftPadding = this.getDatesAfter(firstDayOfMonth, -leftPaddingCount) let rightPadding = this.getDatesAfter(lastDayOfMonth, rightPaddingCount) let daysInMonth = this.getDaysInMonth(monthIndex, year) let datesInMonth = this.getDatesAfter(firstDayOfMonth, daysInMonth - 1) let dates = [...leftPadding, firstDayOfMonth, ...datesInMonth, ...rightPadding] if (dates.length < 42) { const finalPadding = this.getDatesAfter(dates.at(-1), 42 - dates.length) dates = dates.concat(...finalPadding) } return dates }, formatMonth() { let date = this.getDate(this.currentYear, this.currentMonth - 1, 1) return date.toLocaleString('en-US', { month: 'short', year: 'numeric', }) }, }, methods: { selectDate(date) { this.$emit('change', this.toValue(date)) }, selectCurrentMonthYear() { let date = this.value ? this.getDate(this.value) : this.getDate() if (date === 'Invalid Date') { date = this.getDate() } this.currentYear = date.getFullYear() this.currentMonth = date.getMonth() + 1 }, prevMonth() { this.changeMonth(-1) }, nextMonth() { this.changeMonth(1) }, changeMonth(adder) { this.currentMonth = this.currentMonth + adder if (this.currentMonth < 1) { this.currentMonth = 12 this.currentYear = this.currentYear - 1 } if (this.currentMonth > 12) { this.currentMonth = 1 this.currentYear = this.currentYear + 1 } }, getDatesAfter(date, count) { let incrementer = 1 if (count < 0) { incrementer = -1 count = Math.abs(count) } let dates = [] while (count) { date = this.getDate( date.getFullYear(), date.getMonth(), date.getDate() + incrementer ) dates.push(date) count-- } if (incrementer === -1) { return dates.reverse() } return dates }, getDaysInMonth(monthIndex, year) { let daysInMonthMap = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] let daysInMonth = daysInMonthMap[monthIndex] if (monthIndex === 1 && this.isLeapYear(year)) { return 29 } return daysInMonth }, isLeapYear(year) { if (year % 400 === 0) return true if (year % 100 === 0) return false if (year % 4 === 0) return true return false }, toValue(date) { if (!date) { return '' } // toISOString is buggy and reduces the day by one // this is because it considers the UTC timestamp // in order to circumvent that we need to use luxon/moment // but that refactor could take some time, so fixing the time difference // as suggested in this answer. // https://stackoverflow.com/a/16084846/3541205 date.setHours(0, -date.getTimezoneOffset(), 0, 0) return date.toISOString().slice(0, 10) }, getDate(...args) { let d = new Date(...args) return d }, }, } </script>
2302_79757062/insights
frontend/src/components/Controls/DatePicker.vue
Vue
agpl-3.0
6,647
<template> <div class="w-fit select-none space-y-3 bg-white p-1 text-base"> <div class="flex items-center text-gray-700"> <div class="flex h-6 w-6 cursor-pointer items-center justify-center rounded hover:bg-gray-100" > <FeatherIcon @click="prevMonth" name="chevron-left" class="h-5 w-5" /> </div> <div class="flex-1 text-center text-lg font-medium text-blue-500"> {{ formatMonth }} </div> <div class="flex h-6 w-6 cursor-pointer items-center justify-center rounded hover:bg-gray-100" > <FeatherIcon @click="nextMonth" name="chevron-right" class="h-5 w-5" /> </div> </div> <div class="flex space-x-2"> <Input type="text" :value="value" @change="selectDate(getDate($event))"></Input> <Button class="h-7" @click="selectDate(getDate())"> Today </Button> </div> <div class="mt-2 flex flex-col items-center justify-center text-base"> <div class="flex w-full items-center space-x-1 text-gray-600"> <div class="flex h-[30px] w-[30px] items-center justify-center text-center" v-for="(d, i) in ['S', 'M', 'T', 'W', 'T', 'F', 'S']" :key="i" > {{ d }} </div> </div> <div v-for="(week, i) in datesAsWeeks" :key="i" class="mt-1"> <div class="flex w-full items-center"> <div v-for="date in week" :key="toValue(date)" class="mr-1 flex h-[30px] w-[30px] cursor-pointer items-center justify-center rounded last:mr-0 hover:bg-blue-50 hover:text-blue-500" :class="{ 'text-gray-600': date.getMonth() !== currentMonth - 1, 'text-blue-500': toValue(date) === toValue(today), 'bg-blue-50 font-semibold text-blue-500': toValue(date) === value, }" @click="() => selectDate(date)" > {{ date.getDate() }} </div> </div> </div> </div> <div class="mt-1 flex w-full justify-end"> <div class="cursor-pointer rounded px-2 py-1 hover:bg-gray-100" @click="selectDate('')"> Clear </div> </div> </div> </template> <script> export default { name: 'DatePicker', props: ['value', 'placeholder', 'readonly', 'inputClass'], emits: ['change'], data() { return { currentYear: null, currentMonth: null, } }, created() { this.selectCurrentMonthYear() }, computed: { today() { return this.getDate() }, datesAsWeeks() { let datesAsWeeks = [] let dates = this.dates.slice() while (dates.length) { let week = dates.splice(0, 7) datesAsWeeks.push(week) } return datesAsWeeks }, dates() { if (!(this.currentYear && this.currentMonth)) { return [] } let monthIndex = this.currentMonth - 1 let year = this.currentYear let firstDayOfMonth = this.getDate(year, monthIndex, 1) let lastDayOfMonth = this.getDate(year, monthIndex + 1, 0) let leftPaddingCount = firstDayOfMonth.getDay() let rightPaddingCount = 6 - lastDayOfMonth.getDay() let leftPadding = this.getDatesAfter(firstDayOfMonth, -leftPaddingCount) let rightPadding = this.getDatesAfter(lastDayOfMonth, rightPaddingCount) let daysInMonth = this.getDaysInMonth(monthIndex, year) let datesInMonth = this.getDatesAfter(firstDayOfMonth, daysInMonth - 1) let dates = [...leftPadding, firstDayOfMonth, ...datesInMonth, ...rightPadding] if (dates.length < 42) { const finalPadding = this.getDatesAfter(dates.at(-1), 42 - dates.length) dates = dates.concat(...finalPadding) } return dates }, formatMonth() { let date = this.getDate(this.currentYear, this.currentMonth - 1, 1) return date.toLocaleString('en-US', { month: 'short', year: 'numeric', }) }, }, methods: { selectDate(date) { this.$emit('change', this.toValue(date)) }, selectCurrentMonthYear() { let date = this.value ? this.getDate(this.value) : this.getDate() if (date === 'Invalid Date') { date = this.getDate() } this.currentYear = date.getFullYear() this.currentMonth = date.getMonth() + 1 }, prevMonth() { this.changeMonth(-1) }, nextMonth() { this.changeMonth(1) }, changeMonth(adder) { this.currentMonth = this.currentMonth + adder if (this.currentMonth < 1) { this.currentMonth = 12 this.currentYear = this.currentYear - 1 } if (this.currentMonth > 12) { this.currentMonth = 1 this.currentYear = this.currentYear + 1 } }, getDatesAfter(date, count) { let incrementer = 1 if (count < 0) { incrementer = -1 count = Math.abs(count) } let dates = [] while (count) { date = this.getDate( date.getFullYear(), date.getMonth(), date.getDate() + incrementer ) dates.push(date) count-- } if (incrementer === -1) { return dates.reverse() } return dates }, getDaysInMonth(monthIndex, year) { let daysInMonthMap = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] let daysInMonth = daysInMonthMap[monthIndex] if (monthIndex === 1 && this.isLeapYear(year)) { return 29 } return daysInMonth }, isLeapYear(year) { if (year % 400 === 0) return true if (year % 100 === 0) return false if (year % 4 === 0) return true return false }, toValue(date) { if (!date) { return '' } // toISOString is buggy and reduces the day by one // this is because it considers the UTC timestamp // in order to circumvent that we need to use luxon/moment // but that refactor could take some time, so fixing the time difference // as suggested in this answer. // https://stackoverflow.com/a/16084846/3541205 date.setHours(0, -date.getTimezoneOffset(), 0, 0) return date.toISOString().slice(0, 10) }, getDate(...args) { let d = new Date(...args) return d }, }, } </script>
2302_79757062/insights
frontend/src/components/Controls/DatePickerFlat.vue
Vue
agpl-3.0
5,696
<template> <Popover @open="selectCurrentMonthYear" class="flex w-full [&>div:first-child]:w-full"> <template #target="{ togglePopover }"> <input readonly type="text" :placeholder="placeholder" :value="formatter ? formatDates(value) : value" @focus="!readonly ? togglePopover() : null" :class="[ 'form-input block h-7 w-full cursor-pointer select-none rounded border-gray-400 text-sm placeholder-gray-500 ', inputClass, ]" /> </template> <template #body="{ togglePopover }"> <div class="my-2 w-[16rem] select-none space-y-3 rounded border border-gray-50 bg-white p-3 text-base shadow" > <div class="flex items-center text-gray-700"> <div class="flex h-6 w-6 cursor-pointer items-center justify-center rounded hover:bg-gray-100" > <FeatherIcon @click="prevMonth" name="chevron-left" class="h-5 w-5" /> </div> <div class="flex-1 text-center text-lg font-medium text-blue-500"> {{ formatMonth }} </div> <div class="flex h-6 w-6 cursor-pointer items-center justify-center rounded hover:bg-gray-100" > <FeatherIcon @click="nextMonth" name="chevron-right" class="h-5 w-5" /> </div> </div> <div class="flex space-x-2"> <Input type="text" v-model="fromDate"></Input> <Input type="text" v-model="toDate"></Input> </div> <div class="mt-2 flex flex-col items-center justify-center text-base"> <div class="flex w-full items-center justify-center space-x-1 text-gray-600"> <div class="flex h-[30px] w-[30px] items-center justify-center text-center" v-for="(d, i) in ['S', 'M', 'T', 'W', 'T', 'F', 'S']" :key="i" > {{ d }} </div> </div> <div v-for="(week, i) in datesAsWeeks" :key="i"> <div class="flex w-full items-center"> <div v-for="date in week" :key="toValue(date)" class="flex h-[30px] w-[30px] cursor-pointer items-center justify-center hover:bg-blue-50 hover:text-blue-500" :class="{ 'text-gray-600': date.getMonth() !== currentMonth - 1, 'text-blue-500': toValue(date) === toValue(today), 'bg-blue-50 text-blue-500': isInRange(date), 'rounded-l-md bg-blue-100': fromDate && toValue(date) === toValue(fromDate), 'rounded-r-md bg-blue-100': toDate && toValue(date) === toValue(toDate), }" @click="() => handleDateClick(date)" > {{ date.getDate() }} </div> </div> </div> </div> <div class="mt-1 flex w-full justify-end space-x-2"> <Button @click="() => clearDates()" :disabled="!value"> Clear </Button> <Button @click="() => selectDates() | togglePopover()" :disabled="!fromDate || !toDate" variant="solid" > Apply </Button> </div> </div> </template> </Popover> </template> <script> export default { name: 'DateRangePicker', props: ['value', 'placeholder', 'formatter', 'readonly', 'inputClass'], emits: ['change'], data() { const fromDate = this.value ? this.value.split(',')[0] : '' const toDate = this.value ? this.value.split(',')[1] : '' return { currentYear: null, currentMonth: null, fromDate, toDate, } }, created() { this.selectCurrentMonthYear() }, computed: { today() { return this.getDate() }, datesAsWeeks() { let datesAsWeeks = [] let dates = this.dates.slice() while (dates.length) { let week = dates.splice(0, 7) datesAsWeeks.push(week) } return datesAsWeeks }, dates() { if (!(this.currentYear && this.currentMonth)) { return [] } let monthIndex = this.currentMonth - 1 let year = this.currentYear let firstDayOfMonth = this.getDate(year, monthIndex, 1) let lastDayOfMonth = this.getDate(year, monthIndex + 1, 0) let leftPaddingCount = firstDayOfMonth.getDay() let rightPaddingCount = 6 - lastDayOfMonth.getDay() let leftPadding = this.getDatesAfter(firstDayOfMonth, -leftPaddingCount) let rightPadding = this.getDatesAfter(lastDayOfMonth, rightPaddingCount) let daysInMonth = this.getDaysInMonth(monthIndex, year) let datesInMonth = this.getDatesAfter(firstDayOfMonth, daysInMonth - 1) let dates = [...leftPadding, firstDayOfMonth, ...datesInMonth, ...rightPadding] if (dates.length < 42) { const finalPadding = this.getDatesAfter(dates.at(-1), 42 - dates.length) dates = dates.concat(...finalPadding) } return dates }, formatMonth() { let date = this.getDate(this.currentYear, this.currentMonth - 1, 1) return date.toLocaleString('en-US', { month: 'short', year: 'numeric', }) }, }, methods: { handleDateClick(date) { if (this.fromDate && this.toDate) { this.fromDate = this.toValue(date) this.toDate = '' } else if (this.fromDate && !this.toDate) { this.toDate = this.toValue(date) } else { this.fromDate = this.toValue(date) } this.swapDatesIfNecessary() }, selectDates() { if (!this.fromDate && !this.toDate) { return this.$emit('change', '') } this.$emit('change', `${this.fromDate},${this.toDate}`) }, swapDatesIfNecessary() { if (!this.fromDate || !this.toDate) { return } // if fromDate is greater than toDate, swap them let fromDate = this.getDate(this.fromDate) let toDate = this.getDate(this.toDate) if (fromDate > toDate) { let temp = fromDate fromDate = toDate toDate = temp } this.fromDate = this.toValue(fromDate) this.toDate = this.toValue(toDate) }, selectCurrentMonthYear() { let date = this.toDate ? this.getDate(this.toDate) : this.today this.currentYear = date.getFullYear() this.currentMonth = date.getMonth() + 1 }, prevMonth() { this.changeMonth(-1) }, nextMonth() { this.changeMonth(1) }, changeMonth(adder) { this.currentMonth = this.currentMonth + adder if (this.currentMonth < 1) { this.currentMonth = 12 this.currentYear = this.currentYear - 1 } if (this.currentMonth > 12) { this.currentMonth = 1 this.currentYear = this.currentYear + 1 } }, getDatesAfter(date, count) { let incrementer = 1 if (count < 0) { incrementer = -1 count = Math.abs(count) } let dates = [] while (count) { date = this.getDate( date.getFullYear(), date.getMonth(), date.getDate() + incrementer ) dates.push(date) count-- } if (incrementer === -1) { return dates.reverse() } return dates }, getDaysInMonth(monthIndex, year) { let daysInMonthMap = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] let daysInMonth = daysInMonthMap[monthIndex] if (monthIndex === 1 && this.isLeapYear(year)) { return 29 } return daysInMonth }, isLeapYear(year) { if (year % 400 === 0) return true if (year % 100 === 0) return false if (year % 4 === 0) return true return false }, toValue(date) { if (!date) { return '' } if (typeof date === 'string') { return date } // toISOString is buggy and reduces the day by one // this is because it considers the UTC timestamp // in order to circumvent that we need to use luxon/moment // but that refactor could take some time, so fixing the time difference // as suggested in this answer. // https://stackoverflow.com/a/16084846/3541205 date.setHours(0, -date.getTimezoneOffset(), 0, 0) return date.toISOString().slice(0, 10) }, getDate(...args) { let d = new Date(...args) return d }, isInRange(date) { if (!this.fromDate || !this.toDate) { return false } return date >= this.getDate(this.fromDate) && date <= this.getDate(this.toDate) }, formatDates(value) { if (!value) { return '' } const values = value.split(',') return this.formatter(values[0]) + ' to ' + this.formatter(values[1]) }, clearDates() { this.fromDate = '' this.toDate = '' this.selectDates() }, }, } </script>
2302_79757062/insights
frontend/src/components/Controls/DateRangePicker.vue
Vue
agpl-3.0
8,007