diff --git a/pom.xml b/pom.xml index ec0fb6405..439f56046 100644 --- a/pom.xml +++ b/pom.xml @@ -17,7 +17,7 @@ yudao-module-system yudao-module-infra yudao-module-pay - + yudao-module-bpm @@ -39,7 +39,7 @@ 3.8.1 1.18.24 - 2.7.7 + 2.7.8 1.5.3.Final UTF-8 diff --git a/sql/mysql/ruoyi-vue-pro.sql b/sql/mysql/ruoyi-vue-pro.sql index 0b5d4e6b3..93a49a6a8 100644 --- a/sql/mysql/ruoyi-vue-pro.sql +++ b/sql/mysql/ruoyi-vue-pro.sql @@ -1895,76 +1895,76 @@ INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_i INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (1267, '客户端删除', 'system:oauth2-client:delete', 3, 4, 1263, '', '', '', 0, b'1', b'1', '', '2022-05-10 16:26:33', '1', '2022-05-11 00:31:33', b'0'); INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (1281, '报表管理', '', 1, 40, 0, '/visualization', 'chart', NULL, 0, b'1', b'1', '1', '2022-07-10 20:22:15', '1', '2022-12-10 16:33:13', b'0'); INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (1282, '报表设计器', '', 2, 1, 1281, 'jimu-report', 'example', 'visualization/jmreport/index', 0, b'1', b'1', '1', '2022-07-10 20:26:36', '1', '2022-07-29 12:48:05', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2000, '商品中心', '', 1, 60, 0, '/product', 'merchant', NULL, 0, b'1', b'1', '', '2022-07-29 15:53:53', '1', '2022-07-30 22:26:19', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2002, '商品分类', '', 2, 2, 2000, 'category', 'dict', 'mall/product/category/index', 0, b'1', b'1', '', '2022-07-29 15:53:53', '1', '2022-07-30 22:23:37', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2003, '分类查询', 'product:category:query', 3, 1, 2002, '', '', '', 0, b'1', b'1', '', '2022-07-29 15:53:53', '', '2022-07-29 15:53:53', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2004, '分类创建', 'product:category:create', 3, 2, 2002, '', '', '', 0, b'1', b'1', '', '2022-07-29 15:53:53', '', '2022-07-29 15:53:53', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2005, '分类更新', 'product:category:update', 3, 3, 2002, '', '', '', 0, b'1', b'1', '', '2022-07-29 15:53:53', '', '2022-07-29 15:53:53', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2006, '分类删除', 'product:category:delete', 3, 4, 2002, '', '', '', 0, b'1', b'1', '', '2022-07-29 15:53:53', '', '2022-07-29 15:53:53', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2008, '商品品牌', '', 2, 3, 2000, 'brand', 'dashboard', 'mall/product/brand/index', 0, b'1', b'1', '', '2022-07-30 13:52:44', '1', '2022-10-24 22:29:30', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2009, '品牌查询', 'product:brand:query', 3, 1, 2008, '', '', '', 0, b'1', b'1', '', '2022-07-30 13:52:44', '', '2022-07-30 13:52:44', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2010, '品牌创建', 'product:brand:create', 3, 2, 2008, '', '', '', 0, b'1', b'1', '', '2022-07-30 13:52:44', '', '2022-07-30 13:52:44', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2011, '品牌更新', 'product:brand:update', 3, 3, 2008, '', '', '', 0, b'1', b'1', '', '2022-07-30 13:52:44', '', '2022-07-30 13:52:44', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2012, '品牌删除', 'product:brand:delete', 3, 4, 2008, '', '', '', 0, b'1', b'1', '', '2022-07-30 13:52:44', '', '2022-07-30 13:52:44', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2014, '商品列表', '', 2, 1, 2000, 'spu', 'list', 'mall/product/spu/index', 0, b'1', b'1', '', '2022-07-30 14:22:58', '1', '2022-10-24 22:29:25', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2015, '商品查询', 'product:spu:query', 3, 1, 2014, '', '', '', 0, b'1', b'1', '', '2022-07-30 14:22:58', '', '2022-07-30 14:22:58', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2016, '商品创建', 'product:spu:create', 3, 2, 2014, '', '', '', 0, b'1', b'1', '', '2022-07-30 14:22:58', '', '2022-07-30 14:22:58', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2017, '商品更新', 'product:spu:update', 3, 3, 2014, '', '', '', 0, b'1', b'1', '', '2022-07-30 14:22:58', '', '2022-07-30 14:22:58', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2018, '商品删除', 'product:spu:delete', 3, 4, 2014, '', '', '', 0, b'1', b'1', '', '2022-07-30 14:22:58', '', '2022-07-30 14:22:58', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2019, '商品属性', '', 2, 3, 2000, 'property', 'eye', 'mall/product/property/index', 0, b'1', b'1', '', '2022-08-01 14:55:35', '1', '2022-12-12 20:58:06', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2020, '规格查询', 'product:property:query', 3, 1, 2019, '', '', '', 0, b'1', b'1', '', '2022-08-01 14:55:35', '', '2022-12-12 20:26:24', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2021, '规格创建', 'product:property:create', 3, 2, 2019, '', '', '', 0, b'1', b'1', '', '2022-08-01 14:55:35', '', '2022-12-12 20:26:30', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2022, '规格更新', 'product:property:update', 3, 3, 2019, '', '', '', 0, b'1', b'1', '', '2022-08-01 14:55:35', '', '2022-12-12 20:26:33', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2023, '规格删除', 'product:property:delete', 3, 4, 2019, '', '', '', 0, b'1', b'1', '', '2022-08-01 14:55:35', '', '2022-12-12 20:26:37', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2025, 'Banner管理', '', 2, 100, 2000, 'banner', '', 'mall/market/banner/index', 0, b'1', b'1', '', '2022-08-01 14:56:14', '1', '2022-10-24 22:29:39', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2026, 'Banner查询', 'market:banner:query', 3, 1, 2025, '', '', '', 0, b'1', b'1', '', '2022-08-01 14:56:14', '', '2022-08-01 14:56:14', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2027, 'Banner创建', 'market:banner:create', 3, 2, 2025, '', '', '', 0, b'1', b'1', '', '2022-08-01 14:56:14', '', '2022-08-01 14:56:14', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2028, 'Banner更新', 'market:banner:update', 3, 3, 2025, '', '', '', 0, b'1', b'1', '', '2022-08-01 14:56:14', '', '2022-08-01 14:56:14', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2029, 'Banner删除', 'market:banner:delete', 3, 4, 2025, '', '', '', 0, b'1', b'1', '', '2022-08-01 14:56:14', '', '2022-08-01 14:56:14', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2030, '营销中心', '', 1, 70, 0, '/promotion', 'rate', NULL, 0, b'1', b'1', '1', '2022-10-31 21:25:09', '1', '2022-10-31 21:25:09', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2032, '优惠劵', '', 2, 2, 2030, 'coupon-template', 'textarea', 'mall/promotion/couponTemplate/index', 0, b'1', b'1', '', '2022-10-31 22:27:14', '1', '2022-11-05 12:27:34', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2033, '优惠劵模板查询', 'promotion:coupon-template:query', 3, 1, 2032, '', '', '', 0, b'1', b'1', '', '2022-10-31 22:27:14', '', '2022-10-31 22:27:14', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2034, '优惠劵模板创建', 'promotion:coupon-template:create', 3, 2, 2032, '', '', '', 0, b'1', b'1', '', '2022-10-31 22:27:14', '', '2022-10-31 22:27:14', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2035, '优惠劵模板更新', 'promotion:coupon-template:update', 3, 3, 2032, '', '', '', 0, b'1', b'1', '', '2022-10-31 22:27:14', '', '2022-10-31 22:27:14', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2036, '优惠劵模板删除', 'promotion:coupon-template:delete', 3, 4, 2032, '', '', '', 0, b'1', b'1', '', '2022-10-31 22:27:14', '', '2022-10-31 22:27:14', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2038, '会员优惠劵', '', 2, 2, 2030, 'coupon', '', 'mall/promotion/coupon/index', 0, b'0', b'1', '', '2022-11-03 23:21:31', '1', '2022-11-05 12:27:45', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2039, '优惠劵查询', 'promotion:coupon:query', 3, 1, 2038, '', '', '', 0, b'1', b'1', '', '2022-11-03 23:21:31', '', '2022-11-03 23:21:31', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2040, '优惠劵删除', 'promotion:coupon:delete', 3, 4, 2038, '', '', '', 0, b'1', b'1', '', '2022-11-03 23:21:31', '', '2022-11-03 23:21:31', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2041, '满减送活动', '', 2, 10, 2030, 'reward-activity', 'radio', 'mall/promotion/rewardActivity/index', 0, b'1', b'1', '', '2022-11-04 23:47:49', '1', '2022-11-05 12:27:56', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2042, '满减送活动查询', 'promotion:reward-activity:query', 3, 1, 2041, '', '', '', 0, b'1', b'1', '', '2022-11-04 23:47:49', '', '2022-11-04 23:47:49', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2043, '满减送活动创建', 'promotion:reward-activity:create', 3, 2, 2041, '', '', '', 0, b'1', b'1', '', '2022-11-04 23:47:49', '', '2022-11-04 23:47:49', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2044, '满减送活动更新', 'promotion:reward-activity:update', 3, 3, 2041, '', '', '', 0, b'1', b'1', '', '2022-11-04 23:47:50', '', '2022-11-04 23:47:50', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2045, '满减送活动删除', 'promotion:reward-activity:delete', 3, 4, 2041, '', '', '', 0, b'1', b'1', '', '2022-11-04 23:47:50', '', '2022-11-04 23:47:50', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2046, '满减送活动关闭', 'promotion:reward-activity:close', 3, 5, 2041, '', '', '', 0, b'1', b'1', '1', '2022-11-05 10:42:53', '1', '2022-11-05 10:42:53', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2047, '限时折扣活动', '', 2, 7, 2030, 'discount-activity', 'time', 'mall/promotion/discountActivity/index', 0, b'1', b'1', '', '2022-11-05 17:12:15', '1', '2022-11-29 22:14:56', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2048, '限时折扣活动查询', 'promotion:discount-activity:query', 3, 1, 2047, '', '', '', 0, b'1', b'1', '', '2022-11-05 17:12:15', '', '2022-11-05 17:12:15', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2049, '限时折扣活动创建', 'promotion:discount-activity:create', 3, 2, 2047, '', '', '', 0, b'1', b'1', '', '2022-11-05 17:12:15', '', '2022-11-05 17:12:15', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2050, '限时折扣活动更新', 'promotion:discount-activity:update', 3, 3, 2047, '', '', '', 0, b'1', b'1', '', '2022-11-05 17:12:16', '', '2022-11-05 17:12:16', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2051, '限时折扣活动删除', 'promotion:discount-activity:delete', 3, 4, 2047, '', '', '', 0, b'1', b'1', '', '2022-11-05 17:12:16', '', '2022-11-05 17:12:16', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2052, '限时折扣活动关闭', 'promotion:discount-activity:close', 3, 5, 2047, '', '', '', 0, b'1', b'1', '', '2022-11-05 17:12:16', '', '2022-11-05 17:12:16', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2059, '秒杀活动管理', '', 2, 0, 2030, 'seckill-activity', 'time-range', 'mall/promotion/seckill/seckillActivity/index', 0, b'1', b'1', '', '2022-11-06 22:24:49', '1', '2022-11-29 22:24:39', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2060, '秒杀活动查询', 'promotion:seckill-activity:query', 3, 1, 2059, '', '', '', 0, b'1', b'1', '', '2022-11-06 22:24:49', '', '2022-11-06 22:24:49', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2061, '秒杀活动创建', 'promotion:seckill-activity:create', 3, 2, 2059, '', '', '', 0, b'1', b'1', '', '2022-11-06 22:24:49', '', '2022-11-06 22:24:49', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2062, '秒杀活动更新', 'promotion:seckill-activity:update', 3, 3, 2059, '', '', '', 0, b'1', b'1', '', '2022-11-06 22:24:49', '', '2022-11-06 22:24:49', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2063, '秒杀活动删除', 'promotion:seckill-activity:delete', 3, 4, 2059, '', '', '', 0, b'1', b'1', '', '2022-11-06 22:24:49', '', '2022-11-06 22:24:49', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2064, '秒杀活动导出', 'promotion:seckill-activity:export', 3, 5, 2059, '', '', '', 0, b'1', b'1', '', '2022-11-06 22:24:49', '', '2022-11-06 22:24:49', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2066, '秒杀时段管理', '', 2, 0, 2030, 'seckill-time', '', 'mall/promotion/seckill/seckillTime/index', 0, b'0', b'1', '', '2022-11-15 19:46:50', '1', '2022-11-29 22:09:03', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2067, '秒杀时段查询', 'promotion:seckill-time:query', 3, 1, 2066, '', '', '', 0, b'1', b'1', '', '2022-11-15 19:46:51', '', '2022-11-15 19:46:51', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2068, '秒杀时段创建', 'promotion:seckill-time:create', 3, 2, 2066, '', '', '', 0, b'1', b'1', '', '2022-11-15 19:46:51', '', '2022-11-15 19:46:51', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2069, '秒杀时段更新', 'promotion:seckill-time:update', 3, 3, 2066, '', '', '', 0, b'1', b'1', '', '2022-11-15 19:46:51', '', '2022-11-15 19:46:51', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2070, '秒杀时段删除', 'promotion:seckill-time:delete', 3, 4, 2066, '', '', '', 0, b'1', b'1', '', '2022-11-15 19:46:51', '', '2022-11-15 19:46:51', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2071, '秒杀时段导出', 'promotion:seckill-time:export', 3, 5, 2066, '', '', '', 0, b'1', b'1', '', '2022-11-15 19:46:51', '', '2022-11-15 19:46:51', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2072, '订单中心', '', 1, 65, 0, '/trade', 'order', NULL, 0, b'1', b'1', '1', '2022-11-19 18:57:19', '1', '2022-12-10 16:32:57', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2073, '售后退款', '', 2, 1, 2072, 'trade/after-sale', 'education', 'mall/trade/afterSale/index', 0, b'1', b'1', '', '2022-11-19 20:15:32', '1', '2022-12-10 21:11:02', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2074, '售后查询', 'trade:after-sale:query', 3, 1, 2073, '', '', '', 0, b'1', b'1', '', '2022-11-19 20:15:33', '1', '2022-12-10 21:04:29', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2075, '秒杀活动关闭', 'promotion:sekill-activity:close', 3, 6, 2059, '', '', '', 0, b'1', b'1', '1', '2022-11-28 20:20:15', '1', '2022-11-28 20:20:15', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2076, '订单列表', '', 2, 0, 2072, 'trade/order', 'list', 'mall/trade/order/index', 0, b'1', b'1', '1', '2022-12-10 21:05:44', '1', '2022-12-10 21:08:44', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2077, '物流公司管理管理', '', 2, 0, 2072, 'express-company', '', 'mall/trade/expressCompany/index', 0, b'1', b'1', '', '2022-12-20 23:27:55', '1', '2022-12-20 23:36:20', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2078, '物流公司管理查询', 'trade:express-company:query', 3, 1, 2077, '', '', '', 0, b'1', b'1', '', '2022-12-20 23:27:55', '', '2022-12-20 23:27:55', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2079, '物流公司管理创建', 'trade:express-company:create', 3, 2, 2077, '', '', '', 0, b'1', b'1', '', '2022-12-20 23:27:55', '', '2022-12-20 23:27:55', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2080, '物流公司管理更新', 'trade:express-company:update', 3, 3, 2077, '', '', '', 0, b'1', b'1', '', '2022-12-20 23:27:55', '', '2022-12-20 23:27:55', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2081, '物流公司管理删除', 'trade:express-company:delete', 3, 4, 2077, '', '', '', 0, b'1', b'1', '', '2022-12-20 23:27:55', '', '2022-12-20 23:27:55', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2082, '物流公司管理导出', 'trade:express-company:export', 3, 5, 2077, '', '', '', 0, b'1', b'1', '', '2022-12-20 23:27:55', '', '2022-12-20 23:27:55', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2000, '商品中心', '', 1, 60, 0, '/product', 'merchant', NULL, 0, b'1', b'1', '', '2022-07-29 15:53:53', '1', '2022-07-30 22:26:19', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2002, '商品分类', '', 2, 2, 2000, 'category', 'dict', 'mall/product/category/index', 0, b'1', b'1', '', '2022-07-29 15:53:53', '1', '2022-07-30 22:23:37', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2003, '分类查询', 'product:category:query', 3, 1, 2002, '', '', '', 0, b'1', b'1', '', '2022-07-29 15:53:53', '', '2022-07-29 15:53:53', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2004, '分类创建', 'product:category:create', 3, 2, 2002, '', '', '', 0, b'1', b'1', '', '2022-07-29 15:53:53', '', '2022-07-29 15:53:53', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2005, '分类更新', 'product:category:update', 3, 3, 2002, '', '', '', 0, b'1', b'1', '', '2022-07-29 15:53:53', '', '2022-07-29 15:53:53', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2006, '分类删除', 'product:category:delete', 3, 4, 2002, '', '', '', 0, b'1', b'1', '', '2022-07-29 15:53:53', '', '2022-07-29 15:53:53', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2008, '商品品牌', '', 2, 3, 2000, 'brand', 'dashboard', 'mall/product/brand/index', 0, b'1', b'1', '', '2022-07-30 13:52:44', '1', '2022-10-24 22:29:30', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2009, '品牌查询', 'product:brand:query', 3, 1, 2008, '', '', '', 0, b'1', b'1', '', '2022-07-30 13:52:44', '', '2022-07-30 13:52:44', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2010, '品牌创建', 'product:brand:create', 3, 2, 2008, '', '', '', 0, b'1', b'1', '', '2022-07-30 13:52:44', '', '2022-07-30 13:52:44', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2011, '品牌更新', 'product:brand:update', 3, 3, 2008, '', '', '', 0, b'1', b'1', '', '2022-07-30 13:52:44', '', '2022-07-30 13:52:44', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2012, '品牌删除', 'product:brand:delete', 3, 4, 2008, '', '', '', 0, b'1', b'1', '', '2022-07-30 13:52:44', '', '2022-07-30 13:52:44', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2014, '商品列表', '', 2, 1, 2000, 'spu', 'list', 'mall/product/spu/index', 0, b'1', b'1', '', '2022-07-30 14:22:58', '1', '2022-10-24 22:29:25', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2015, '商品查询', 'product:spu:query', 3, 1, 2014, '', '', '', 0, b'1', b'1', '', '2022-07-30 14:22:58', '', '2022-07-30 14:22:58', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2016, '商品创建', 'product:spu:create', 3, 2, 2014, '', '', '', 0, b'1', b'1', '', '2022-07-30 14:22:58', '', '2022-07-30 14:22:58', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2017, '商品更新', 'product:spu:update', 3, 3, 2014, '', '', '', 0, b'1', b'1', '', '2022-07-30 14:22:58', '', '2022-07-30 14:22:58', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2018, '商品删除', 'product:spu:delete', 3, 4, 2014, '', '', '', 0, b'1', b'1', '', '2022-07-30 14:22:58', '', '2022-07-30 14:22:58', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2019, '商品属性', '', 2, 3, 2000, 'property', 'eye', 'mall/product/property/index', 0, b'1', b'1', '', '2022-08-01 14:55:35', '1', '2022-12-12 20:58:06', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2020, '规格查询', 'product:property:query', 3, 1, 2019, '', '', '', 0, b'1', b'1', '', '2022-08-01 14:55:35', '', '2022-12-12 20:26:24', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2021, '规格创建', 'product:property:create', 3, 2, 2019, '', '', '', 0, b'1', b'1', '', '2022-08-01 14:55:35', '', '2022-12-12 20:26:30', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2022, '规格更新', 'product:property:update', 3, 3, 2019, '', '', '', 0, b'1', b'1', '', '2022-08-01 14:55:35', '', '2022-12-12 20:26:33', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2023, '规格删除', 'product:property:delete', 3, 4, 2019, '', '', '', 0, b'1', b'1', '', '2022-08-01 14:55:35', '', '2022-12-12 20:26:37', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2025, 'Banner管理', '', 2, 100, 2000, 'banner', '', 'mall/market/banner/index', 0, b'1', b'1', '', '2022-08-01 14:56:14', '1', '2022-10-24 22:29:39', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2026, 'Banner查询', 'market:banner:query', 3, 1, 2025, '', '', '', 0, b'1', b'1', '', '2022-08-01 14:56:14', '', '2022-08-01 14:56:14', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2027, 'Banner创建', 'market:banner:create', 3, 2, 2025, '', '', '', 0, b'1', b'1', '', '2022-08-01 14:56:14', '', '2022-08-01 14:56:14', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2028, 'Banner更新', 'market:banner:update', 3, 3, 2025, '', '', '', 0, b'1', b'1', '', '2022-08-01 14:56:14', '', '2022-08-01 14:56:14', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2029, 'Banner删除', 'market:banner:delete', 3, 4, 2025, '', '', '', 0, b'1', b'1', '', '2022-08-01 14:56:14', '', '2022-08-01 14:56:14', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2030, '营销中心', '', 1, 70, 0, '/promotion', 'rate', NULL, 0, b'1', b'1', '1', '2022-10-31 21:25:09', '1', '2022-10-31 21:25:09', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2032, '优惠劵', '', 2, 2, 2030, 'coupon-template', 'textarea', 'mall/promotion/couponTemplate/index', 0, b'1', b'1', '', '2022-10-31 22:27:14', '1', '2022-11-05 12:27:34', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2033, '优惠劵模板查询', 'promotion:coupon-template:query', 3, 1, 2032, '', '', '', 0, b'1', b'1', '', '2022-10-31 22:27:14', '', '2022-10-31 22:27:14', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2034, '优惠劵模板创建', 'promotion:coupon-template:create', 3, 2, 2032, '', '', '', 0, b'1', b'1', '', '2022-10-31 22:27:14', '', '2022-10-31 22:27:14', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2035, '优惠劵模板更新', 'promotion:coupon-template:update', 3, 3, 2032, '', '', '', 0, b'1', b'1', '', '2022-10-31 22:27:14', '', '2022-10-31 22:27:14', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2036, '优惠劵模板删除', 'promotion:coupon-template:delete', 3, 4, 2032, '', '', '', 0, b'1', b'1', '', '2022-10-31 22:27:14', '', '2022-10-31 22:27:14', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2038, '会员优惠劵', '', 2, 2, 2030, 'coupon', '', 'mall/promotion/coupon/index', 0, b'0', b'1', '', '2022-11-03 23:21:31', '1', '2022-11-05 12:27:45', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2039, '优惠劵查询', 'promotion:coupon:query', 3, 1, 2038, '', '', '', 0, b'1', b'1', '', '2022-11-03 23:21:31', '', '2022-11-03 23:21:31', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2040, '优惠劵删除', 'promotion:coupon:delete', 3, 4, 2038, '', '', '', 0, b'1', b'1', '', '2022-11-03 23:21:31', '', '2022-11-03 23:21:31', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2041, '满减送活动', '', 2, 10, 2030, 'reward-activity', 'radio', 'mall/promotion/rewardActivity/index', 0, b'1', b'1', '', '2022-11-04 23:47:49', '1', '2022-11-05 12:27:56', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2042, '满减送活动查询', 'promotion:reward-activity:query', 3, 1, 2041, '', '', '', 0, b'1', b'1', '', '2022-11-04 23:47:49', '', '2022-11-04 23:47:49', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2043, '满减送活动创建', 'promotion:reward-activity:create', 3, 2, 2041, '', '', '', 0, b'1', b'1', '', '2022-11-04 23:47:49', '', '2022-11-04 23:47:49', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2044, '满减送活动更新', 'promotion:reward-activity:update', 3, 3, 2041, '', '', '', 0, b'1', b'1', '', '2022-11-04 23:47:50', '', '2022-11-04 23:47:50', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2045, '满减送活动删除', 'promotion:reward-activity:delete', 3, 4, 2041, '', '', '', 0, b'1', b'1', '', '2022-11-04 23:47:50', '', '2022-11-04 23:47:50', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2046, '满减送活动关闭', 'promotion:reward-activity:close', 3, 5, 2041, '', '', '', 0, b'1', b'1', '1', '2022-11-05 10:42:53', '1', '2022-11-05 10:42:53', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2047, '限时折扣活动', '', 2, 7, 2030, 'discount-activity', 'time', 'mall/promotion/discountActivity/index', 0, b'1', b'1', '', '2022-11-05 17:12:15', '1', '2022-11-29 22:14:56', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2048, '限时折扣活动查询', 'promotion:discount-activity:query', 3, 1, 2047, '', '', '', 0, b'1', b'1', '', '2022-11-05 17:12:15', '', '2022-11-05 17:12:15', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2049, '限时折扣活动创建', 'promotion:discount-activity:create', 3, 2, 2047, '', '', '', 0, b'1', b'1', '', '2022-11-05 17:12:15', '', '2022-11-05 17:12:15', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2050, '限时折扣活动更新', 'promotion:discount-activity:update', 3, 3, 2047, '', '', '', 0, b'1', b'1', '', '2022-11-05 17:12:16', '', '2022-11-05 17:12:16', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2051, '限时折扣活动删除', 'promotion:discount-activity:delete', 3, 4, 2047, '', '', '', 0, b'1', b'1', '', '2022-11-05 17:12:16', '', '2022-11-05 17:12:16', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2052, '限时折扣活动关闭', 'promotion:discount-activity:close', 3, 5, 2047, '', '', '', 0, b'1', b'1', '', '2022-11-05 17:12:16', '', '2022-11-05 17:12:16', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2059, '秒杀活动管理', '', 2, 0, 2030, 'seckill-activity', 'time-range', 'mall/promotion/seckill/seckillActivity/index', 0, b'1', b'1', '', '2022-11-06 22:24:49', '1', '2022-11-29 22:24:39', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2060, '秒杀活动查询', 'promotion:seckill-activity:query', 3, 1, 2059, '', '', '', 0, b'1', b'1', '', '2022-11-06 22:24:49', '', '2022-11-06 22:24:49', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2061, '秒杀活动创建', 'promotion:seckill-activity:create', 3, 2, 2059, '', '', '', 0, b'1', b'1', '', '2022-11-06 22:24:49', '', '2022-11-06 22:24:49', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2062, '秒杀活动更新', 'promotion:seckill-activity:update', 3, 3, 2059, '', '', '', 0, b'1', b'1', '', '2022-11-06 22:24:49', '', '2022-11-06 22:24:49', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2063, '秒杀活动删除', 'promotion:seckill-activity:delete', 3, 4, 2059, '', '', '', 0, b'1', b'1', '', '2022-11-06 22:24:49', '', '2022-11-06 22:24:49', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2064, '秒杀活动导出', 'promotion:seckill-activity:export', 3, 5, 2059, '', '', '', 0, b'1', b'1', '', '2022-11-06 22:24:49', '', '2022-11-06 22:24:49', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2066, '秒杀时段管理', '', 2, 0, 2030, 'seckill-time', '', 'mall/promotion/seckill/seckillTime/index', 0, b'0', b'1', '', '2022-11-15 19:46:50', '1', '2022-11-29 22:09:03', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2067, '秒杀时段查询', 'promotion:seckill-time:query', 3, 1, 2066, '', '', '', 0, b'1', b'1', '', '2022-11-15 19:46:51', '', '2022-11-15 19:46:51', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2068, '秒杀时段创建', 'promotion:seckill-time:create', 3, 2, 2066, '', '', '', 0, b'1', b'1', '', '2022-11-15 19:46:51', '', '2022-11-15 19:46:51', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2069, '秒杀时段更新', 'promotion:seckill-time:update', 3, 3, 2066, '', '', '', 0, b'1', b'1', '', '2022-11-15 19:46:51', '', '2022-11-15 19:46:51', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2070, '秒杀时段删除', 'promotion:seckill-time:delete', 3, 4, 2066, '', '', '', 0, b'1', b'1', '', '2022-11-15 19:46:51', '', '2022-11-15 19:46:51', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2071, '秒杀时段导出', 'promotion:seckill-time:export', 3, 5, 2066, '', '', '', 0, b'1', b'1', '', '2022-11-15 19:46:51', '', '2022-11-15 19:46:51', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2072, '订单中心', '', 1, 65, 0, '/trade', 'order', NULL, 0, b'1', b'1', '1', '2022-11-19 18:57:19', '1', '2022-12-10 16:32:57', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2073, '售后退款', '', 2, 1, 2072, 'trade/after-sale', 'education', 'mall/trade/afterSale/index', 0, b'1', b'1', '', '2022-11-19 20:15:32', '1', '2022-12-10 21:11:02', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2074, '售后查询', 'trade:after-sale:query', 3, 1, 2073, '', '', '', 0, b'1', b'1', '', '2022-11-19 20:15:33', '1', '2022-12-10 21:04:29', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2075, '秒杀活动关闭', 'promotion:sekill-activity:close', 3, 6, 2059, '', '', '', 0, b'1', b'1', '1', '2022-11-28 20:20:15', '1', '2022-11-28 20:20:15', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2076, '订单列表', '', 2, 0, 2072, 'trade/order', 'list', 'mall/trade/order/index', 0, b'1', b'1', '1', '2022-12-10 21:05:44', '1', '2022-12-10 21:08:44', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2077, '物流公司管理管理', '', 2, 0, 2072, 'express-company', '', 'mall/trade/expressCompany/index', 0, b'1', b'1', '', '2022-12-20 23:27:55', '1', '2022-12-20 23:36:20', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2078, '物流公司管理查询', 'trade:express-company:query', 3, 1, 2077, '', '', '', 0, b'1', b'1', '', '2022-12-20 23:27:55', '', '2022-12-20 23:27:55', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2079, '物流公司管理创建', 'trade:express-company:create', 3, 2, 2077, '', '', '', 0, b'1', b'1', '', '2022-12-20 23:27:55', '', '2022-12-20 23:27:55', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2080, '物流公司管理更新', 'trade:express-company:update', 3, 3, 2077, '', '', '', 0, b'1', b'1', '', '2022-12-20 23:27:55', '', '2022-12-20 23:27:55', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2081, '物流公司管理删除', 'trade:express-company:delete', 3, 4, 2077, '', '', '', 0, b'1', b'1', '', '2022-12-20 23:27:55', '', '2022-12-20 23:27:55', b'0'); +# INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2082, '物流公司管理导出', 'trade:express-company:export', 3, 5, 2077, '', '', '', 0, b'1', b'1', '', '2022-12-20 23:27:55', '', '2022-12-20 23:27:55', b'0'); INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2083, '地区管理', '', 2, 14, 1, 'area', 'row', 'system/area/index', 0, b'1', b'1', '1', '2022-12-23 17:35:05', '1', '2022-12-23 17:35:48', b'0'); INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2084, '公众号管理', '', 1, 100, 0, '/mp', 'wechat', NULL, 0, b'1', b'1', '1', '2023-01-01 20:11:04', '1', '2023-01-15 11:28:57', b'0'); INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2085, '账号管理', 'mp:account:query', 2, 1, 2084, 'account', 'phone', 'mp/account/index', 0, b'1', b'1', '1', '2023-01-01 20:13:31', '1', '2023-01-01 20:14:39', b'0'); @@ -1981,7 +1981,7 @@ INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_i INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2096, '修改标签', 'mp:tag:update', 3, 2, 2093, '', '', '', 0, b'1', b'1', '1', '2023-01-08 11:59:41', '1', '2023-01-08 11:59:41', b'0'); INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2097, '删除标签', 'mp:tag:delete', 3, 3, 2093, '', '', '', 0, b'1', b'1', '1', '2023-01-08 12:00:04', '1', '2023-01-08 12:00:13', b'0'); INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2098, '同步标签', 'mp:tag:sync', 3, 4, 2093, '', '', '', 0, b'1', b'1', '1', '2023-01-08 12:00:29', '1', '2023-01-08 12:00:29', b'0'); -INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2099, '粉丝管理', '', 2, 4, 2084, 'user', 'people', 'mp/user/index', 0, b'1', b'1', '1', '2023-01-08 16:51:20', '1', '2023-01-08 16:56:19', b'0'); +INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2099, '粉丝管理', '', 2, 4, 2084, 'mpuser', 'people', 'mp/mpuser/index', 0, b'1', b'1', '1', '2023-01-08 16:51:20', '1', '2023-01-08 16:56:19', b'0'); INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2100, '查询粉丝', 'mp:user:query', 3, 0, 2099, '', '', '', 0, b'1', b'1', '1', '2023-01-08 17:16:59', '1', '2023-01-08 17:17:23', b'0'); INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2101, '修改粉丝', 'mp:user:update', 3, 1, 2099, '', '', '', 0, b'1', b'1', '1', '2023-01-08 17:17:11', '1', '2023-01-08 17:17:11', b'0'); INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `status`, `visible`, `keep_alive`, `creator`, `create_time`, `updater`, `update_time`, `deleted`) VALUES (2102, '同步粉丝', 'mp:user:sync', 3, 2, 2099, '', '', '', 0, b'1', b'1', '1', '2023-01-08 17:17:40', '1', '2023-01-08 17:17:40', b'0'); @@ -3251,7 +3251,7 @@ CREATE TABLE `system_tenant` ( `package_id` bigint NOT NULL COMMENT '租户套餐编号', `expire_time` datetime NOT NULL COMMENT '过期时间', `account_count` int NOT NULL COMMENT '账号数量', - `creator` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '创建者', + `creator` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT '' COMMENT '创建者', `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `updater` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT '' COMMENT '更新者', `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', @@ -3282,7 +3282,7 @@ CREATE TABLE `system_tenant_package` ( `status` tinyint NOT NULL DEFAULT 0 COMMENT '租户状态(0正常 1停用)', `remark` varchar(256) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT '' COMMENT '备注', `menu_ids` varchar(2048) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '关联的菜单编号', - `creator` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '创建者', + `creator` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT '' COMMENT '创建者', `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `updater` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT '' COMMENT '更新者', `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', diff --git a/sql/postgresql/ruoyi-vue-pro.sql b/sql/postgresql/ruoyi-vue-pro.sql index 7484486c2..c16a51f75 100644 --- a/sql/postgresql/ruoyi-vue-pro.sql +++ b/sql/postgresql/ruoyi-vue-pro.sql @@ -3817,7 +3817,7 @@ CREATE TABLE "system_tenant" ( "package_id" int8 NOT NULL, "expire_time" timestamp(6) NOT NULL, "account_count" int4 NOT NULL, - "creator" varchar(64) COLLATE "pg_catalog"."default" NOT NULL, + "creator" varchar(64) COLLATE "pg_catalog"."default", "create_time" timestamp(6) NOT NULL, "updater" varchar(64) COLLATE "pg_catalog"."default", "update_time" timestamp(6) NOT NULL, @@ -3860,7 +3860,7 @@ CREATE TABLE "system_tenant_package" ( "status" int2 NOT NULL, "remark" varchar(256) COLLATE "pg_catalog"."default", "menu_ids" varchar(2048) COLLATE "pg_catalog"."default" NOT NULL, - "creator" varchar(64) COLLATE "pg_catalog"."default" NOT NULL, + "creator" varchar(64) COLLATE "pg_catalog"."default", "create_time" timestamp(6) NOT NULL, "updater" varchar(64) COLLATE "pg_catalog"."default", "update_time" timestamp(6) NOT NULL, diff --git a/sql/sqlserver/ruoyi-vue-pro.sql b/sql/sqlserver/ruoyi-vue-pro.sql index 386e9bd2e..dd728f2c7 100644 --- a/sql/sqlserver/ruoyi-vue-pro.sql +++ b/sql/sqlserver/ruoyi-vue-pro.sql @@ -10600,7 +10600,7 @@ CREATE TABLE [dbo].[system_tenant] ( [package_id] bigint NOT NULL, [expire_time] datetime2(7) NOT NULL, [account_count] int NOT NULL, - [creator] nvarchar(64) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, + [creator] nvarchar(64) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, [create_time] datetime2(7) NOT NULL, [updater] nvarchar(64) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, [update_time] datetime2(7) NOT NULL, @@ -10761,7 +10761,7 @@ CREATE TABLE [dbo].[system_tenant_package] ( [status] tinyint NOT NULL, [remark] nvarchar(256) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, [menu_ids] nvarchar(2048) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, - [creator] nvarchar(64) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, + [creator] nvarchar(64) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, [create_time] datetime2(7) NOT NULL, [updater] nvarchar(64) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, [update_time] datetime2(7) NOT NULL, diff --git a/yudao-dependencies/pom.xml b/yudao-dependencies/pom.xml index f76d50da8..50e7dc53e 100644 --- a/yudao-dependencies/pom.xml +++ b/yudao-dependencies/pom.xml @@ -16,7 +16,7 @@ 1.7.0-snapshot - 2.7.7 + 2.7.8 1.6.14 4.0.0 @@ -41,12 +41,12 @@ 6.8.0 - 1.0.1 + 1.0.2 1.15.3 1.18.24 1.5.3.Final 5.8.11 - 3.1.5 + 3.2.0 2.3 1.0.5 1.2.83 diff --git a/yudao-example/yudao-sso-demo-by-code/pom.xml b/yudao-example/yudao-sso-demo-by-code/pom.xml index ef83df4ac..f60c21cb6 100644 --- a/yudao-example/yudao-sso-demo-by-code/pom.xml +++ b/yudao-example/yudao-sso-demo-by-code/pom.xml @@ -21,7 +21,7 @@ 8 UTF-8 - 2.7.7 + 2.7.8 diff --git a/yudao-example/yudao-sso-demo-by-password/pom.xml b/yudao-example/yudao-sso-demo-by-password/pom.xml index 391358ee2..0f7f9056a 100644 --- a/yudao-example/yudao-sso-demo-by-password/pom.xml +++ b/yudao-example/yudao-sso-demo-by-password/pom.xml @@ -21,7 +21,7 @@ 8 UTF-8 - 2.7.7 + 2.7.8 diff --git a/yudao-framework/yudao-spring-boot-starter-biz-data-permission/src/main/java/cn/iocoder/yudao/framework/datapermission/core/util/DataPermissionUtils.java b/yudao-framework/yudao-spring-boot-starter-biz-data-permission/src/main/java/cn/iocoder/yudao/framework/datapermission/core/util/DataPermissionUtils.java new file mode 100644 index 000000000..c154bd5f5 --- /dev/null +++ b/yudao-framework/yudao-spring-boot-starter-biz-data-permission/src/main/java/cn/iocoder/yudao/framework/datapermission/core/util/DataPermissionUtils.java @@ -0,0 +1,43 @@ +package cn.iocoder.yudao.framework.datapermission.core.util; + +import cn.iocoder.yudao.framework.datapermission.core.annotation.DataPermission; +import cn.iocoder.yudao.framework.datapermission.core.aop.DataPermissionContextHolder; +import lombok.SneakyThrows; + +/** + * 数据权限 Util + * + * @author 芋道源码 + */ +public class DataPermissionUtils { + + private static DataPermission DATA_PERMISSION_DISABLE; + + @DataPermission(enable = false) + @SneakyThrows + private static DataPermission getDisableDataPermissionDisable() { + if (DATA_PERMISSION_DISABLE == null) { + DATA_PERMISSION_DISABLE = DataPermissionUtils.class + .getDeclaredMethod("getDisableDataPermissionDisable") + .getAnnotation(DataPermission.class); + } + return DATA_PERMISSION_DISABLE; + } + + /** + * 忽略数据权限,执行对应的逻辑 + * + * @param runnable 逻辑 + */ + public static void executeIgnore(Runnable runnable) { + DataPermission dataPermission = getDisableDataPermissionDisable(); + DataPermissionContextHolder.add(dataPermission); + try { + // 执行 runnable + runnable.run(); + } finally { + DataPermissionContextHolder.remove(); + } + } + +} diff --git a/yudao-framework/yudao-spring-boot-starter-biz-data-permission/src/test/java/cn/iocoder/yudao/framework/datapermission/core/util/DataPermissionUtilsTest.java b/yudao-framework/yudao-spring-boot-starter-biz-data-permission/src/test/java/cn/iocoder/yudao/framework/datapermission/core/util/DataPermissionUtilsTest.java new file mode 100644 index 000000000..1cc57c258 --- /dev/null +++ b/yudao-framework/yudao-spring-boot-starter-biz-data-permission/src/test/java/cn/iocoder/yudao/framework/datapermission/core/util/DataPermissionUtilsTest.java @@ -0,0 +1,15 @@ +package cn.iocoder.yudao.framework.datapermission.core.util; + +import cn.iocoder.yudao.framework.datapermission.core.aop.DataPermissionContextHolder; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +public class DataPermissionUtilsTest { + + @Test + public void testExecuteIgnore() { + DataPermissionUtils.executeIgnore(() -> assertFalse(DataPermissionContextHolder.get().enable())); + } + +} diff --git a/yudao-framework/yudao-spring-boot-starter-biz-error-code/src/main/java/cn/iocoder/yudao/framework/errorcode/core/generator/ErrorCodeAutoGeneratorImpl.java b/yudao-framework/yudao-spring-boot-starter-biz-error-code/src/main/java/cn/iocoder/yudao/framework/errorcode/core/generator/ErrorCodeAutoGeneratorImpl.java index a7f6c2835..d670c1829 100644 --- a/yudao-framework/yudao-spring-boot-starter-biz-error-code/src/main/java/cn/iocoder/yudao/framework/errorcode/core/generator/ErrorCodeAutoGeneratorImpl.java +++ b/yudao-framework/yudao-spring-boot-starter-biz-error-code/src/main/java/cn/iocoder/yudao/framework/errorcode/core/generator/ErrorCodeAutoGeneratorImpl.java @@ -49,7 +49,7 @@ public class ErrorCodeAutoGeneratorImpl implements ErrorCodeAutoGenerator { log.info("[execute][解析到错误码数量为 ({}) 个]", autoGenerateDTOs.size()); // 第二步,写入到 system 服务 - errorCodeApi.autoGenerateErrorCodes(autoGenerateDTOs); + errorCodeApi.autoGenerateErrorCodeList(autoGenerateDTOs); log.info("[execute][写入到 system 组件完成]"); } diff --git a/yudao-framework/yudao-spring-boot-starter-biz-tenant/src/main/java/cn/iocoder/yudao/framework/tenant/core/service/TenantFrameworkServiceImpl.java b/yudao-framework/yudao-spring-boot-starter-biz-tenant/src/main/java/cn/iocoder/yudao/framework/tenant/core/service/TenantFrameworkServiceImpl.java index 75d065e1e..f2b7b27a8 100644 --- a/yudao-framework/yudao-spring-boot-starter-biz-tenant/src/main/java/cn/iocoder/yudao/framework/tenant/core/service/TenantFrameworkServiceImpl.java +++ b/yudao-framework/yudao-spring-boot-starter-biz-tenant/src/main/java/cn/iocoder/yudao/framework/tenant/core/service/TenantFrameworkServiceImpl.java @@ -32,7 +32,7 @@ public class TenantFrameworkServiceImpl implements TenantFrameworkService { @Override public List load(Object key) { - return tenantApi.getTenantIds(); + return tenantApi.getTenantIdList(); } }); @@ -47,7 +47,7 @@ public class TenantFrameworkServiceImpl implements TenantFrameworkService { @Override public ServiceException load(Long id) { try { - tenantApi.validTenant(id); + tenantApi.validateTenant(id); return SERVICE_EXCEPTION_NULL; } catch (ServiceException ex) { return ex; diff --git a/yudao-framework/yudao-spring-boot-starter-test/src/main/java/cn/iocoder/yudao/framework/test/core/util/RandomUtils.java b/yudao-framework/yudao-spring-boot-starter-test/src/main/java/cn/iocoder/yudao/framework/test/core/util/RandomUtils.java index 11a810cf1..7f114e5b1 100644 --- a/yudao-framework/yudao-spring-boot-starter-test/src/main/java/cn/iocoder/yudao/framework/test/core/util/RandomUtils.java +++ b/yudao-framework/yudao-spring-boot-starter-test/src/main/java/cn/iocoder/yudao/framework/test/core/util/RandomUtils.java @@ -50,7 +50,7 @@ public class RandomUtils { } // 如果是 type、status 结尾的字段,返回 tinyint 范围 if (StrUtil.endWithAnyIgnoreCase(attributeMetadata.getAttributeName(), - "type", "status", "category", "scope")) { + "type", "status", "category", "scope", "result")) { return RandomUtil.randomInt(0, TINYINT_MAX + 1); } return RandomUtil.randomInt(); diff --git a/yudao-module-bpm/yudao-module-bpm-biz/src/main/java/cn/iocoder/yudao/module/bpm/service/definition/BpmTaskAssignRuleServiceImpl.java b/yudao-module-bpm/yudao-module-bpm-biz/src/main/java/cn/iocoder/yudao/module/bpm/service/definition/BpmTaskAssignRuleServiceImpl.java index 49bfdac4e..508af962d 100644 --- a/yudao-module-bpm/yudao-module-bpm-biz/src/main/java/cn/iocoder/yudao/module/bpm/service/definition/BpmTaskAssignRuleServiceImpl.java +++ b/yudao-module-bpm/yudao-module-bpm-biz/src/main/java/cn/iocoder/yudao/module/bpm/service/definition/BpmTaskAssignRuleServiceImpl.java @@ -213,18 +213,18 @@ public class BpmTaskAssignRuleServiceImpl implements BpmTaskAssignRuleService { private void validTaskAssignRuleOptions(Integer type, Set options) { if (Objects.equals(type, BpmTaskAssignRuleTypeEnum.ROLE.getType())) { - roleApi.validRoles(options); + roleApi.validRoleList(options); } else if (ObjectUtils.equalsAny(type, BpmTaskAssignRuleTypeEnum.DEPT_MEMBER.getType(), BpmTaskAssignRuleTypeEnum.DEPT_LEADER.getType())) { - deptApi.validDepts(options); + deptApi.validateDeptList(options); } else if (Objects.equals(type, BpmTaskAssignRuleTypeEnum.POST.getType())) { - postApi.validPosts(options); + postApi.validPostList(options); } else if (Objects.equals(type, BpmTaskAssignRuleTypeEnum.USER.getType())) { - adminUserApi.validUsers(options); + adminUserApi.validateUserList(options); } else if (Objects.equals(type, BpmTaskAssignRuleTypeEnum.USER_GROUP.getType())) { userGroupService.validUserGroups(options); } else if (Objects.equals(type, BpmTaskAssignRuleTypeEnum.SCRIPT.getType())) { - dictDataApi.validDictDatas(DictTypeConstants.TASK_ASSIGN_SCRIPT, + dictDataApi.validateDictDataList(DictTypeConstants.TASK_ASSIGN_SCRIPT, CollectionUtils.convertSet(options, String::valueOf)); } else { throw new IllegalArgumentException(format("未知的规则类型({})", type)); @@ -288,12 +288,12 @@ public class BpmTaskAssignRuleServiceImpl implements BpmTaskAssignRuleService { } private Set calculateTaskCandidateUsersByDeptMember(BpmTaskAssignRuleDO rule) { - List users = adminUserApi.getUsersByDeptIds(rule.getOptions()); + List users = adminUserApi.getUserListByDeptIds(rule.getOptions()); return convertSet(users, AdminUserRespDTO::getId); } private Set calculateTaskCandidateUsersByDeptLeader(BpmTaskAssignRuleDO rule) { - List depts = deptApi.getDepts(rule.getOptions()); + List depts = deptApi.getDeptList(rule.getOptions()); return convertSet(depts, DeptRespDTO::getLeaderUserId); } diff --git a/yudao-module-bpm/yudao-module-bpm-biz/src/test/java/cn/iocoder/yudao/module/bpm/service/definition/BpmTaskAssignRuleServiceImplTest.java b/yudao-module-bpm/yudao-module-bpm-biz/src/test/java/cn/iocoder/yudao/module/bpm/service/definition/BpmTaskAssignRuleServiceImplTest.java index ff163663d..7c1eb0f84 100644 --- a/yudao-module-bpm/yudao-module-bpm-biz/src/test/java/cn/iocoder/yudao/module/bpm/service/definition/BpmTaskAssignRuleServiceImplTest.java +++ b/yudao-module-bpm/yudao-module-bpm-biz/src/test/java/cn/iocoder/yudao/module/bpm/service/definition/BpmTaskAssignRuleServiceImplTest.java @@ -86,7 +86,7 @@ public class BpmTaskAssignRuleServiceImplTest extends BaseDbUnitTest { // mock 方法 List users = CollectionUtils.convertList(asSet(11L, 22L), id -> new AdminUserRespDTO().setId(id)); - when(adminUserApi.getUsersByDeptIds(eq(rule.getOptions()))).thenReturn(users); + when(adminUserApi.getUserListByDeptIds(eq(rule.getOptions()))).thenReturn(users); mockGetUserMap(asSet(11L, 22L)); // 调用 diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/controller/admin/config/ConfigController.java b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/controller/admin/config/ConfigController.java index 33d77e8e2..e3f704bc0 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/controller/admin/config/ConfigController.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/controller/admin/config/ConfigController.java @@ -1,6 +1,5 @@ package cn.iocoder.yudao.module.infra.controller.admin.config; -import cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil; import cn.iocoder.yudao.framework.common.pojo.CommonResult; import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils; @@ -8,7 +7,6 @@ import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog; import cn.iocoder.yudao.module.infra.controller.admin.config.vo.*; import cn.iocoder.yudao.module.infra.convert.config.ConfigConvert; import cn.iocoder.yudao.module.infra.dal.dataobject.config.ConfigDO; -import cn.iocoder.yudao.module.infra.service.config.ConfigService; import cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.Parameter; @@ -23,6 +21,7 @@ import javax.validation.Valid; import java.io.IOException; import java.util.List; +import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success; import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT; @@ -76,7 +75,7 @@ public class ConfigController { return null; } if (!config.getVisible()) { - throw ServiceExceptionUtil.exception(ErrorCodeConstants.CONFIG_GET_VALUE_ERROR_IF_VISIBLE); + throw exception(ErrorCodeConstants.CONFIG_GET_VALUE_ERROR_IF_VISIBLE); } return success(config.getValue()); } @@ -93,8 +92,8 @@ public class ConfigController { @Operation(summary = "导出参数配置") @PreAuthorize("@ss.hasPermission('infra:config:export')") @OperateLog(type = EXPORT) - public void exportSysConfig(@Valid ConfigExportReqVO reqVO, - HttpServletResponse response) throws IOException { + public void exportConfig(@Valid ConfigExportReqVO reqVO, + HttpServletResponse response) throws IOException { List list = configService.getConfigList(reqVO); // 拼接数据 List datas = ConfigConvert.INSTANCE.convertList(list); diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/dal/dataobject/codegen/CodegenColumnDO.java b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/dal/dataobject/codegen/CodegenColumnDO.java index f1990f3fc..368162214 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/dal/dataobject/codegen/CodegenColumnDO.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/dal/dataobject/codegen/CodegenColumnDO.java @@ -39,27 +39,38 @@ public class CodegenColumnDO extends BaseDO { /** * 字段名 + * + * 关联 {@link TableField#getName()} */ private String columnName; /** * 数据库字段类型 + * * 关联 {@link TableField.MetaInfo#getJdbcType()} */ private String dataType; /** * 字段描述 + * + * 关联 {@link TableField#getComment()} */ private String columnComment; /** * 是否允许为空 + * + * 关联 {@link TableField.MetaInfo#isNullable()} */ private Boolean nullable; /** * 是否主键 + * + * 关联 {@link TableField#isKeyFlag()} */ private Boolean primaryKey; /** * 是否自增 + * + * 关联 {@link TableField#isKeyIdentityFlag()} */ private Boolean autoIncrement; /** @@ -71,12 +82,16 @@ public class CodegenColumnDO extends BaseDO { /** * Java 属性类型 - *

+ * * 例如说 String、Boolean 等等 + * + * 关联 {@link TableField#getColumnType()} */ private String javaType; /** * Java 属性名 + * + * 关联 {@link TableField#getPropertyName()} */ private String javaField; /** diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/dal/dataobject/codegen/CodegenTableDO.java b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/dal/dataobject/codegen/CodegenTableDO.java index b821d210c..4f4a644a7 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/dal/dataobject/codegen/CodegenTableDO.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/dal/dataobject/codegen/CodegenTableDO.java @@ -6,6 +6,7 @@ import cn.iocoder.yudao.module.infra.enums.codegen.CodegenSceneEnum; import cn.iocoder.yudao.module.infra.enums.codegen.CodegenTemplateTypeEnum; import com.baomidou.mybatisplus.annotation.KeySequence; import com.baomidou.mybatisplus.annotation.TableName; +import com.baomidou.mybatisplus.generator.config.po.TableInfo; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; @@ -44,10 +45,14 @@ public class CodegenTableDO extends BaseDO { /** * 表名称 + * + * 关联 {@link TableInfo#getName()} */ private String tableName; /** * 表描述 + * + * 关联 {@link TableInfo#getComment()} */ private String tableComment; /** diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/dal/mysql/job/JobLogMapper.java b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/dal/mysql/job/JobLogMapper.java index fe196df35..c467498bf 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/dal/mysql/job/JobLogMapper.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/dal/mysql/job/JobLogMapper.java @@ -2,7 +2,7 @@ package cn.iocoder.yudao.module.infra.dal.mysql.job; import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX; -import cn.iocoder.yudao.framework.mybatis.core.query.QueryWrapperX; +import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX; import cn.iocoder.yudao.module.infra.controller.admin.job.vo.log.JobLogExportReqVO; import cn.iocoder.yudao.module.infra.controller.admin.job.vo.log.JobLogPageReqVO; import cn.iocoder.yudao.module.infra.dal.dataobject.job.JobLogDO; @@ -19,24 +19,24 @@ import java.util.List; public interface JobLogMapper extends BaseMapperX { default PageResult selectPage(JobLogPageReqVO reqVO) { - return selectPage(reqVO, new QueryWrapperX() - .eqIfPresent("job_id", reqVO.getJobId()) - .likeIfPresent("handler_name", reqVO.getHandlerName()) - .geIfPresent("begin_time", reqVO.getBeginTime()) - .leIfPresent("end_time", reqVO.getEndTime()) - .eqIfPresent("status", reqVO.getStatus()) - .orderByDesc("id") // ID 倒序 + return selectPage(reqVO, new LambdaQueryWrapperX() + .eqIfPresent(JobLogDO::getJobId, reqVO.getJobId()) + .likeIfPresent(JobLogDO::getHandlerName, reqVO.getHandlerName()) + .geIfPresent(JobLogDO::getBeginTime, reqVO.getBeginTime()) + .leIfPresent(JobLogDO::getEndTime, reqVO.getEndTime()) + .eqIfPresent(JobLogDO::getStatus, reqVO.getStatus()) + .orderByDesc(JobLogDO::getId) // ID 倒序 ); } default List selectList(JobLogExportReqVO reqVO) { - return selectList(new QueryWrapperX() - .eqIfPresent("job_id", reqVO.getJobId()) - .likeIfPresent("handler_name", reqVO.getHandlerName()) - .geIfPresent("begin_time", reqVO.getBeginTime()) - .leIfPresent("end_time", reqVO.getEndTime()) - .eqIfPresent("status", reqVO.getStatus()) - .orderByDesc("id") // ID 倒序 + return selectList(new LambdaQueryWrapperX() + .eqIfPresent(JobLogDO::getJobId, reqVO.getJobId()) + .likeIfPresent(JobLogDO::getHandlerName, reqVO.getHandlerName()) + .geIfPresent(JobLogDO::getBeginTime, reqVO.getBeginTime()) + .leIfPresent(JobLogDO::getEndTime, reqVO.getEndTime()) + .eqIfPresent(JobLogDO::getStatus, reqVO.getStatus()) + .orderByDesc(JobLogDO::getId) // ID 倒序 ); } diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/codegen/CodegenServiceImpl.java b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/codegen/CodegenServiceImpl.java index 3b693eb50..e3a352b8b 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/codegen/CodegenServiceImpl.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/codegen/CodegenServiceImpl.java @@ -76,7 +76,7 @@ public class CodegenServiceImpl implements CodegenService { private Long createCodegen0(Long userId, Long dataSourceConfigId, TableInfo tableInfo) { // 校验导入的表和字段非空 - checkTableInfo(tableInfo); + validateTableInfo(tableInfo); // 校验是否已经存在 if (codegenTableMapper.selectByTableNameAndDataSourceConfigId(tableInfo.getName(), dataSourceConfigId) != null) { @@ -100,7 +100,7 @@ public class CodegenServiceImpl implements CodegenService { return table.getId(); } - private void checkTableInfo(TableInfo tableInfo) { + private void validateTableInfo(TableInfo tableInfo) { if (tableInfo == null) { throw exception(CODEGEN_IMPORT_TABLE_NULL); } @@ -149,7 +149,7 @@ public class CodegenServiceImpl implements CodegenService { private void syncCodegen0(Long tableId, TableInfo tableInfo) { // 校验导入的表和字段非空 - checkTableInfo(tableInfo); + validateTableInfo(tableInfo); List tableFields = tableInfo.getFields(); // 构建 CodegenColumnDO 数组,只同步新增的字段 diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/config/ConfigServiceImpl.java b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/config/ConfigServiceImpl.java index 5c354c989..51c912be7 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/config/ConfigServiceImpl.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/config/ConfigServiceImpl.java @@ -9,7 +9,6 @@ import cn.iocoder.yudao.module.infra.controller.admin.config.vo.ConfigUpdateReqV import cn.iocoder.yudao.module.infra.convert.config.ConfigConvert; import cn.iocoder.yudao.module.infra.dal.dataobject.config.ConfigDO; import cn.iocoder.yudao.module.infra.dal.mysql.config.ConfigMapper; -import cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants; import cn.iocoder.yudao.module.infra.enums.config.ConfigTypeEnum; import com.google.common.annotations.VisibleForTesting; import lombok.extern.slf4j.Slf4j; @@ -20,6 +19,7 @@ import javax.annotation.Resource; import java.util.List; import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; +import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.*; /** * 参数配置 Service 实现类 @@ -35,7 +35,7 @@ public class ConfigServiceImpl implements ConfigService { @Override public Long createConfig(ConfigCreateReqVO reqVO) { // 校验正确性 - checkCreateOrUpdate(null, reqVO.getKey()); + validateConfigForCreateOrUpdate(null, reqVO.getKey()); // 插入参数配置 ConfigDO config = ConfigConvert.INSTANCE.convert(reqVO); config.setType(ConfigTypeEnum.CUSTOM.getType()); @@ -46,19 +46,19 @@ public class ConfigServiceImpl implements ConfigService { @Override public void updateConfig(ConfigUpdateReqVO reqVO) { // 校验正确性 - checkCreateOrUpdate(reqVO.getId(), null); // 不允许更新 key + validateConfigForCreateOrUpdate(reqVO.getId(), null); // 不允许更新 key // 更新参数配置 ConfigDO updateObj = ConfigConvert.INSTANCE.convert(reqVO); - configMapper.updateById(updateObj);; + configMapper.updateById(updateObj); } @Override public void deleteConfig(Long id) { // 校验配置存在 - ConfigDO config = checkConfigExists(id); + ConfigDO config = validateConfigExists(id); // 内置配置,不允许删除 if (ConfigTypeEnum.SYSTEM.getType().equals(config.getType())) { - throw exception(ErrorCodeConstants.CONFIG_CAN_NOT_DELETE_SYSTEM_TYPE); + throw exception(CONFIG_CAN_NOT_DELETE_SYSTEM_TYPE); } // 删除 configMapper.deleteById(id); @@ -84,39 +84,39 @@ public class ConfigServiceImpl implements ConfigService { return configMapper.selectList(reqVO); } - private void checkCreateOrUpdate(Long id, String key) { + private void validateConfigForCreateOrUpdate(Long id, String key) { // 校验自己存在 - checkConfigExists(id); + validateConfigExists(id); // 校验参数配置 key 的唯一性 if (StrUtil.isNotEmpty(key)) { - checkConfigKeyUnique(id, key); + validateConfigKeyUnique(id, key); } } @VisibleForTesting - public ConfigDO checkConfigExists(Long id) { + public ConfigDO validateConfigExists(Long id) { if (id == null) { return null; } ConfigDO config = configMapper.selectById(id); if (config == null) { - throw exception(ErrorCodeConstants.CONFIG_NOT_EXISTS); + throw exception(CONFIG_NOT_EXISTS); } return config; } @VisibleForTesting - public void checkConfigKeyUnique(Long id, String key) { + public void validateConfigKeyUnique(Long id, String key) { ConfigDO config = configMapper.selectByKey(key); if (config == null) { return; } // 如果 id 为空,说明不用比较是否为相同 id 的参数配置 if (id == null) { - throw exception(ErrorCodeConstants.CONFIG_KEY_DUPLICATE); + throw exception(CONFIG_KEY_DUPLICATE); } if (!config.getId().equals(id)) { - throw exception(ErrorCodeConstants.CONFIG_KEY_DUPLICATE); + throw exception(CONFIG_KEY_DUPLICATE); } } diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/db/DataSourceConfigServiceImpl.java b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/db/DataSourceConfigServiceImpl.java index f2fd0a408..e4365c205 100755 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/db/DataSourceConfigServiceImpl.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/db/DataSourceConfigServiceImpl.java @@ -37,7 +37,7 @@ public class DataSourceConfigServiceImpl implements DataSourceConfigService { @Override public Long createDataSourceConfig(DataSourceConfigCreateReqVO createReqVO) { DataSourceConfigDO dataSourceConfig = DataSourceConfigConvert.INSTANCE.convert(createReqVO); - checkConnectionOK(dataSourceConfig); + validateConnectionOK(dataSourceConfig); // 插入 dataSourceConfigMapper.insert(dataSourceConfig); @@ -50,7 +50,7 @@ public class DataSourceConfigServiceImpl implements DataSourceConfigService { // 校验存在 validateDataSourceConfigExists(updateReqVO.getId()); DataSourceConfigDO updateObj = DataSourceConfigConvert.INSTANCE.convert(updateReqVO); - checkConnectionOK(updateObj); + validateConnectionOK(updateObj); // 更新 dataSourceConfigMapper.updateById(updateObj); @@ -88,7 +88,7 @@ public class DataSourceConfigServiceImpl implements DataSourceConfigService { return result; } - private void checkConnectionOK(DataSourceConfigDO config) { + private void validateConnectionOK(DataSourceConfigDO config) { boolean success = JdbcUtils.isConnectionOK(config.getUrl(), config.getUsername(), config.getPassword()); if (!success) { throw exception(DATA_SOURCE_CONFIG_NOT_OK); diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/db/DatabaseTableServiceImpl.java b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/db/DatabaseTableServiceImpl.java index d0c80ba61..17fb5cea3 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/db/DatabaseTableServiceImpl.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/db/DatabaseTableServiceImpl.java @@ -41,7 +41,7 @@ public class DatabaseTableServiceImpl implements DatabaseTableService { return CollUtil.getFirst(getTableList0(dataSourceConfigId, name)); } - public List getTableList0(Long dataSourceConfigId, String name) { + private List getTableList0(Long dataSourceConfigId, String name) { // 获得数据源配置 DataSourceConfigDO config = dataSourceConfigService.getDataSourceConfig(dataSourceConfigId); Assert.notNull(config, "数据源({}) 不存在!", dataSourceConfigId); diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/file/FileConfigService.java b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/file/FileConfigService.java index b3fc6bad2..43ab5bc68 100755 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/file/FileConfigService.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/file/FileConfigService.java @@ -8,8 +8,6 @@ import cn.iocoder.yudao.module.infra.controller.admin.file.vo.config.FileConfigU import cn.iocoder.yudao.module.infra.dal.dataobject.file.FileConfigDO; import javax.validation.Valid; -import java.util.Collection; -import java.util.List; /** * 文件配置 Service 接口 @@ -60,14 +58,6 @@ public interface FileConfigService { */ FileConfigDO getFileConfig(Long id); - /** - * 获得文件配置列表 - * - * @param ids 编号 - * @return 文件配置列表 - */ - List getFileConfigList(Collection ids); - /** * 获得文件配置分页 * diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/file/FileConfigServiceImpl.java b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/file/FileConfigServiceImpl.java index 590ff8116..6236df6ff 100755 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/file/FileConfigServiceImpl.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/file/FileConfigServiceImpl.java @@ -27,7 +27,6 @@ import org.springframework.validation.annotation.Validated; import javax.annotation.PostConstruct; import javax.annotation.Resource; import javax.validation.Validator; -import java.util.Collection; import java.util.List; import java.util.Map; @@ -95,7 +94,7 @@ public class FileConfigServiceImpl implements FileConfigService { @Override public void updateFileConfig(FileConfigUpdateReqVO updateReqVO) { // 校验存在 - FileConfigDO config = this.validateFileConfigExists(updateReqVO.getId()); + FileConfigDO config = validateFileConfigExists(updateReqVO.getId()); // 更新 FileConfigDO updateObj = FileConfigConvert.INSTANCE.convert(updateReqVO) .setConfig(parseClientConfig(config.getStorage(), updateReqVO.getConfig())); @@ -108,7 +107,7 @@ public class FileConfigServiceImpl implements FileConfigService { @Transactional(rollbackFor = Exception.class) public void updateFileConfigMaster(Long id) { // 校验存在 - this.validateFileConfigExists(id); + validateFileConfigExists(id); // 更新其它为非 master fileConfigMapper.updateBatch(new FileConfigDO().setMaster(false)); // 更新 @@ -138,7 +137,7 @@ public class FileConfigServiceImpl implements FileConfigService { @Override public void deleteFileConfig(Long id) { // 校验存在 - FileConfigDO config = this.validateFileConfigExists(id); + FileConfigDO config = validateFileConfigExists(id); if (Boolean.TRUE.equals(config.getMaster())) { throw exception(FILE_CONFIG_DELETE_FAIL_MASTER); } @@ -161,11 +160,6 @@ public class FileConfigServiceImpl implements FileConfigService { return fileConfigMapper.selectById(id); } - @Override - public List getFileConfigList(Collection ids) { - return fileConfigMapper.selectBatchIds(ids); - } - @Override public PageResult getFileConfigPage(FileConfigPageReqVO pageReqVO) { return fileConfigMapper.selectPage(pageReqVO); @@ -174,7 +168,7 @@ public class FileConfigServiceImpl implements FileConfigService { @Override public String testFileConfig(Long id) throws Exception { // 校验存在 - this.validateFileConfigExists(id); + validateFileConfigExists(id); // 上传文件 byte[] content = ResourceUtil.readBytes("file/erweima.jpg"); return fileClientFactory.getFileClient(id).upload(content, IdUtil.fastSimpleUUID() + ".jpg", "image/jpeg"); diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/file/FileServiceImpl.java b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/file/FileServiceImpl.java index 2226e7bae..0732765d8 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/file/FileServiceImpl.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/file/FileServiceImpl.java @@ -69,7 +69,7 @@ public class FileServiceImpl implements FileService { @Override public void deleteFile(Long id) throws Exception { // 校验存在 - FileDO file = this.validateFileExists(id); + FileDO file = validateFileExists(id); // 从文件存储器中删除 FileClient client = fileConfigService.getFileClient(file.getConfigId()); diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/job/JobServiceImpl.java b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/job/JobServiceImpl.java index e0a245750..498d816b8 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/job/JobServiceImpl.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/job/JobServiceImpl.java @@ -69,7 +69,7 @@ public class JobServiceImpl implements JobService { public void updateJob(JobUpdateReqVO updateReqVO) throws SchedulerException { validateCronExpression(updateReqVO.getCronExpression()); // 校验存在 - JobDO job = this.validateJobExists(updateReqVO.getId()); + JobDO job = validateJobExists(updateReqVO.getId()); // 只有开启状态,才可以修改.原因是,如果出暂停状态,修改 Quartz Job 时,会导致任务又开始执行 if (!job.getStatus().equals(JobStatusEnum.NORMAL.getStatus())) { throw exception(JOB_UPDATE_ONLY_NORMAL_STATUS); @@ -92,7 +92,7 @@ public class JobServiceImpl implements JobService { throw exception(JOB_CHANGE_STATUS_INVALID); } // 校验存在 - JobDO job = this.validateJobExists(id); + JobDO job = validateJobExists(id); // 校验是否已经为当前状态 if (job.getStatus().equals(status)) { throw exception(JOB_CHANGE_STATUS_EQUALS); @@ -112,7 +112,7 @@ public class JobServiceImpl implements JobService { @Override public void triggerJob(Long id) throws SchedulerException { // 校验存在 - JobDO job = this.validateJobExists(id); + JobDO job = validateJobExists(id); // 触发 Quartz 中的 Job schedulerManager.triggerJob(job.getId(), job.getHandlerName(), job.getHandlerParam()); @@ -122,7 +122,7 @@ public class JobServiceImpl implements JobService { @Transactional(rollbackFor = Exception.class) public void deleteJob(Long id) throws SchedulerException { // 校验存在 - JobDO job = this.validateJobExists(id); + JobDO job = validateJobExists(id); // 更新 jobMapper.deleteById(id); diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/logger/ApiErrorLogServiceImpl.java b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/logger/ApiErrorLogServiceImpl.java index c1b129322..c0f9252af 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/logger/ApiErrorLogServiceImpl.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/logger/ApiErrorLogServiceImpl.java @@ -1,6 +1,5 @@ package cn.iocoder.yudao.module.infra.service.logger; -import cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil; import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.module.infra.api.logger.dto.ApiErrorLogCreateReqDTO; import cn.iocoder.yudao.module.infra.controller.admin.logger.vo.apierrorlog.ApiErrorLogExportReqVO; @@ -8,7 +7,6 @@ import cn.iocoder.yudao.module.infra.controller.admin.logger.vo.apierrorlog.ApiE import cn.iocoder.yudao.module.infra.convert.logger.ApiErrorLogConvert; import cn.iocoder.yudao.module.infra.dal.dataobject.logger.ApiErrorLogDO; import cn.iocoder.yudao.module.infra.dal.mysql.logger.ApiErrorLogMapper; -import cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants; import cn.iocoder.yudao.module.infra.enums.logger.ApiErrorLogProcessStatusEnum; import org.springframework.stereotype.Service; import org.springframework.validation.annotation.Validated; @@ -17,6 +15,10 @@ import javax.annotation.Resource; import java.time.LocalDateTime; import java.util.List; +import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; +import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.API_ERROR_LOG_NOT_FOUND; +import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.API_ERROR_LOG_PROCESSED; + /** * API 错误日志 Service 实现类 * @@ -31,8 +33,8 @@ public class ApiErrorLogServiceImpl implements ApiErrorLogService { @Override public void createApiErrorLog(ApiErrorLogCreateReqDTO createDTO) { - ApiErrorLogDO apiErrorLog = ApiErrorLogConvert.INSTANCE.convert(createDTO); - apiErrorLog.setProcessStatus(ApiErrorLogProcessStatusEnum.INIT.getStatus()); + ApiErrorLogDO apiErrorLog = ApiErrorLogConvert.INSTANCE.convert(createDTO) + .setProcessStatus(ApiErrorLogProcessStatusEnum.INIT.getStatus()); apiErrorLogMapper.insert(apiErrorLog); } @@ -50,10 +52,10 @@ public class ApiErrorLogServiceImpl implements ApiErrorLogService { public void updateApiErrorLogProcess(Long id, Integer processStatus, Long processUserId) { ApiErrorLogDO errorLog = apiErrorLogMapper.selectById(id); if (errorLog == null) { - throw ServiceExceptionUtil.exception(ErrorCodeConstants.API_ERROR_LOG_NOT_FOUND); + throw exception(API_ERROR_LOG_NOT_FOUND); } if (!ApiErrorLogProcessStatusEnum.INIT.getStatus().equals(errorLog.getProcessStatus())) { - throw ServiceExceptionUtil.exception(ErrorCodeConstants.API_ERROR_LOG_PROCESSED); + throw exception(API_ERROR_LOG_PROCESSED); } // 标记处理 apiErrorLogMapper.updateById(ApiErrorLogDO.builder().id(id).processStatus(processStatus) diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/test/TestDemoServiceImpl.java b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/test/TestDemoServiceImpl.java index 731a29ccc..70f2ebc5d 100755 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/test/TestDemoServiceImpl.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/test/TestDemoServiceImpl.java @@ -45,7 +45,7 @@ public class TestDemoServiceImpl implements TestDemoService { @CacheEvict(value = "test", key = "#updateReqVO.id") public void updateTestDemo(TestDemoUpdateReqVO updateReqVO) { // 校验存在 - this.validateTestDemoExists(updateReqVO.getId()); + validateTestDemoExists(updateReqVO.getId()); // 更新 TestDemoDO updateObj = TestDemoConvert.INSTANCE.convert(updateReqVO); testDemoMapper.updateById(updateObj); @@ -55,7 +55,7 @@ public class TestDemoServiceImpl implements TestDemoService { @CacheEvict(value = "test", key = "#id") public void deleteTestDemo(Long id) { // 校验存在 - this.validateTestDemoExists(id); + validateTestDemoExists(id); // 删除 testDemoMapper.deleteById(id); } diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/resources/codegen/java/service/serviceImpl.vm b/yudao-module-infra/yudao-module-infra-biz/src/main/resources/codegen/java/service/serviceImpl.vm index 85dfa0aab..a732039ce 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/resources/codegen/java/service/serviceImpl.vm +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/resources/codegen/java/service/serviceImpl.vm @@ -39,7 +39,7 @@ public class ${table.className}ServiceImpl implements ${table.className}Service @Override public void update${simpleClassName}(${sceneEnum.prefixClass}${table.className}UpdateReqVO updateReqVO) { // 校验存在 - this.validate${simpleClassName}Exists(updateReqVO.getId()); + validate${simpleClassName}Exists(updateReqVO.getId()); // 更新 ${table.className}DO updateObj = ${table.className}Convert.INSTANCE.convert(updateReqVO); ${classNameVar}Mapper.updateById(updateObj); @@ -48,7 +48,7 @@ public class ${table.className}ServiceImpl implements ${table.className}Service @Override public void delete${simpleClassName}(${primaryColumn.javaType} id) { // 校验存在 - this.validate${simpleClassName}Exists(id); + validate${simpleClassName}Exists(id); // 删除 ${classNameVar}Mapper.deleteById(id); } diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/resources/codegen/java/test/serviceTest.vm b/yudao-module-infra/yudao-module-infra-biz/src/main/resources/codegen/java/test/serviceTest.vm index e97fbb275..67a44e989 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/resources/codegen/java/test/serviceTest.vm +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/resources/codegen/java/test/serviceTest.vm @@ -52,7 +52,7 @@ import static org.mockito.Mockito.*; #if (${column.listOperation}) #set ($JavaField = $column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)})##首字母大写 #if (${column.listOperationCondition} == "BETWEEN")## BETWEEN 的情况 - reqVO.set${JavaField}((new LocalDateTime[]{})); + reqVO.set${JavaField}(buildBetweenTime(2023, 2, 1, 2023, 2, 28)); #else reqVO.set$JavaField(null); #end diff --git a/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/config/ConfigServiceTest.java b/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/config/ConfigServiceImplTest.java similarity index 75% rename from yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/config/ConfigServiceTest.java rename to yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/config/ConfigServiceImplTest.java index 5f29e79ec..428b20522 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/config/ConfigServiceTest.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/config/ConfigServiceImplTest.java @@ -2,7 +2,6 @@ package cn.iocoder.yudao.module.infra.service.config; import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.common.util.collection.ArrayUtils; -import cn.iocoder.yudao.framework.common.util.object.ObjectUtils; import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import cn.iocoder.yudao.framework.test.core.util.RandomUtils; import cn.iocoder.yudao.module.infra.controller.admin.config.vo.ConfigCreateReqVO; @@ -12,17 +11,17 @@ import cn.iocoder.yudao.module.infra.controller.admin.config.vo.ConfigUpdateReqV import cn.iocoder.yudao.module.infra.dal.dataobject.config.ConfigDO; import cn.iocoder.yudao.module.infra.dal.mysql.config.ConfigMapper; import cn.iocoder.yudao.module.infra.enums.config.ConfigTypeEnum; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.context.annotation.Import; import javax.annotation.Resource; -import java.time.LocalDateTime; import java.util.List; import java.util.function.Consumer; import static cn.hutool.core.util.RandomUtil.randomEle; +import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildBetweenTime; import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildTime; +import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; @@ -30,7 +29,7 @@ import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.*; import static org.junit.jupiter.api.Assertions.*; @Import(ConfigServiceImpl.class) -public class ConfigServiceTest extends BaseDbUnitTest { +public class ConfigServiceImplTest extends BaseDbUnitTest { @Resource private ConfigServiceImpl configService; @@ -50,7 +49,7 @@ public class ConfigServiceTest extends BaseDbUnitTest { // 校验记录的属性是否正确 ConfigDO config = configMapper.selectById(configId); assertPojoEquals(reqVO, config); - Assertions.assertEquals(ConfigTypeEnum.CUSTOM.getType(), config.getType()); + assertEquals(ConfigTypeEnum.CUSTOM.getType(), config.getType()); } @Test @@ -101,40 +100,40 @@ public class ConfigServiceTest extends BaseDbUnitTest { } @Test - public void testCheckConfigExists_success() { + public void testValidateConfigExists_success() { // mock 数据 ConfigDO dbConfigDO = randomConfigDO(); configMapper.insert(dbConfigDO);// @Sql: 先插入出一条存在的数据 // 调用成功 - configService.checkConfigExists(dbConfigDO.getId()); + configService.validateConfigExists(dbConfigDO.getId()); } @Test - public void testCheckConfigExist_notExists() { - assertServiceException(() -> configService.checkConfigExists(randomLongId()), CONFIG_NOT_EXISTS); + public void testValidateConfigExist_notExists() { + assertServiceException(() -> configService.validateConfigExists(randomLongId()), CONFIG_NOT_EXISTS); } @Test - public void testCheckConfigKeyUnique_success() { + public void testValidateConfigKeyUnique_success() { // 调用,成功 - configService.checkConfigKeyUnique(randomLongId(), randomString()); + configService.validateConfigKeyUnique(randomLongId(), randomString()); } @Test - public void testCheckConfigKeyUnique_keyDuplicateForCreate() { + public void testValidateConfigKeyUnique_keyDuplicateForCreate() { // 准备参数 String key = randomString(); // mock 数据 configMapper.insert(randomConfigDO(o -> o.setConfigKey(key))); // 调用,校验异常 - assertServiceException(() -> configService.checkConfigKeyUnique(null, key), + assertServiceException(() -> configService.validateConfigKeyUnique(null, key), CONFIG_KEY_DUPLICATE); } @Test - public void testCheckConfigKeyUnique_keyDuplicateForUpdate() { + public void testValidateConfigKeyUnique_keyDuplicateForUpdate() { // 准备参数 Long id = randomLongId(); String key = randomString(); @@ -142,7 +141,7 @@ public class ConfigServiceTest extends BaseDbUnitTest { configMapper.insert(randomConfigDO(o -> o.setConfigKey(key))); // 调用,校验异常 - assertServiceException(() -> configService.checkConfigKeyUnique(id, key), + assertServiceException(() -> configService.validateConfigKeyUnique(id, key), CONFIG_KEY_DUPLICATE); } @@ -157,19 +156,19 @@ public class ConfigServiceTest extends BaseDbUnitTest { }); configMapper.insert(dbConfig); // 测试 name 不匹配 - configMapper.insert(ObjectUtils.cloneIgnoreId(dbConfig, o -> o.setName("土豆"))); + configMapper.insert(cloneIgnoreId(dbConfig, o -> o.setName("土豆"))); // 测试 key 不匹配 - configMapper.insert(ObjectUtils.cloneIgnoreId(dbConfig, o -> o.setConfigKey("tudou"))); + configMapper.insert(cloneIgnoreId(dbConfig, o -> o.setConfigKey("tudou"))); // 测试 type 不匹配 - configMapper.insert(ObjectUtils.cloneIgnoreId(dbConfig, o -> o.setType(ConfigTypeEnum.CUSTOM.getType()))); + configMapper.insert(cloneIgnoreId(dbConfig, o -> o.setType(ConfigTypeEnum.CUSTOM.getType()))); // 测试 createTime 不匹配 - configMapper.insert(ObjectUtils.cloneIgnoreId(dbConfig, o -> o.setCreateTime(buildTime(2021, 1, 1)))); + configMapper.insert(cloneIgnoreId(dbConfig, o -> o.setCreateTime(buildTime(2021, 1, 1)))); // 准备参数 ConfigPageReqVO reqVO = new ConfigPageReqVO(); reqVO.setName("艿"); reqVO.setKey("nai"); reqVO.setType(ConfigTypeEnum.SYSTEM.getType()); - reqVO.setCreateTime((new LocalDateTime[]{buildTime(2021, 1, 15),buildTime(2021, 2, 15)})); + reqVO.setCreateTime(buildBetweenTime(2021, 1, 15, 2021, 2, 15)); // 调用 PageResult pageResult = configService.getConfigPage(reqVO); @@ -190,19 +189,19 @@ public class ConfigServiceTest extends BaseDbUnitTest { }); configMapper.insert(dbConfig); // 测试 name 不匹配 - configMapper.insert(ObjectUtils.cloneIgnoreId(dbConfig, o -> o.setName("土豆"))); + configMapper.insert(cloneIgnoreId(dbConfig, o -> o.setName("土豆"))); // 测试 key 不匹配 - configMapper.insert(ObjectUtils.cloneIgnoreId(dbConfig, o -> o.setConfigKey("tudou"))); + configMapper.insert(cloneIgnoreId(dbConfig, o -> o.setConfigKey("tudou"))); // 测试 type 不匹配 - configMapper.insert(ObjectUtils.cloneIgnoreId(dbConfig, o -> o.setType(ConfigTypeEnum.CUSTOM.getType()))); + configMapper.insert(cloneIgnoreId(dbConfig, o -> o.setType(ConfigTypeEnum.CUSTOM.getType()))); // 测试 createTime 不匹配 - configMapper.insert(ObjectUtils.cloneIgnoreId(dbConfig, o -> o.setCreateTime(buildTime(2021, 1, 1)))); + configMapper.insert(cloneIgnoreId(dbConfig, o -> o.setCreateTime(buildTime(2021, 1, 1)))); // 准备参数 ConfigExportReqVO reqVO = new ConfigExportReqVO(); reqVO.setName("艿"); reqVO.setKey("nai"); reqVO.setType(ConfigTypeEnum.SYSTEM.getType()); - reqVO.setCreateTime((new LocalDateTime[]{buildTime(2021, 1, 15),buildTime(2021, 2, 15)})); + reqVO.setCreateTime(buildBetweenTime(2021, 1, 15, 2021, 2, 15)); // 调用 List list = configService.getConfigList(reqVO); @@ -211,6 +210,21 @@ public class ConfigServiceTest extends BaseDbUnitTest { assertPojoEquals(dbConfig, list.get(0)); } + @Test + public void testGetConfig() { + // mock 数据 + ConfigDO dbConfig = randomConfigDO(); + configMapper.insert(dbConfig);// @Sql: 先插入出一条存在的数据 + // 准备参数 + Long id = dbConfig.getId(); + + // 调用 + ConfigDO config = configService.getConfig(id); + // 断言 + assertNotNull(config); + assertPojoEquals(dbConfig, config); + } + @Test public void testGetConfigByKey() { // mock 数据 diff --git a/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/db/DataSourceConfigServiceImplTest.java b/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/db/DataSourceConfigServiceImplTest.java index e1c997f7b..b5ef46c46 100755 --- a/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/db/DataSourceConfigServiceImplTest.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/db/DataSourceConfigServiceImplTest.java @@ -1,5 +1,6 @@ package cn.iocoder.yudao.module.infra.service.db; +import cn.hutool.core.map.MapUtil; import cn.hutool.core.util.ReflectUtil; import cn.hutool.crypto.symmetric.AES; import cn.iocoder.yudao.framework.mybatis.core.type.EncryptTypeHandler; @@ -9,6 +10,7 @@ import cn.iocoder.yudao.module.infra.controller.admin.db.vo.DataSourceConfigCrea import cn.iocoder.yudao.module.infra.controller.admin.db.vo.DataSourceConfigUpdateReqVO; import cn.iocoder.yudao.module.infra.dal.dataobject.db.DataSourceConfigDO; import cn.iocoder.yudao.module.infra.dal.mysql.db.DataSourceConfigMapper; +import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty; import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -18,14 +20,14 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import javax.annotation.Resource; +import java.util.List; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomLongId; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo; import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.DATA_SOURCE_CONFIG_NOT_EXISTS; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mockStatic; @@ -57,6 +59,11 @@ public class DataSourceConfigServiceImplTest extends BaseDbUnitTest { ReflectUtil.setFieldValue(EncryptTypeHandler.class, "aes", aes); when(aes.encryptBase64(anyString())).then((Answer) invocation -> invocation.getArgument(0)); when(aes.decryptStr(anyString())).then((Answer) invocation -> invocation.getArgument(0)); + + // mock DynamicDataSourceProperties + when(dynamicDataSourceProperties.getPrimary()).thenReturn("primary"); + when(dynamicDataSourceProperties.getDatasource()).thenReturn(MapUtil.of("primary", + new DataSourceProperty().setUrl("http://localhost:3306").setUsername("yunai").setPassword("tudou"))); } @Test @@ -89,7 +96,6 @@ public class DataSourceConfigServiceImplTest extends BaseDbUnitTest { o.setId(dbDataSourceConfig.getId()); // 设置更新的 ID }); // mock 方法 -// when(stringEncryptor.encrypt(eq(reqVO.getPassword()))).thenReturn("123456"); databaseUtilsMock.when(() -> JdbcUtils.isConnectionOK(eq(reqVO.getUrl()), eq(reqVO.getUsername()), eq(reqVO.getPassword()))).thenReturn(true); @@ -142,7 +148,58 @@ public class DataSourceConfigServiceImplTest extends BaseDbUnitTest { // 调用 DataSourceConfigDO result = dataSourceConfigMapper.selectOne(DataSourceConfigDO::getPassword, EncryptTypeHandler.encrypt(dbDataSourceConfig.getPassword())); - System.out.println(result); + assertPojoEquals(dbDataSourceConfig, result); + } + + @Test + public void testGetDataSourceConfig_master() { + // 准备参数 + Long id = 0L; + // mock 方法 + + // 调用 + DataSourceConfigDO dataSourceConfig = dataSourceConfigService.getDataSourceConfig(id); + // 断言 + assertEquals(id, dataSourceConfig.getId()); + assertEquals("primary", dataSourceConfig.getName()); + assertEquals("http://localhost:3306", dataSourceConfig.getUrl()); + assertEquals("yunai", dataSourceConfig.getUsername()); + assertEquals("tudou", dataSourceConfig.getPassword()); + } + + @Test + public void testGetDataSourceConfig_normal() { + // mock 数据 + DataSourceConfigDO dbDataSourceConfig = randomPojo(DataSourceConfigDO.class); + dataSourceConfigMapper.insert(dbDataSourceConfig);// @Sql: 先插入出一条存在的数据 + // 准备参数 + Long id = dbDataSourceConfig.getId(); + + // 调用 + DataSourceConfigDO dataSourceConfig = dataSourceConfigService.getDataSourceConfig(id); + // 断言 + assertPojoEquals(dbDataSourceConfig, dataSourceConfig); + } + + @Test + public void testGetDataSourceConfigList() { + // mock 数据 + DataSourceConfigDO dbDataSourceConfig = randomPojo(DataSourceConfigDO.class); + dataSourceConfigMapper.insert(dbDataSourceConfig);// @Sql: 先插入出一条存在的数据 + // 准备参数 + + // 调用 + List dataSourceConfigList = dataSourceConfigService.getDataSourceConfigList(); + // 断言 + assertEquals(2, dataSourceConfigList.size()); + // master + assertEquals(0L, dataSourceConfigList.get(0).getId()); + assertEquals("primary", dataSourceConfigList.get(0).getName()); + assertEquals("http://localhost:3306", dataSourceConfigList.get(0).getUrl()); + assertEquals("yunai", dataSourceConfigList.get(0).getUsername()); + assertEquals("tudou", dataSourceConfigList.get(0).getPassword()); + // normal + assertPojoEquals(dbDataSourceConfig, dataSourceConfigList.get(1)); } } diff --git a/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/db/DatabaseTableServiceImplTest.java b/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/db/DatabaseTableServiceImplTest.java new file mode 100644 index 000000000..6ce8c7d41 --- /dev/null +++ b/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/db/DatabaseTableServiceImplTest.java @@ -0,0 +1,89 @@ +package cn.iocoder.yudao.module.infra.service.db; + +import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; +import cn.iocoder.yudao.module.infra.dal.dataobject.db.DataSourceConfigDO; +import com.baomidou.mybatisplus.generator.config.po.TableField; +import com.baomidou.mybatisplus.generator.config.po.TableInfo; +import com.baomidou.mybatisplus.generator.config.rules.DbColumnType; +import org.apache.ibatis.type.JdbcType; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.context.annotation.Import; + +import javax.annotation.Resource; +import java.util.List; + +import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomLongId; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + +@Import(DatabaseTableServiceImpl.class) +public class DatabaseTableServiceImplTest extends BaseDbUnitTest { + + @Resource + private DatabaseTableServiceImpl databaseTableService; + + @MockBean + private DataSourceConfigService dataSourceConfigService; + + @Test + public void testGetTableList() { + // 准备参数 + Long dataSourceConfigId = randomLongId(); + // mock 方法 + DataSourceConfigDO dataSourceConfig = new DataSourceConfigDO().setUsername("sa").setPassword("") + .setUrl("jdbc:h2:mem:testdb"); + when(dataSourceConfigService.getDataSourceConfig(eq(dataSourceConfigId))) + .thenReturn(dataSourceConfig); + + // 调用 + List tables = databaseTableService.getTableList(dataSourceConfigId, + "config", "参数"); + // 断言 + assertEquals(1, tables.size()); + assertTableInfo(tables.get(0)); + } + + @Test + public void testGetTable() { + // 准备参数 + Long dataSourceConfigId = randomLongId(); + // mock 方法 + DataSourceConfigDO dataSourceConfig = new DataSourceConfigDO().setUsername("sa").setPassword("") + .setUrl("jdbc:h2:mem:testdb"); + when(dataSourceConfigService.getDataSourceConfig(eq(dataSourceConfigId))) + .thenReturn(dataSourceConfig); + + // 调用 + TableInfo tableInfo = databaseTableService.getTable(dataSourceConfigId, "infra_config"); + // 断言 + assertTableInfo(tableInfo); + } + + private void assertTableInfo(TableInfo tableInfo) { + assertEquals("infra_config", tableInfo.getName()); + assertEquals("参数配置表", tableInfo.getComment()); + assertEquals(13, tableInfo.getFields().size()); + // id 字段 + TableField idField = tableInfo.getFields().get(0); + assertEquals("id", idField.getName()); + assertEquals(JdbcType.BIGINT, idField.getMetaInfo().getJdbcType()); + assertEquals("编号", idField.getComment()); + assertFalse(idField.getMetaInfo().isNullable()); + assertTrue(idField.isKeyFlag()); + assertTrue(idField.isKeyIdentityFlag()); + assertEquals(DbColumnType.LONG, idField.getColumnType()); + assertEquals("id", idField.getPropertyName()); + // name 字段 + TableField nameField = tableInfo.getFields().get(3); + assertEquals("name", nameField.getName()); + assertEquals(JdbcType.VARCHAR, nameField.getMetaInfo().getJdbcType()); + assertEquals("名字", nameField.getComment()); + assertFalse(nameField.getMetaInfo().isNullable()); + assertFalse(nameField.isKeyFlag()); + assertFalse(nameField.isKeyIdentityFlag()); + assertEquals(DbColumnType.STRING, nameField.getColumnType()); + assertEquals("name", nameField.getPropertyName()); + } +} diff --git a/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/file/FileConfigServiceImplTest.java b/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/file/FileConfigServiceImplTest.java index 61c9827f6..656955194 100755 --- a/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/file/FileConfigServiceImplTest.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/file/FileConfigServiceImplTest.java @@ -7,6 +7,7 @@ import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.file.core.client.FileClient; import cn.iocoder.yudao.framework.file.core.client.FileClientConfig; import cn.iocoder.yudao.framework.file.core.client.FileClientFactory; +import cn.iocoder.yudao.framework.file.core.client.local.LocalFileClient; import cn.iocoder.yudao.framework.file.core.client.local.LocalFileClientConfig; import cn.iocoder.yudao.framework.file.core.enums.FileStorageEnum; import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; @@ -242,6 +243,30 @@ public class FileConfigServiceImplTest extends BaseDbUnitTest { assertEquals("https://www.iocoder.cn", fileConfigService.testFileConfig(id)); } + @Test + public void testGetFileConfig() { + // mock 数据 + FileConfigDO dbFileConfig = randomFileConfigDO().setMaster(false); + fileConfigMapper.insert(dbFileConfig);// @Sql: 先插入出一条存在的数据 + // 准备参数 + Long id = dbFileConfig.getId(); + + // 调用,并断言 + assertPojoEquals(dbFileConfig, fileConfigService.getFileConfig(id)); + } + + @Test + public void testGetFileClient() { + // 准备参数 + Long id = randomLongId(); + // mock 获得 Client + FileClient fileClient = new LocalFileClient(id, new LocalFileClientConfig()); + when(fileClientFactory.getFileClient(eq(id))).thenReturn(fileClient); + + // 调用,并断言 + assertSame(fileClient, fileConfigService.getFileClient(id)); + } + private FileConfigDO randomFileConfigDO() { return randomPojo(FileConfigDO.class).setStorage(randomEle(FileStorageEnum.values()).getStorage()) .setConfig(new EmptyFileClientConfig()); diff --git a/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/file/FileServiceTest.java b/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/file/FileServiceImplTest.java similarity index 98% rename from yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/file/FileServiceTest.java rename to yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/file/FileServiceImplTest.java index 90bde8f4e..57cc4c476 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/file/FileServiceTest.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/file/FileServiceImplTest.java @@ -26,7 +26,7 @@ import static org.mockito.ArgumentMatchers.same; import static org.mockito.Mockito.*; @Import({FileServiceImpl.class}) -public class FileServiceTest extends BaseDbUnitTest { +public class FileServiceImplTest extends BaseDbUnitTest { @Resource private FileService fileService; diff --git a/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/job/JobLogServiceTest.java b/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/job/JobLogServiceImplTest.java similarity index 52% rename from yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/job/JobLogServiceTest.java rename to yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/job/JobLogServiceImplTest.java index 665e9c509..efba0c0cf 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/job/JobLogServiceTest.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/job/JobLogServiceImplTest.java @@ -1,7 +1,6 @@ package cn.iocoder.yudao.module.infra.service.job; import cn.iocoder.yudao.framework.common.pojo.PageResult; -import cn.iocoder.yudao.framework.common.util.object.ObjectUtils; import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import cn.iocoder.yudao.module.infra.controller.admin.job.vo.log.JobLogExportReqVO; import cn.iocoder.yudao.module.infra.controller.admin.job.vo.log.JobLogPageReqVO; @@ -12,18 +11,20 @@ import org.junit.jupiter.api.Test; import org.springframework.context.annotation.Import; import javax.annotation.Resource; -import java.util.ArrayList; +import java.time.LocalDateTime; +import java.util.Collection; import java.util.List; -import static cn.hutool.core.util.RandomUtil.randomEle; import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildTime; +import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; +import static java.util.Collections.singleton; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; @Import(JobLogServiceImpl.class) -public class JobLogServiceTest extends BaseDbUnitTest { +public class JobLogServiceImplTest extends BaseDbUnitTest { @Resource private JobLogServiceImpl jobLogService; @@ -31,66 +32,103 @@ public class JobLogServiceTest extends BaseDbUnitTest { private JobLogMapper jobLogMapper; @Test - public void testCreateJobLog_success() { + public void testCreateJobLog() { // 准备参数 - JobLogDO reqVO = randomPojo(JobLogDO.class, o -> { - o.setExecuteIndex(1); - }); + JobLogDO reqVO = randomPojo(JobLogDO.class, o -> o.setExecuteIndex(1)); + // 调用 - Long jobLogId = jobLogService.createJobLog(reqVO.getJobId(), reqVO.getBeginTime(), reqVO.getHandlerName(), reqVO.getHandlerParam(), reqVO.getExecuteIndex()); + Long id = jobLogService.createJobLog(reqVO.getJobId(), reqVO.getBeginTime(), + reqVO.getHandlerName(), reqVO.getHandlerParam(), reqVO.getExecuteIndex()); // 断言 - assertNotNull(jobLogId); + assertNotNull(id); // 校验记录的属性是否正确 - JobLogDO job = jobLogMapper.selectById(jobLogId); + JobLogDO job = jobLogMapper.selectById(id); assertEquals(JobLogStatusEnum.RUNNING.getStatus(), job.getStatus()); } @Test public void testUpdateJobLogResultAsync_success() { - // 准备参数 - JobLogDO reqVO = randomPojo(JobLogDO.class, o -> { + // mock 数据 + JobLogDO log = randomPojo(JobLogDO.class, o -> { o.setExecuteIndex(1); + o.setStatus(JobLogStatusEnum.RUNNING.getStatus()); }); - JobLogDO log = JobLogDO.builder().jobId(reqVO.getJobId()).handlerName(reqVO.getHandlerName()).handlerParam(reqVO.getHandlerParam()).executeIndex(reqVO.getExecuteIndex()) - .beginTime(reqVO.getBeginTime()).status(JobLogStatusEnum.RUNNING.getStatus()).build(); jobLogMapper.insert(log); - // 调用 - jobLogService.updateJobLogResultAsync(log.getId(), reqVO.getBeginTime(), reqVO.getDuration(), true,reqVO.getResult()); - // 校验记录的属性是否正确 - JobLogDO job = jobLogMapper.selectById(log.getId()); - assertEquals(JobLogStatusEnum.SUCCESS.getStatus(), job.getStatus()); + // 准备参数 + Long logId = log.getId(); + LocalDateTime endTime = randomLocalDateTime(); + Integer duration = randomInteger(); + boolean success = true; + String result = randomString(); // 调用 - jobLogService.updateJobLogResultAsync(log.getId(), reqVO.getBeginTime(), reqVO.getDuration(), false,reqVO.getResult()); + jobLogService.updateJobLogResultAsync(logId, endTime, duration, success, result); // 校验记录的属性是否正确 - JobLogDO job2 = jobLogMapper.selectById(log.getId()); - assertEquals(JobLogStatusEnum.FAILURE.getStatus(), job2.getStatus()); + JobLogDO dbLog = jobLogMapper.selectById(log.getId()); + assertEquals(endTime, dbLog.getEndTime()); + assertEquals(duration, dbLog.getDuration()); + assertEquals(JobLogStatusEnum.SUCCESS.getStatus(), dbLog.getStatus()); + assertEquals(result, dbLog.getResult()); } @Test - public void testGetJobLogListByIds_success() { + public void testUpdateJobLogResultAsync_failure() { // mock 数据 - JobLogDO dbJobLog = randomPojo(JobLogDO.class, o -> { + JobLogDO log = randomPojo(JobLogDO.class, o -> { o.setExecuteIndex(1); - o.setStatus(randomEle(JobLogStatusEnum.values()).getStatus()); // 保证 status 的范围 + o.setStatus(JobLogStatusEnum.RUNNING.getStatus()); }); - JobLogDO cloneJobLog = ObjectUtils.cloneIgnoreId(dbJobLog, o -> o.setHandlerName(randomString())); + jobLogMapper.insert(log); + // 准备参数 + Long logId = log.getId(); + LocalDateTime endTime = randomLocalDateTime(); + Integer duration = randomInteger(); + boolean success = false; + String result = randomString(); + + // 调用 + jobLogService.updateJobLogResultAsync(logId, endTime, duration, success, result); + // 校验记录的属性是否正确 + JobLogDO dbLog = jobLogMapper.selectById(log.getId()); + assertEquals(endTime, dbLog.getEndTime()); + assertEquals(duration, dbLog.getDuration()); + assertEquals(JobLogStatusEnum.FAILURE.getStatus(), dbLog.getStatus()); + assertEquals(result, dbLog.getResult()); + } + + @Test + public void testGetJobLog() { + // mock 数据 + JobLogDO dbJobLog = randomPojo(JobLogDO.class, o -> o.setExecuteIndex(1)); + jobLogMapper.insert(dbJobLog); + // 准备参数 + Long id = dbJobLog.getId(); + + // 调用 + JobLogDO jobLog = jobLogService.getJobLog(id); + // 断言 + assertPojoEquals(dbJobLog, jobLog); + } + + @Test + public void testGetJobLogList() { + // mock 数据 + JobLogDO dbJobLog = randomPojo(JobLogDO.class, o -> o.setExecuteIndex(1)); jobLogMapper.insert(dbJobLog); // 测试 handlerName 不匹配 - jobLogMapper.insert(cloneJobLog); + jobLogMapper.insert(cloneIgnoreId(dbJobLog, o -> {})); // 准备参数 - ArrayList ids = new ArrayList<>(); - ids.add(dbJobLog.getId()); - ids.add(cloneJobLog.getId()); + Collection ids = singleton(dbJobLog.getId()); + // 调用 List list = jobLogService.getJobLogList(ids); // 断言 - assertEquals(2, list.size()); + assertEquals(1, list.size()); assertPojoEquals(dbJobLog, list.get(0)); } @Test - public void testGetJobPage_success() { + public void testGetJobPage() { // mock 数据 JobLogDO dbJobLog = randomPojo(JobLogDO.class, o -> { o.setExecuteIndex(1); @@ -101,15 +139,15 @@ public class JobLogServiceTest extends BaseDbUnitTest { }); jobLogMapper.insert(dbJobLog); // 测试 jobId 不匹配 - jobLogMapper.insert(ObjectUtils.cloneIgnoreId(dbJobLog, o -> o.setJobId(randomLongId()))); + jobLogMapper.insert(cloneIgnoreId(dbJobLog, o -> o.setJobId(randomLongId()))); // 测试 handlerName 不匹配 - jobLogMapper.insert(ObjectUtils.cloneIgnoreId(dbJobLog, o -> o.setHandlerName(randomString()))); + jobLogMapper.insert(cloneIgnoreId(dbJobLog, o -> o.setHandlerName(randomString()))); // 测试 beginTime 不匹配 - jobLogMapper.insert(ObjectUtils.cloneIgnoreId(dbJobLog, o -> o.setBeginTime(buildTime(2021, 1, 7)))); + jobLogMapper.insert(cloneIgnoreId(dbJobLog, o -> o.setBeginTime(buildTime(2021, 1, 7)))); // 测试 endTime 不匹配 - jobLogMapper.insert(ObjectUtils.cloneIgnoreId(dbJobLog, o -> o.setEndTime(buildTime(2021, 1, 9)))); + jobLogMapper.insert(cloneIgnoreId(dbJobLog, o -> o.setEndTime(buildTime(2021, 1, 9)))); // 测试 status 不匹配 - jobLogMapper.insert(ObjectUtils.cloneIgnoreId(dbJobLog, o -> o.setStatus(JobLogStatusEnum.FAILURE.getStatus()))); + jobLogMapper.insert(cloneIgnoreId(dbJobLog, o -> o.setStatus(JobLogStatusEnum.FAILURE.getStatus()))); // 准备参数 JobLogPageReqVO reqVo = new JobLogPageReqVO(); reqVo.setJobId(dbJobLog.getJobId()); @@ -117,6 +155,7 @@ public class JobLogServiceTest extends BaseDbUnitTest { reqVo.setBeginTime(dbJobLog.getBeginTime()); reqVo.setEndTime(dbJobLog.getEndTime()); reqVo.setStatus(JobLogStatusEnum.SUCCESS.getStatus()); + // 调用 PageResult pageResult = jobLogService.getJobLogPage(reqVo); // 断言 @@ -126,7 +165,7 @@ public class JobLogServiceTest extends BaseDbUnitTest { } @Test - public void testGetJobListForExport_success() { + public void testGetJobList_export() { // mock 数据 JobLogDO dbJobLog = randomPojo(JobLogDO.class, o -> { o.setExecuteIndex(1); @@ -137,15 +176,15 @@ public class JobLogServiceTest extends BaseDbUnitTest { }); jobLogMapper.insert(dbJobLog); // 测试 jobId 不匹配 - jobLogMapper.insert(ObjectUtils.cloneIgnoreId(dbJobLog, o -> o.setJobId(randomLongId()))); + jobLogMapper.insert(cloneIgnoreId(dbJobLog, o -> o.setJobId(randomLongId()))); // 测试 handlerName 不匹配 - jobLogMapper.insert(ObjectUtils.cloneIgnoreId(dbJobLog, o -> o.setHandlerName(randomString()))); + jobLogMapper.insert(cloneIgnoreId(dbJobLog, o -> o.setHandlerName(randomString()))); // 测试 beginTime 不匹配 - jobLogMapper.insert(ObjectUtils.cloneIgnoreId(dbJobLog, o -> o.setBeginTime(buildTime(2021, 1, 7)))); + jobLogMapper.insert(cloneIgnoreId(dbJobLog, o -> o.setBeginTime(buildTime(2021, 1, 7)))); // 测试 endTime 不匹配 - jobLogMapper.insert(ObjectUtils.cloneIgnoreId(dbJobLog, o -> o.setEndTime(buildTime(2021, 1, 9)))); + jobLogMapper.insert(cloneIgnoreId(dbJobLog, o -> o.setEndTime(buildTime(2021, 1, 9)))); // 测试 status 不匹配 - jobLogMapper.insert(ObjectUtils.cloneIgnoreId(dbJobLog, o -> o.setStatus(JobLogStatusEnum.FAILURE.getStatus()))); + jobLogMapper.insert(cloneIgnoreId(dbJobLog, o -> o.setStatus(JobLogStatusEnum.FAILURE.getStatus()))); // 准备参数 JobLogExportReqVO reqVo = new JobLogExportReqVO(); reqVo.setJobId(dbJobLog.getJobId()); @@ -153,6 +192,7 @@ public class JobLogServiceTest extends BaseDbUnitTest { reqVo.setBeginTime(dbJobLog.getBeginTime()); reqVo.setEndTime(dbJobLog.getEndTime()); reqVo.setStatus(JobLogStatusEnum.SUCCESS.getStatus()); + // 调用 List list = jobLogService.getJobLogList(reqVo); // 断言 diff --git a/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/job/JobServiceTest.java b/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/job/JobServiceImplTest.java similarity index 60% rename from yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/job/JobServiceTest.java rename to yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/job/JobServiceImplTest.java index 1cfcae998..f10c40365 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/job/JobServiceTest.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/job/JobServiceImplTest.java @@ -1,14 +1,12 @@ package cn.iocoder.yudao.module.infra.service.job; import cn.iocoder.yudao.framework.common.pojo.PageResult; -import cn.iocoder.yudao.framework.common.util.object.ObjectUtils; import cn.iocoder.yudao.framework.quartz.core.scheduler.SchedulerManager; import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import cn.iocoder.yudao.module.infra.controller.admin.job.vo.job.JobCreateReqVO; import cn.iocoder.yudao.module.infra.controller.admin.job.vo.job.JobExportReqVO; import cn.iocoder.yudao.module.infra.controller.admin.job.vo.job.JobPageReqVO; import cn.iocoder.yudao.module.infra.controller.admin.job.vo.job.JobUpdateReqVO; -import cn.iocoder.yudao.module.infra.convert.job.JobConvert; import cn.iocoder.yudao.module.infra.dal.dataobject.job.JobDO; import cn.iocoder.yudao.module.infra.dal.mysql.job.JobMapper; import cn.iocoder.yudao.module.infra.enums.job.JobStatusEnum; @@ -18,22 +16,23 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import javax.annotation.Resource; -import java.util.ArrayList; +import java.util.Collection; import java.util.List; import static cn.hutool.core.util.RandomUtil.randomEle; +import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomString; import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.*; +import static java.util.Collections.singletonList; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @Import(JobServiceImpl.class) -public class JobServiceTest extends BaseDbUnitTest { +public class JobServiceImplTest extends BaseDbUnitTest { @Resource private JobServiceImpl jobService; @@ -46,6 +45,7 @@ public class JobServiceTest extends BaseDbUnitTest { public void testCreateJob_cronExpressionValid() { // 准备参数。Cron 表达式为 String 类型,默认随机字符串。 JobCreateReqVO reqVO = randomPojo(JobCreateReqVO.class); + // 调用,并断言异常 assertServiceException(() -> jobService.createJob(reqVO), JOB_CRON_EXPRESSION_VALID); } @@ -54,6 +54,7 @@ public class JobServiceTest extends BaseDbUnitTest { public void testCreateJob_jobHandlerExists() throws SchedulerException { // 准备参数 指定 Cron 表达式 JobCreateReqVO reqVO = randomPojo(JobCreateReqVO.class, o -> o.setCronExpression("0 0/1 * * * ? *")); + // 调用 jobService.createJob(reqVO); // 调用,并断言异常 @@ -64,6 +65,7 @@ public class JobServiceTest extends BaseDbUnitTest { public void testCreateJob_success() throws SchedulerException { // 准备参数 指定 Cron 表达式 JobCreateReqVO reqVO = randomPojo(JobCreateReqVO.class, o -> o.setCronExpression("0 0/1 * * * ? *")); + // 调用 Long jobId = jobService.createJob(reqVO); // 断言 @@ -73,14 +75,15 @@ public class JobServiceTest extends BaseDbUnitTest { assertPojoEquals(reqVO, job); assertEquals(JobStatusEnum.NORMAL.getStatus(), job.getStatus()); // 校验调用 - verify(schedulerManager, times(1)).addJob(eq(job.getId()), eq(job.getHandlerName()), eq(job.getHandlerParam()), eq(job.getCronExpression()), - eq(reqVO.getRetryCount()), eq(reqVO.getRetryInterval())); + verify(schedulerManager).addJob(eq(job.getId()), eq(job.getHandlerName()), eq(job.getHandlerParam()), + eq(job.getCronExpression()), eq(reqVO.getRetryCount()), eq(reqVO.getRetryInterval())); } @Test public void testUpdateJob_jobNotExists(){ // 准备参数 JobUpdateReqVO reqVO = randomPojo(JobUpdateReqVO.class, o -> o.setCronExpression("0 0/1 * * * ? *")); + // 调用,并断言异常 assertServiceException(() -> jobService.updateJob(reqVO), JOB_NOT_EXISTS); } @@ -88,150 +91,136 @@ public class JobServiceTest extends BaseDbUnitTest { @Test public void testUpdateJob_onlyNormalStatus(){ // mock 数据 - JobCreateReqVO createReqVO = randomPojo(JobCreateReqVO.class, o -> o.setCronExpression("0 0/1 * * * ? *")); - JobDO job = JobConvert.INSTANCE.convert(createReqVO); - job.setStatus(JobStatusEnum.INIT.getStatus()); - fillJobMonitorTimeoutEmpty(job); + JobDO job = randomPojo(JobDO.class, o -> o.setStatus(JobStatusEnum.INIT.getStatus())); jobMapper.insert(job); // 准备参数 JobUpdateReqVO updateReqVO = randomPojo(JobUpdateReqVO.class, o -> { o.setId(job.getId()); - o.setName(createReqVO.getName()); - o.setCronExpression(createReqVO.getCronExpression()); + o.setCronExpression("0 0/1 * * * ? *"); }); + // 调用,并断言异常 - assertServiceException(() -> jobService.updateJob(updateReqVO), JOB_UPDATE_ONLY_NORMAL_STATUS); + assertServiceException(() -> jobService.updateJob(updateReqVO), + JOB_UPDATE_ONLY_NORMAL_STATUS); } @Test public void testUpdateJob_success() throws SchedulerException { // mock 数据 - JobCreateReqVO createReqVO = randomPojo(JobCreateReqVO.class, o -> o.setCronExpression("0 0/1 * * * ? *")); - JobDO job = JobConvert.INSTANCE.convert(createReqVO); - job.setStatus(JobStatusEnum.NORMAL.getStatus()); - fillJobMonitorTimeoutEmpty(job); + JobDO job = randomPojo(JobDO.class, o -> o.setStatus(JobStatusEnum.NORMAL.getStatus())); jobMapper.insert(job); // 准备参数 JobUpdateReqVO updateReqVO = randomPojo(JobUpdateReqVO.class, o -> { o.setId(job.getId()); - o.setName(createReqVO.getName()); - o.setCronExpression(createReqVO.getCronExpression()); + o.setCronExpression("0 0/1 * * * ? *"); }); + // 调用 jobService.updateJob(updateReqVO); // 校验记录的属性是否正确 JobDO updateJob = jobMapper.selectById(updateReqVO.getId()); assertPojoEquals(updateReqVO, updateJob); // 校验调用 - verify(schedulerManager, times(1)).updateJob(eq(job.getHandlerName()), eq(updateReqVO.getHandlerParam()), eq(updateReqVO.getCronExpression()), - eq(updateReqVO.getRetryCount()), eq(updateReqVO.getRetryInterval())); + verify(schedulerManager).updateJob(eq(job.getHandlerName()), eq(updateReqVO.getHandlerParam()), + eq(updateReqVO.getCronExpression()), eq(updateReqVO.getRetryCount()), eq(updateReqVO.getRetryInterval())); } @Test public void testUpdateJobStatus_changeStatusInvalid() { // 调用,并断言异常 - assertServiceException(() -> jobService.updateJobStatus(1L, JobStatusEnum.INIT.getStatus()), JOB_CHANGE_STATUS_INVALID); + assertServiceException(() -> jobService.updateJobStatus(1L, JobStatusEnum.INIT.getStatus()), + JOB_CHANGE_STATUS_INVALID); } @Test public void testUpdateJobStatus_changeStatusEquals() { // mock 数据 - JobCreateReqVO createReqVO = randomPojo(JobCreateReqVO.class, o -> o.setCronExpression("0 0/1 * * * ? *")); - JobDO job = JobConvert.INSTANCE.convert(createReqVO); - job.setStatus(JobStatusEnum.NORMAL.getStatus()); - fillJobMonitorTimeoutEmpty(job); + JobDO job = randomPojo(JobDO.class, o -> o.setStatus(JobStatusEnum.NORMAL.getStatus())); jobMapper.insert(job); + // 调用,并断言异常 - assertServiceException(() -> jobService.updateJobStatus(job.getId(), job.getStatus()), JOB_CHANGE_STATUS_EQUALS); + assertServiceException(() -> jobService.updateJobStatus(job.getId(), job.getStatus()), + JOB_CHANGE_STATUS_EQUALS); } @Test - public void testUpdateJobStatus_NormalToStop_success() throws SchedulerException { + public void testUpdateJobStatus_stopSuccess() throws SchedulerException { // mock 数据 - JobCreateReqVO createReqVO = randomPojo(JobCreateReqVO.class, o -> o.setCronExpression("0 0/1 * * * ? *")); - JobDO job = JobConvert.INSTANCE.convert(createReqVO); - job.setStatus(JobStatusEnum.NORMAL.getStatus()); - fillJobMonitorTimeoutEmpty(job); + JobDO job = randomPojo(JobDO.class, o -> o.setStatus(JobStatusEnum.NORMAL.getStatus())); jobMapper.insert(job); + // 调用 jobService.updateJobStatus(job.getId(), JobStatusEnum.STOP.getStatus()); // 校验记录的属性是否正确 - JobDO updateJob = jobMapper.selectById(job.getId()); - assertEquals(JobStatusEnum.STOP.getStatus(), updateJob.getStatus()); + JobDO dbJob = jobMapper.selectById(job.getId()); + assertEquals(JobStatusEnum.STOP.getStatus(), dbJob.getStatus()); // 校验调用 - verify(schedulerManager, times(1)).pauseJob(eq(job.getHandlerName())); + verify(schedulerManager).pauseJob(eq(job.getHandlerName())); } @Test - public void testUpdateJobStatus_StopToNormal_success() throws SchedulerException { + public void testUpdateJobStatus_normalSuccess() throws SchedulerException { // mock 数据 - JobCreateReqVO createReqVO = randomPojo(JobCreateReqVO.class, o -> o.setCronExpression("0 0/1 * * * ? *")); - JobDO job = JobConvert.INSTANCE.convert(createReqVO); - job.setStatus(JobStatusEnum.STOP.getStatus()); - fillJobMonitorTimeoutEmpty(job); + JobDO job = randomPojo(JobDO.class, o -> o.setStatus(JobStatusEnum.STOP.getStatus())); jobMapper.insert(job); + // 调用 jobService.updateJobStatus(job.getId(), JobStatusEnum.NORMAL.getStatus()); // 校验记录的属性是否正确 - JobDO updateJob = jobMapper.selectById(job.getId()); - assertEquals(JobStatusEnum.NORMAL.getStatus(), updateJob.getStatus()); + JobDO dbJob = jobMapper.selectById(job.getId()); + assertEquals(JobStatusEnum.NORMAL.getStatus(), dbJob.getStatus()); // 校验调用 - verify(schedulerManager, times(1)).resumeJob(eq(job.getHandlerName())); + verify(schedulerManager).resumeJob(eq(job.getHandlerName())); } @Test public void testTriggerJob_success() throws SchedulerException { // mock 数据 - JobCreateReqVO createReqVO = randomPojo(JobCreateReqVO.class, o -> o.setCronExpression("0 0/1 * * * ? *")); - JobDO job = JobConvert.INSTANCE.convert(createReqVO); - job.setStatus(JobStatusEnum.NORMAL.getStatus()); - fillJobMonitorTimeoutEmpty(job); + JobDO job = randomPojo(JobDO.class); jobMapper.insert(job); + // 调用 jobService.triggerJob(job.getId()); // 校验调用 - verify(schedulerManager, times(1)).triggerJob(eq(job.getId()), eq(job.getHandlerName()), eq(job.getHandlerParam())); + verify(schedulerManager).triggerJob(eq(job.getId()), + eq(job.getHandlerName()), eq(job.getHandlerParam())); } @Test public void testDeleteJob_success() throws SchedulerException { // mock 数据 - JobCreateReqVO createReqVO = randomPojo(JobCreateReqVO.class, o -> o.setCronExpression("0 0/1 * * * ? *")); - JobDO job = JobConvert.INSTANCE.convert(createReqVO); - job.setStatus(JobStatusEnum.NORMAL.getStatus()); - fillJobMonitorTimeoutEmpty(job); + JobDO job = randomPojo(JobDO.class); jobMapper.insert(job); - // 调用 UPDATE inf_job SET deleted=1 WHERE id=? AND deleted=0 + + // 调用 jobService.deleteJob(job.getId()); - // 校验数据不存在了 WHERE id=? AND deleted=0 查询为空正常 + // 校验不存在 assertNull(jobMapper.selectById(job.getId())); // 校验调用 - verify(schedulerManager, times(1)).deleteJob(eq(job.getHandlerName())); + verify(schedulerManager).deleteJob(eq(job.getHandlerName())); } @Test - public void testGetJobListByIds_success() { + public void testGetJobList() { // mock 数据 JobDO dbJob = randomPojo(JobDO.class, o -> { o.setStatus(randomEle(JobStatusEnum.values()).getStatus()); // 保证 status 的范围 }); - JobDO cloneJob = ObjectUtils.cloneIgnoreId(dbJob, o -> o.setHandlerName(randomString())); jobMapper.insert(dbJob); - // 测试 handlerName 不匹配 - jobMapper.insert(cloneJob); + // 测试 id 不匹配 + jobMapper.insert(cloneIgnoreId(dbJob, o -> {})); + // 准备参数 - ArrayList ids = new ArrayList<>(); - ids.add(dbJob.getId()); - ids.add(cloneJob.getId()); + Collection ids = singletonList(dbJob.getId()); // 调用 List list = jobService.getJobList(ids); // 断言 - assertEquals(2, list.size()); + assertEquals(1, list.size()); assertPojoEquals(dbJob, list.get(0)); } @Test - public void testGetJobPage_success() { + public void testGetJobPage() { // mock 数据 JobDO dbJob = randomPojo(JobDO.class, o -> { o.setName("定时任务测试"); @@ -240,16 +229,17 @@ public class JobServiceTest extends BaseDbUnitTest { }); jobMapper.insert(dbJob); // 测试 name 不匹配 - jobMapper.insert(ObjectUtils.cloneIgnoreId(dbJob, o -> o.setName("土豆"))); + jobMapper.insert(cloneIgnoreId(dbJob, o -> o.setName("土豆"))); // 测试 status 不匹配 - jobMapper.insert(ObjectUtils.cloneIgnoreId(dbJob, o -> o.setStatus(JobStatusEnum.NORMAL.getStatus()))); + jobMapper.insert(cloneIgnoreId(dbJob, o -> o.setStatus(JobStatusEnum.NORMAL.getStatus()))); // 测试 handlerName 不匹配 - jobMapper.insert(ObjectUtils.cloneIgnoreId(dbJob, o -> o.setHandlerName(randomString()))); + jobMapper.insert(cloneIgnoreId(dbJob, o -> o.setHandlerName(randomString()))); // 准备参数 JobPageReqVO reqVo = new JobPageReqVO(); reqVo.setName("定时"); reqVo.setStatus(JobStatusEnum.INIT.getStatus()); reqVo.setHandlerName("单元"); + // 调用 PageResult pageResult = jobService.getJobPage(reqVo); // 断言 @@ -259,7 +249,7 @@ public class JobServiceTest extends BaseDbUnitTest { } @Test - public void testGetJobListForExport_success() { + public void testGetJobList_export() { // mock 数据 JobDO dbJob = randomPojo(JobDO.class, o -> { o.setName("定时任务测试"); @@ -268,16 +258,17 @@ public class JobServiceTest extends BaseDbUnitTest { }); jobMapper.insert(dbJob); // 测试 name 不匹配 - jobMapper.insert(ObjectUtils.cloneIgnoreId(dbJob, o -> o.setName("土豆"))); + jobMapper.insert(cloneIgnoreId(dbJob, o -> o.setName("土豆"))); // 测试 status 不匹配 - jobMapper.insert(ObjectUtils.cloneIgnoreId(dbJob, o -> o.setStatus(JobStatusEnum.NORMAL.getStatus()))); + jobMapper.insert(cloneIgnoreId(dbJob, o -> o.setStatus(JobStatusEnum.NORMAL.getStatus()))); // 测试 handlerName 不匹配 - jobMapper.insert(ObjectUtils.cloneIgnoreId(dbJob, o -> o.setHandlerName(randomString()))); + jobMapper.insert(cloneIgnoreId(dbJob, o -> o.setHandlerName(randomString()))); // 准备参数 JobExportReqVO reqVo = new JobExportReqVO(); reqVo.setName("定时"); reqVo.setStatus(JobStatusEnum.INIT.getStatus()); reqVo.setHandlerName("单元"); + // 调用 List list = jobService.getJobList(reqVo); // 断言 @@ -285,10 +276,15 @@ public class JobServiceTest extends BaseDbUnitTest { assertPojoEquals(dbJob, list.get(0)); } - private static void fillJobMonitorTimeoutEmpty(JobDO job) { - if (job.getMonitorTimeout() == null) { - job.setMonitorTimeout(0); - } + @Test + public void testGetJob() { + // mock 数据 + JobDO dbJob = randomPojo(JobDO.class); + jobMapper.insert(dbJob); + // 调用 + JobDO job = jobService.getJob(dbJob.getId()); + // 断言 + assertPojoEquals(dbJob, job); } } diff --git a/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/logger/ApiAccessLogServiceImplTest.java b/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/logger/ApiAccessLogServiceImplTest.java index b650fb603..8ff2dd9bf 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/logger/ApiAccessLogServiceImplTest.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/logger/ApiAccessLogServiceImplTest.java @@ -1,12 +1,9 @@ package cn.iocoder.yudao.module.infra.service.logger; -import cn.hutool.core.util.RandomUtil; import cn.iocoder.yudao.framework.common.enums.UserTypeEnum; import cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants; import cn.iocoder.yudao.framework.common.pojo.PageResult; -import cn.iocoder.yudao.framework.common.util.object.ObjectUtils; import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; -import cn.iocoder.yudao.framework.test.core.util.RandomUtils; import cn.iocoder.yudao.module.infra.api.logger.dto.ApiAccessLogCreateReqDTO; import cn.iocoder.yudao.module.infra.controller.admin.logger.vo.apiaccesslog.ApiAccessLogExportReqVO; import cn.iocoder.yudao.module.infra.controller.admin.logger.vo.apiaccesslog.ApiAccessLogPageReqVO; @@ -16,149 +13,121 @@ import org.junit.jupiter.api.Test; import org.springframework.context.annotation.Import; import javax.annotation.Resource; -import java.time.LocalDateTime; import java.util.List; +import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildBetweenTime; import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildTime; +import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; +import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; @Import(ApiAccessLogServiceImpl.class) public class ApiAccessLogServiceImplTest extends BaseDbUnitTest { @Resource - private ApiAccessLogService apiAccessLogService; + private ApiAccessLogServiceImpl apiAccessLogService; @Resource private ApiAccessLogMapper apiAccessLogMapper; @Test public void testGetApiAccessLogPage() { - // 构造测试数据 - long userId = 2233L; - int userType = UserTypeEnum.ADMIN.getValue(); - String applicationName = "yudao-test"; - String requestUrl = "foo"; - LocalDateTime beginTime = buildTime(2021, 3, 13); - int duration = 1000; - int resultCode = GlobalErrorCodeConstants.SUCCESS.getCode(); - - ApiAccessLogDO infApiAccessLogDO = RandomUtils.randomPojo(ApiAccessLogDO.class, dto -> { - dto.setUserId(userId); - dto.setUserType(userType); - dto.setApplicationName(applicationName); - dto.setRequestUrl(requestUrl); - dto.setBeginTime(beginTime); - dto.setDuration(duration); - dto.setResultCode(resultCode); + ApiAccessLogDO apiAccessLogDO = randomPojo(ApiAccessLogDO.class, o -> { + o.setUserId(2233L); + o.setUserType(UserTypeEnum.ADMIN.getValue()); + o.setApplicationName("yudao-test"); + o.setRequestUrl("foo"); + o.setBeginTime(buildTime(2021, 3, 13)); + o.setDuration(1000); + o.setResultCode(GlobalErrorCodeConstants.SUCCESS.getCode()); }); - apiAccessLogMapper.insert(infApiAccessLogDO); - - // 下面几个都是不匹配的数据 - // userId 不同的 - apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setUserId(3344L))); - // userType - apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setUserType(UserTypeEnum.MEMBER.getValue()))); - // applicationName 不同的 - apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setApplicationName("test"))); - // requestUrl 不同的 - apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setRequestUrl("bar"))); - // 构造一个早期时间 2021-02-06 00:00:00 - apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setBeginTime(buildTime(2021, 2, 6)))); - // duration 不同的 - apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setDuration(100))); - // resultCode 不同的 - apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setResultCode(2))); - - // 构造调用参数 + apiAccessLogMapper.insert(apiAccessLogDO); + // 测试 userId 不匹配 + apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setUserId(3344L))); + // 测试 userType 不匹配 + apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setUserType(UserTypeEnum.MEMBER.getValue()))); + // 测试 applicationName 不匹配 + apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setApplicationName("test"))); + // 测试 requestUrl 不匹配 + apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setRequestUrl("bar"))); + // 测试 beginTime 不匹配:构造一个早期时间 2021-02-06 00:00:00 + apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setBeginTime(buildTime(2021, 2, 6)))); + // 测试 duration 不匹配 + apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setDuration(100))); + // 测试 resultCode 不匹配 + apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setResultCode(2))); + // 准备参数 ApiAccessLogPageReqVO reqVO = new ApiAccessLogPageReqVO(); - reqVO.setUserId(userId); - reqVO.setUserType(userType); - reqVO.setApplicationName(applicationName); - reqVO.setRequestUrl(requestUrl); - reqVO.setBeginTime((new LocalDateTime[]{buildTime(2021, 3, 12),buildTime(2021, 3, 14)})); - reqVO.setDuration(duration); - reqVO.setResultCode(resultCode); + reqVO.setUserId(2233L); + reqVO.setUserType(UserTypeEnum.ADMIN.getValue()); + reqVO.setApplicationName("yudao-test"); + reqVO.setRequestUrl("foo"); + reqVO.setBeginTime(buildBetweenTime(2021, 3, 13, 2021, 3, 13)); + reqVO.setDuration(1000); + reqVO.setResultCode(GlobalErrorCodeConstants.SUCCESS.getCode()); - // 调用service方法 + // 调用 PageResult pageResult = apiAccessLogService.getApiAccessLogPage(reqVO); - // 断言,只查到了一条符合条件的 assertEquals(1, pageResult.getTotal()); assertEquals(1, pageResult.getList().size()); - assertPojoEquals(infApiAccessLogDO, pageResult.getList().get(0)); + assertPojoEquals(apiAccessLogDO, pageResult.getList().get(0)); } @Test public void testGetApiAccessLogList() { - // 构造测试数据 - long userId = 2233L; - int userType = UserTypeEnum.ADMIN.getValue(); - String applicationName = "yudao-test"; - String requestUrl = "foo"; - LocalDateTime beginTime = buildTime(2021, 3, 13); - int duration = 1000; - int resultCode = GlobalErrorCodeConstants.SUCCESS.getCode(); - - ApiAccessLogDO infApiAccessLogDO = RandomUtils.randomPojo(ApiAccessLogDO.class, dto -> { - dto.setUserId(userId); - dto.setUserType(userType); - dto.setApplicationName(applicationName); - dto.setRequestUrl(requestUrl); - dto.setBeginTime(beginTime); - dto.setDuration(duration); - dto.setResultCode(resultCode); + ApiAccessLogDO apiAccessLogDO = randomPojo(ApiAccessLogDO.class, o -> { + o.setUserId(2233L); + o.setUserType(UserTypeEnum.ADMIN.getValue()); + o.setApplicationName("yudao-test"); + o.setRequestUrl("foo"); + o.setBeginTime(buildTime(2021, 3, 13)); + o.setDuration(1000); + o.setResultCode(GlobalErrorCodeConstants.SUCCESS.getCode()); }); - apiAccessLogMapper.insert(infApiAccessLogDO); - - // 下面几个都是不匹配的数据 - // userId 不同的 - apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setUserId(3344L))); - // userType - apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setUserType(UserTypeEnum.MEMBER.getValue()))); - // applicationName 不同的 - apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setApplicationName("test"))); - // requestUrl 不同的 - apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setRequestUrl("bar"))); - // 构造一个早期时间 2021-02-06 00:00:00 - apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setBeginTime(buildTime(2021, 2, 6)))); - // duration 不同的 - apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setDuration(100))); - // resultCode 不同的 - apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setResultCode(2))); - - // 构造调用参数 + apiAccessLogMapper.insert(apiAccessLogDO); + // 测试 userId 不匹配 + apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setUserId(3344L))); + // 测试 userType 不匹配 + apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setUserType(UserTypeEnum.MEMBER.getValue()))); + // 测试 applicationName 不匹配 + apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setApplicationName("test"))); + // 测试 requestUrl 不匹配 + apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setRequestUrl("bar"))); + // 测试 beginTime 不匹配:构造一个早期时间 2021-02-06 00:00:00 + apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setBeginTime(buildTime(2021, 2, 6)))); + // 测试 duration 不匹配 + apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setDuration(100))); + // 测试 resultCode 不匹配 + apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setResultCode(2))); + // 准备参数 ApiAccessLogExportReqVO reqVO = new ApiAccessLogExportReqVO(); - reqVO.setUserId(userId); - reqVO.setUserType(userType); - reqVO.setApplicationName(applicationName); - reqVO.setRequestUrl(requestUrl); - reqVO.setBeginTime((new LocalDateTime[]{buildTime(2021, 3, 12),buildTime(2021, 3, 14)})); - reqVO.setDuration(duration); - reqVO.setResultCode(resultCode); + reqVO.setUserId(2233L); + reqVO.setUserType(UserTypeEnum.ADMIN.getValue()); + reqVO.setApplicationName("yudao-test"); + reqVO.setRequestUrl("foo"); + reqVO.setBeginTime(buildBetweenTime(2021, 3, 13, 2021, 3, 13)); + reqVO.setDuration(1000); + reqVO.setResultCode(GlobalErrorCodeConstants.SUCCESS.getCode()); - // 调用service方法 + // 调用 List list = apiAccessLogService.getApiAccessLogList(reqVO); - // 断言,只查到了一条符合条件的 assertEquals(1, list.size()); - assertPojoEquals(infApiAccessLogDO, list.get(0)); + assertPojoEquals(apiAccessLogDO, list.get(0)); } @Test - public void testCreateApiAccessLogAsync() { + public void testCreateApiAccessLog() { // 准备参数 - ApiAccessLogCreateReqDTO createDTO = RandomUtils.randomPojo(ApiAccessLogCreateReqDTO.class, - dto -> dto.setUserType(RandomUtil.randomEle(UserTypeEnum.values()).getValue())); + ApiAccessLogCreateReqDTO createDTO = randomPojo(ApiAccessLogCreateReqDTO.class); // 调用 apiAccessLogService.createApiAccessLog(createDTO); // 断言 - ApiAccessLogDO infApiAccessLogDO = apiAccessLogMapper.selectOne(null); - assertNotNull(infApiAccessLogDO); - assertPojoEquals(createDTO, infApiAccessLogDO); + ApiAccessLogDO apiAccessLogDO = apiAccessLogMapper.selectOne(null); + assertPojoEquals(createDTO, apiAccessLogDO); } - } diff --git a/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/logger/ApiErrorLogServiceImplTest.java b/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/logger/ApiErrorLogServiceImplTest.java index 4e35ba7ea..86e55f5d1 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/logger/ApiErrorLogServiceImplTest.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/logger/ApiErrorLogServiceImplTest.java @@ -1,28 +1,28 @@ package cn.iocoder.yudao.module.infra.service.logger; -import cn.hutool.core.util.RandomUtil; import cn.iocoder.yudao.framework.common.enums.UserTypeEnum; import cn.iocoder.yudao.framework.common.pojo.PageResult; -import cn.iocoder.yudao.framework.common.util.object.ObjectUtils; import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; -import cn.iocoder.yudao.framework.test.core.util.RandomUtils; import cn.iocoder.yudao.module.infra.api.logger.dto.ApiErrorLogCreateReqDTO; import cn.iocoder.yudao.module.infra.controller.admin.logger.vo.apierrorlog.ApiErrorLogExportReqVO; import cn.iocoder.yudao.module.infra.controller.admin.logger.vo.apierrorlog.ApiErrorLogPageReqVO; import cn.iocoder.yudao.module.infra.dal.dataobject.logger.ApiErrorLogDO; import cn.iocoder.yudao.module.infra.dal.mysql.logger.ApiErrorLogMapper; import cn.iocoder.yudao.module.infra.enums.logger.ApiErrorLogProcessStatusEnum; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.context.annotation.Import; import javax.annotation.Resource; -import java.time.LocalDateTime; import java.util.List; +import static cn.hutool.core.util.RandomUtil.randomEle; +import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildBetweenTime; import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildTime; +import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; +import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomLongId; +import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo; import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.API_ERROR_LOG_NOT_FOUND; import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.API_ERROR_LOG_PROCESSED; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -35,161 +35,150 @@ public class ApiErrorLogServiceImplTest extends BaseDbUnitTest { private ApiErrorLogServiceImpl apiErrorLogService; @Resource - private ApiErrorLogMapper infApiErrorLogMapper; + private ApiErrorLogMapper apiErrorLogMapper; @Test public void testGetApiErrorLogPage() { - // 构造测试数据 - long userId = 2233L; - int userType = UserTypeEnum.ADMIN.getValue(); - String applicationName = "yudao-test"; - String requestUrl = "foo"; - LocalDateTime beginTime = buildTime(2021, 3, 13); - int progressStatus = ApiErrorLogProcessStatusEnum.INIT.getStatus(); - - ApiErrorLogDO infApiErrorLogDO = RandomUtils.randomPojo(ApiErrorLogDO.class, logDO -> { - logDO.setUserId(userId); - logDO.setUserType(userType); - logDO.setApplicationName(applicationName); - logDO.setRequestUrl(requestUrl); - logDO.setExceptionTime(beginTime); - logDO.setProcessStatus(progressStatus); + // mock 数据 + ApiErrorLogDO apiErrorLogDO = randomPojo(ApiErrorLogDO.class, o -> { + o.setUserId(2233L); + o.setUserType(UserTypeEnum.ADMIN.getValue()); + o.setApplicationName("yudao-test"); + o.setRequestUrl("foo"); + o.setExceptionTime(buildTime(2021, 3, 13)); + o.setProcessStatus(ApiErrorLogProcessStatusEnum.INIT.getStatus()); }); - infApiErrorLogMapper.insert(infApiErrorLogDO); - - // 下面几个都是不匹配的数据 - // userId 不同的 - infApiErrorLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiErrorLogDO, logDO -> logDO.setUserId(3344L))); - // userType - infApiErrorLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiErrorLogDO, logDO -> logDO.setUserType(UserTypeEnum.MEMBER.getValue()))); - // applicationName 不同的 - infApiErrorLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiErrorLogDO, logDO -> logDO.setApplicationName("test"))); - // requestUrl 不同的 - infApiErrorLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiErrorLogDO, logDO -> logDO.setRequestUrl("bar"))); - // 构造一个早期时间 2021-02-06 00:00:00 - infApiErrorLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiErrorLogDO, logDO -> logDO.setExceptionTime(buildTime(2021, 2, 6)))); - // progressStatus 不同的 - infApiErrorLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiErrorLogDO, logDO -> logDO.setProcessStatus(ApiErrorLogProcessStatusEnum.DONE.getStatus()))); - - // 构造调用参数 + apiErrorLogMapper.insert(apiErrorLogDO); + // 测试 userId 不匹配 + apiErrorLogMapper.insert(cloneIgnoreId(apiErrorLogDO, o -> o.setUserId(3344L))); + // 测试 userType 不匹配 + apiErrorLogMapper.insert(cloneIgnoreId(apiErrorLogDO, logDO -> logDO.setUserType(UserTypeEnum.MEMBER.getValue()))); + // 测试 applicationName 不匹配 + apiErrorLogMapper.insert(cloneIgnoreId(apiErrorLogDO, logDO -> logDO.setApplicationName("test"))); + // 测试 requestUrl 不匹配 + apiErrorLogMapper.insert(cloneIgnoreId(apiErrorLogDO, logDO -> logDO.setRequestUrl("bar"))); + // 测试 exceptionTime 不匹配:构造一个早期时间 2021-02-06 00:00:00 + apiErrorLogMapper.insert(cloneIgnoreId(apiErrorLogDO, logDO -> logDO.setExceptionTime(buildTime(2021, 2, 6)))); + // 测试 progressStatus 不匹配 + apiErrorLogMapper.insert(cloneIgnoreId(apiErrorLogDO, logDO -> logDO.setProcessStatus(ApiErrorLogProcessStatusEnum.DONE.getStatus()))); + // 准备参数 ApiErrorLogPageReqVO reqVO = new ApiErrorLogPageReqVO(); - reqVO.setUserId(userId); - reqVO.setUserType(userType); - reqVO.setApplicationName(applicationName); - reqVO.setRequestUrl(requestUrl); - reqVO.setExceptionTime((new LocalDateTime[]{buildTime(2021, 3, 12),buildTime(2021, 3, 14)})); - reqVO.setProcessStatus(progressStatus); + reqVO.setUserId(2233L); + reqVO.setUserType(UserTypeEnum.ADMIN.getValue()); + reqVO.setApplicationName("yudao-test"); + reqVO.setRequestUrl("foo"); + reqVO.setExceptionTime(buildBetweenTime(2021, 3, 1, 2021, 3, 31)); + reqVO.setProcessStatus(ApiErrorLogProcessStatusEnum.INIT.getStatus()); - // 调用service方法 + // 调用 PageResult pageResult = apiErrorLogService.getApiErrorLogPage(reqVO); - // 断言,只查到了一条符合条件的 assertEquals(1, pageResult.getTotal()); assertEquals(1, pageResult.getList().size()); - assertPojoEquals(infApiErrorLogDO, pageResult.getList().get(0)); + assertPojoEquals(apiErrorLogDO, pageResult.getList().get(0)); } @Test public void testGetApiErrorLogList() { - // 构造测试数据 - long userId = 2233L; - int userType = UserTypeEnum.ADMIN.getValue(); - String applicationName = "yudao-test"; - String requestUrl = "foo"; - LocalDateTime beginTime = buildTime(2021, 3, 13); - int progressStatus = ApiErrorLogProcessStatusEnum.INIT.getStatus(); - - ApiErrorLogDO infApiErrorLogDO = RandomUtils.randomPojo(ApiErrorLogDO.class, logDO -> { - logDO.setUserId(userId); - logDO.setUserType(userType); - logDO.setApplicationName(applicationName); - logDO.setRequestUrl(requestUrl); - logDO.setExceptionTime(beginTime); - logDO.setProcessStatus(progressStatus); + // mock 数据 + ApiErrorLogDO apiErrorLogDO = randomPojo(ApiErrorLogDO.class, o -> { + o.setUserId(2233L); + o.setUserType(UserTypeEnum.ADMIN.getValue()); + o.setApplicationName("yudao-test"); + o.setRequestUrl("foo"); + o.setExceptionTime(buildTime(2021, 3, 13)); + o.setProcessStatus(ApiErrorLogProcessStatusEnum.INIT.getStatus()); }); - infApiErrorLogMapper.insert(infApiErrorLogDO); - - // 下面几个都是不匹配的数据 - // userId 不同的 - infApiErrorLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiErrorLogDO, logDO -> logDO.setUserId(3344L))); - // userType - infApiErrorLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiErrorLogDO, logDO -> logDO.setUserType(UserTypeEnum.MEMBER.getValue()))); - // applicationName 不同的 - infApiErrorLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiErrorLogDO, logDO -> logDO.setApplicationName("test"))); - // requestUrl 不同的 - infApiErrorLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiErrorLogDO, logDO -> logDO.setRequestUrl("bar"))); - // 构造一个早期时间 2021-02-06 00:00:00 - infApiErrorLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiErrorLogDO, logDO -> logDO.setExceptionTime(buildTime(2021, 2, 6)))); - // progressStatus 不同的 - infApiErrorLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiErrorLogDO, logDO -> logDO.setProcessStatus(ApiErrorLogProcessStatusEnum.DONE.getStatus()))); - - // 构造调用参数 + apiErrorLogMapper.insert(apiErrorLogDO); + // 测试 userId 不匹配 + apiErrorLogMapper.insert(cloneIgnoreId(apiErrorLogDO, o -> o.setUserId(3344L))); + // 测试 userType 不匹配 + apiErrorLogMapper.insert(cloneIgnoreId(apiErrorLogDO, logDO -> logDO.setUserType(UserTypeEnum.MEMBER.getValue()))); + // 测试 applicationName 不匹配 + apiErrorLogMapper.insert(cloneIgnoreId(apiErrorLogDO, logDO -> logDO.setApplicationName("test"))); + // 测试 requestUrl 不匹配 + apiErrorLogMapper.insert(cloneIgnoreId(apiErrorLogDO, logDO -> logDO.setRequestUrl("bar"))); + // 测试 exceptionTime 不匹配:构造一个早期时间 2021-02-06 00:00:00 + apiErrorLogMapper.insert(cloneIgnoreId(apiErrorLogDO, logDO -> logDO.setExceptionTime(buildTime(2021, 2, 6)))); + // 测试 progressStatus 不匹配 + apiErrorLogMapper.insert(cloneIgnoreId(apiErrorLogDO, logDO -> logDO.setProcessStatus(ApiErrorLogProcessStatusEnum.DONE.getStatus()))); + // 准备参数 ApiErrorLogExportReqVO reqVO = new ApiErrorLogExportReqVO(); - reqVO.setUserId(userId); - reqVO.setUserType(userType); - reqVO.setApplicationName(applicationName); - reqVO.setRequestUrl(requestUrl); - reqVO.setExceptionTime((new LocalDateTime[]{buildTime(2021, 3, 12),buildTime(2021, 3, 14)})); - reqVO.setProcessStatus(progressStatus); + reqVO.setUserId(2233L); + reqVO.setUserType(UserTypeEnum.ADMIN.getValue()); + reqVO.setApplicationName("yudao-test"); + reqVO.setRequestUrl("foo"); + reqVO.setExceptionTime(buildBetweenTime(2021, 3, 1, 2021, 3, 31)); + reqVO.setProcessStatus(ApiErrorLogProcessStatusEnum.INIT.getStatus()); - // 调用service方法 + // 调用 List list = apiErrorLogService.getApiErrorLogList(reqVO); - // 断言,只查到了一条符合条件的 assertEquals(1, list.size()); - assertPojoEquals(infApiErrorLogDO, list.get(0)); - } - - - // TODO 芋艿:单元测试,可以拆小一点 - @Test - public void testUpdateApiErrorLogProcess() { - // 先构造两条数据,第一条用于抛出异常,第二条用于正常的执行update操作 - Long processUserId = 2233L; - - ApiErrorLogDO first = RandomUtils.randomPojo(ApiErrorLogDO.class, logDO -> { - logDO.setProcessUserId(processUserId); - logDO.setUserType(UserTypeEnum.ADMIN.getValue()); - logDO.setProcessStatus(ApiErrorLogProcessStatusEnum.DONE.getStatus()); - }); - infApiErrorLogMapper.insert(first); - - ApiErrorLogDO second = RandomUtils.randomPojo(ApiErrorLogDO.class, logDO -> { - logDO.setProcessUserId(1122L); - logDO.setUserType(UserTypeEnum.ADMIN.getValue()); - logDO.setProcessStatus(ApiErrorLogProcessStatusEnum.INIT.getStatus()); - }); - infApiErrorLogMapper.insert(second); - - Long firstId = first.getId(); - Long secondId = second.getId(); - - // 执行正常的 update 操作 - apiErrorLogService.updateApiErrorLogProcess(secondId, ApiErrorLogProcessStatusEnum.DONE.getStatus(), processUserId); - ApiErrorLogDO secondSelect = infApiErrorLogMapper.selectOne("id", secondId); - - // id 为 0 查询不到,应该抛出异常 API_ERROR_LOG_NOT_FOUND - assertServiceException(() -> apiErrorLogService.updateApiErrorLogProcess(0L, ApiErrorLogProcessStatusEnum.DONE.getStatus(), processUserId), API_ERROR_LOG_NOT_FOUND); - // id 为 first 的 progressStatus 为 DONE ,应该抛出 API_ERROR_LOG_PROCESSED - assertServiceException(() -> apiErrorLogService.updateApiErrorLogProcess(firstId, ApiErrorLogProcessStatusEnum.DONE.getStatus(), processUserId), API_ERROR_LOG_PROCESSED); - // 验证 progressStatus 是否修改成功 - Assertions.assertEquals(ApiErrorLogProcessStatusEnum.DONE.getStatus(), secondSelect.getProcessStatus()); - // 验证 progressUserId 是否修改成功 - Assertions.assertEquals(processUserId, secondSelect.getProcessUserId()); + assertPojoEquals(apiErrorLogDO, list.get(0)); } @Test - public void testCreateApiErrorLogAsync() { + public void testCreateApiErrorLog() { // 准备参数 - ApiErrorLogCreateReqDTO createDTO = RandomUtils.randomPojo(ApiErrorLogCreateReqDTO.class, - dto -> dto.setUserType(RandomUtil.randomEle(UserTypeEnum.values()).getValue())); + ApiErrorLogCreateReqDTO createDTO = randomPojo(ApiErrorLogCreateReqDTO.class); // 调用 apiErrorLogService.createApiErrorLog(createDTO); // 断言 - ApiErrorLogDO infApiErrorLogDO = infApiErrorLogMapper.selectOne(null); - assertNotNull(infApiErrorLogDO); - assertPojoEquals(createDTO, infApiErrorLogDO); + ApiErrorLogDO apiErrorLogDO = apiErrorLogMapper.selectOne(null); + assertPojoEquals(createDTO, apiErrorLogDO); + assertEquals(ApiErrorLogProcessStatusEnum.INIT.getStatus(), apiErrorLogDO.getProcessStatus()); + } + + @Test + public void testUpdateApiErrorLogProcess_success() { + // 准备参数 + ApiErrorLogDO apiErrorLogDO = randomPojo(ApiErrorLogDO.class, + o -> o.setProcessStatus(ApiErrorLogProcessStatusEnum.INIT.getStatus())); + apiErrorLogMapper.insert(apiErrorLogDO); + // 准备参数 + Long id = apiErrorLogDO.getId(); + Integer processStatus = randomEle(ApiErrorLogProcessStatusEnum.values()).getStatus(); + Long processUserId = randomLongId(); + + // 调用 + apiErrorLogService.updateApiErrorLogProcess(id, processStatus, processUserId); + // 断言 + ApiErrorLogDO dbApiErrorLogDO = apiErrorLogMapper.selectById(apiErrorLogDO.getId()); + assertEquals(processStatus, dbApiErrorLogDO.getProcessStatus()); + assertEquals(processUserId, dbApiErrorLogDO.getProcessUserId()); + assertNotNull(dbApiErrorLogDO.getProcessTime()); + } + + @Test + public void testUpdateApiErrorLogProcess_processed() { + // 准备参数 + ApiErrorLogDO apiErrorLogDO = randomPojo(ApiErrorLogDO.class, + o -> o.setProcessStatus(ApiErrorLogProcessStatusEnum.DONE.getStatus())); + apiErrorLogMapper.insert(apiErrorLogDO); + // 准备参数 + Long id = apiErrorLogDO.getId(); + Integer processStatus = randomEle(ApiErrorLogProcessStatusEnum.values()).getStatus(); + Long processUserId = randomLongId(); + + // 调用,并断言异常 + assertServiceException(() -> + apiErrorLogService.updateApiErrorLogProcess(id, processStatus, processUserId), + API_ERROR_LOG_PROCESSED); + } + + @Test + public void testUpdateApiErrorLogProcess_notFound() { + // 准备参数 + Long id = randomLongId(); + Integer processStatus = randomEle(ApiErrorLogProcessStatusEnum.values()).getStatus(); + Long processUserId = randomLongId(); + + // 调用,并断言异常 + assertServiceException(() -> + apiErrorLogService.updateApiErrorLogProcess(id, processStatus, processUserId), + API_ERROR_LOG_NOT_FOUND); } } diff --git a/yudao-module-infra/yudao-module-infra-biz/src/test/resources/sql/clean.sql b/yudao-module-infra/yudao-module-infra-biz/src/test/resources/sql/clean.sql index eb05d3d5a..3dc20f7ba 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/test/resources/sql/clean.sql +++ b/yudao-module-infra/yudao-module-infra-biz/src/test/resources/sql/clean.sql @@ -1,12 +1,10 @@ DELETE FROM "infra_config"; +DELETE FROM "infra_file_config"; DELETE FROM "infra_file"; DELETE FROM "infra_job"; DELETE FROM "infra_job_log"; DELETE FROM "infra_api_access_log"; DELETE FROM "infra_api_error_log"; -DELETE FROM "infra_api_access_log"; -DELETE FROM "infra_file"; -DELETE FROM "infra_api_error_log"; -DELETE FROM "infra_test_demo"; DELETE FROM "infra_file_config"; +DELETE FROM "infra_test_demo"; DELETE FROM "infra_data_source_config"; diff --git a/yudao-module-infra/yudao-module-infra-biz/src/test/resources/sql/create_tables.sql b/yudao-module-infra/yudao-module-infra-biz/src/test/resources/sql/create_tables.sql index 5825e0fef..e076ca895 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/test/resources/sql/create_tables.sql +++ b/yudao-module-infra/yudao-module-infra-biz/src/test/resources/sql/create_tables.sql @@ -1,9 +1,9 @@ CREATE TABLE IF NOT EXISTS "infra_config" ( - "id" bigint(20) NOT NULL GENERATED BY DEFAULT AS IDENTITY, + "id" bigint(20) NOT NULL GENERATED BY DEFAULT AS IDENTITY COMMENT '编号', "category" varchar(50) NOT NULL, "type" tinyint NOT NULL, - "name" varchar(100) NOT NULL DEFAULT '', + "name" varchar(100) NOT NULL DEFAULT '' COMMENT '名字', "config_key" varchar(100) NOT NULL DEFAULT '', "value" varchar(500) NOT NULL DEFAULT '', "visible" bit NOT NULL, @@ -85,19 +85,6 @@ CREATE TABLE IF NOT EXISTS "infra_job_log" ( PRIMARY KEY ("id") )COMMENT='定时任务日志表'; -CREATE TABLE IF NOT EXISTS "inf_file" ( - "id" varchar(188) NOT NULL, - "type" varchar(63) DEFAULT NULL, - "content" blob NOT NULL, - "creator" varchar(64) DEFAULT '', - "create_time" timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - "updater" varchar(64) DEFAULT '', - "update_time" timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - "deleted" bit NOT NULL DEFAULT FALSE, - "tenant_id" bigint not null default '0', - PRIMARY KEY ("id") - ) COMMENT '文件表'; - CREATE TABLE IF NOT EXISTS "infra_api_access_log" ( "id" bigint not null GENERATED BY DEFAULT AS IDENTITY, "trace_id" varchar(64) not null default '', diff --git a/yudao-module-mall/yudao-module-product-biz/src/test/resources/sql/clean.sql b/yudao-module-mall/yudao-module-product-biz/src/test/resources/sql/clean.sql new file mode 100644 index 000000000..2a45ce1bd --- /dev/null +++ b/yudao-module-mall/yudao-module-product-biz/src/test/resources/sql/clean.sql @@ -0,0 +1,7 @@ +DELETE FROM "product_sku"; +DELETE FROM "product_spu"; +DELETE FROM "product_category"; + + + + diff --git a/yudao-module-mall/yudao-module-product-biz/src/test/resources/sql/create_tables.sql b/yudao-module-mall/yudao-module-product-biz/src/test/resources/sql/create_tables.sql new file mode 100644 index 000000000..6b0ffc7c7 --- /dev/null +++ b/yudao-module-mall/yudao-module-product-biz/src/test/resources/sql/create_tables.sql @@ -0,0 +1,68 @@ +CREATE TABLE IF NOT EXISTS `product_sku` ( + `id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键', + `spu_id` bigint NOT NULL COMMENT 'spu编号', + `spu_name` varchar DEFAULT NULL COMMENT '商品 SPU 名字', + `properties` varchar DEFAULT NULL COMMENT '规格值数组-json格式, [{propertId: , valueId: }, {propertId: , valueId: }]', + `price` int NOT NULL DEFAULT '-1' COMMENT '销售价格,单位:分', + `market_price` int DEFAULT NULL COMMENT '市场价', + `cost_price` int NOT NULL DEFAULT '-1' COMMENT '成本价,单位: 分', + `pic_url` varchar NOT NULL COMMENT '图片地址', + `stock` int DEFAULT NULL COMMENT '库存', + `warn_stock` int DEFAULT NULL COMMENT '预警库存', + `volume` double DEFAULT NULL COMMENT '商品体积', + `weight` double DEFAULT NULL COMMENT '商品重量', + `bar_code` varchar DEFAULT NULL COMMENT '条形码', + `status` tinyint DEFAULT NULL COMMENT '状态: 0-正常 1-禁用', + `create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + `creator` varchar DEFAULT NULL COMMENT '创建人', + `updater` varchar DEFAULT NULL COMMENT '更新人', + `deleted` bit(1) NOT NULL DEFAULT 0 COMMENT '是否删除', + PRIMARY KEY (`id`) +) COMMENT '商品sku'; + +CREATE TABLE IF NOT EXISTS `product_spu` ( + `id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键', + `tenant_id` bigint NOT NULL DEFAULT '0' COMMENT '租户编号', + `brand_id` bigint DEFAULT NULL COMMENT '商品品牌编号', + `category_id` bigint NOT NULL COMMENT '分类id', + `spec_type` int NOT NULL COMMENT '规格类型:0 单规格 1 多规格', + `code` varchar(128) DEFAULT NULL COMMENT '商品编码', + `name` varchar(128) NOT NULL COMMENT '商品名称', + `sell_point` varchar(128) DEFAULT NULL COMMENT '卖点', + `description` text COMMENT '描述', + `pic_urls` varchar(1024) DEFAULT '' COMMENT '商品轮播图地址数组,以逗号分隔最多上传15张', + `video_url` varchar(128) DEFAULT NULL COMMENT '商品视频', + `market_price` int DEFAULT NULL COMMENT '市场价,单位使用:分', + `min_price` int DEFAULT NULL COMMENT '最小价格,单位使用:分', + `max_price` int DEFAULT NULL COMMENT '最大价格,单位使用:分', + `total_stock` int NOT NULL DEFAULT '0' COMMENT '总库存', + `show_stock` int DEFAULT '0' COMMENT '是否展示库存', + `sales_count` int DEFAULT '0' COMMENT '商品销量', + `virtual_sales_count` int DEFAULT '0' COMMENT '虚拟销量', + `click_count` int DEFAULT '0' COMMENT '商品点击量', + `status` bit(1) DEFAULT NULL COMMENT '上下架状态: 0 上架(开启) 1 下架(禁用)-1 回收', + `sort` int NOT NULL DEFAULT '0' COMMENT '排序字段', + `create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + `creator` varchar DEFAULT NULL COMMENT '创建人', + `updater` varchar DEFAULT NULL COMMENT '更新人', + `deleted` bit(1) NOT NULL DEFAULT 0 COMMENT '是否删除', +PRIMARY KEY (`id`) +) COMMENT '商品spu'; + +CREATE TABLE IF NOT EXISTS `product_category` ( + `id` bigint NOT NULL AUTO_INCREMENT COMMENT '分类编号', + `parent_id` bigint DEFAULT NULL COMMENT '父分类编号', + `name` varchar(128) NOT NULL COMMENT '分类名称', + `description` varchar(128) NOT NULL COMMENT '分类描述', + `pic_url` varchar DEFAULT NULL COMMENT '分类图片', + `sort` int NOT NULL DEFAULT '0' COMMENT '排序字段', + `status` bit(1) DEFAULT NULL COMMENT '状态', + `create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + `creator` varchar DEFAULT NULL COMMENT '创建人', + `updater` varchar DEFAULT NULL COMMENT '更新人', + `deleted` bit(1) NOT NULL DEFAULT 0 COMMENT '是否删除', + PRIMARY KEY (`id`) +) COMMENT '商品分类'; diff --git a/yudao-module-member/yudao-module-member-biz/src/test/resources/sql/create_tables.sql b/yudao-module-member/yudao-module-member-biz/src/test/resources/sql/create_tables.sql index b0347b058..9724c80d6 100644 --- a/yudao-module-member/yudao-module-member-biz/src/test/resources/sql/create_tables.sql +++ b/yudao-module-member/yudao-module-member-biz/src/test/resources/sql/create_tables.sql @@ -17,19 +17,6 @@ CREATE TABLE IF NOT EXISTS "member_user" ( PRIMARY KEY ("id") ) COMMENT '会员表'; --- inf 开头的 DB -CREATE TABLE IF NOT EXISTS "inf_file" ( - "id" varchar(188) NOT NULL, - "type" varchar(63) DEFAULT NULL, - "content" blob NOT NULL, - "creator" varchar(64) DEFAULT '', - "create_time" timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - "updater" varchar(64) DEFAULT '', - "update_time" timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - "deleted" bit NOT NULL DEFAULT FALSE, - PRIMARY KEY ("id") -) COMMENT '文件表'; - CREATE TABLE IF NOT EXISTS "member_address" ( "id" bigint(20) NOT NULL GENERATED BY DEFAULT AS IDENTITY, "user_id" bigint(20) NOT NULL, diff --git a/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/dept/DeptApi.java b/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/dept/DeptApi.java index c9b456b90..c3d143e46 100644 --- a/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/dept/DeptApi.java +++ b/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/dept/DeptApi.java @@ -29,7 +29,7 @@ public interface DeptApi { * @param ids 部门编号数组 * @return 部门信息数组 */ - List getDepts(Collection ids); + List getDeptList(Collection ids); /** * 校验部门们是否有效。如下情况,视为无效: @@ -38,7 +38,7 @@ public interface DeptApi { * * @param ids 角色编号数组 */ - void validDepts(Collection ids); + void validateDeptList(Collection ids); /** * 获得指定编号的部门 Map @@ -47,7 +47,7 @@ public interface DeptApi { * @return 部门 Map */ default Map getDeptMap(Set ids) { - List list = getDepts(ids); + List list = getDeptList(ids); return CollectionUtils.convertMap(list, DeptRespDTO::getId); } diff --git a/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/dept/PostApi.java b/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/dept/PostApi.java index d1e3d47a1..57db07cc2 100644 --- a/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/dept/PostApi.java +++ b/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/dept/PostApi.java @@ -16,6 +16,6 @@ public interface PostApi { * * @param ids 岗位编号数组 */ - void validPosts(Collection ids); + void validPostList(Collection ids); } diff --git a/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/dict/DictDataApi.java b/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/dict/DictDataApi.java index 5ba3dfd75..3bc28c89e 100644 --- a/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/dict/DictDataApi.java +++ b/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/dict/DictDataApi.java @@ -19,7 +19,7 @@ public interface DictDataApi { * @param dictType 字典类型 * @param values 字典数据值的数组 */ - void validDictDatas(String dictType, Collection values); + void validateDictDataList(String dictType, Collection values); /** * 获得指定的字典数据,从缓存中 diff --git a/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/errorcode/ErrorCodeApi.java b/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/errorcode/ErrorCodeApi.java index b41728d40..6f6bc24c7 100644 --- a/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/errorcode/ErrorCodeApi.java +++ b/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/errorcode/ErrorCodeApi.java @@ -19,7 +19,7 @@ public interface ErrorCodeApi { * * @param autoGenerateDTOs 错误码信息 */ - void autoGenerateErrorCodes(@Valid List autoGenerateDTOs); + void autoGenerateErrorCodeList(@Valid List autoGenerateDTOs); /** * 增量获得错误码数组 diff --git a/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/permission/RoleApi.java b/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/permission/RoleApi.java index 14133e9d9..309c9ef6e 100644 --- a/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/permission/RoleApi.java +++ b/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/permission/RoleApi.java @@ -16,6 +16,6 @@ public interface RoleApi { * * @param ids 角色编号数组 */ - void validRoles(Collection ids); + void validRoleList(Collection ids); } diff --git a/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/sms/SmsCodeApi.java b/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/sms/SmsCodeApi.java index ffcf46dc0..98d4cdeef 100644 --- a/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/sms/SmsCodeApi.java +++ b/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/sms/SmsCodeApi.java @@ -1,7 +1,7 @@ package cn.iocoder.yudao.module.system.api.sms; import cn.iocoder.yudao.framework.common.exception.ServiceException; -import cn.iocoder.yudao.module.system.api.sms.dto.code.SmsCodeCheckReqDTO; +import cn.iocoder.yudao.module.system.api.sms.dto.code.SmsCodeValidateReqDTO; import cn.iocoder.yudao.module.system.api.sms.dto.code.SmsCodeSendReqDTO; import cn.iocoder.yudao.module.system.api.sms.dto.code.SmsCodeUseReqDTO; @@ -35,6 +35,6 @@ public interface SmsCodeApi { * * @param reqDTO 校验请求 */ - void checkSmsCode(@Valid SmsCodeCheckReqDTO reqDTO); + void validateSmsCode(@Valid SmsCodeValidateReqDTO reqDTO); } diff --git a/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/sms/dto/code/SmsCodeCheckReqDTO.java b/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/sms/dto/code/SmsCodeValidateReqDTO.java similarity index 95% rename from yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/sms/dto/code/SmsCodeCheckReqDTO.java rename to yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/sms/dto/code/SmsCodeValidateReqDTO.java index 92895bb4d..e7808354c 100644 --- a/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/sms/dto/code/SmsCodeCheckReqDTO.java +++ b/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/sms/dto/code/SmsCodeValidateReqDTO.java @@ -14,7 +14,7 @@ import javax.validation.constraints.NotNull; * @author 芋道源码 */ @Data -public class SmsCodeCheckReqDTO { +public class SmsCodeValidateReqDTO { /** * 手机号 diff --git a/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/tenant/TenantApi.java b/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/tenant/TenantApi.java index 3f255d55a..1fad83ed6 100644 --- a/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/tenant/TenantApi.java +++ b/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/tenant/TenantApi.java @@ -14,13 +14,13 @@ public interface TenantApi { * * @return 租户编号数组 */ - List getTenantIds(); + List getTenantIdList(); /** * 校验租户是否合法 * * @param id 租户编号 */ - void validTenant(Long id); + void validateTenant(Long id); } diff --git a/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/user/AdminUserApi.java b/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/user/AdminUserApi.java index 6c0b7e9d9..35e11f02d 100644 --- a/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/user/AdminUserApi.java +++ b/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/user/AdminUserApi.java @@ -6,7 +6,6 @@ import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO; import java.util.Collection; import java.util.List; import java.util.Map; -import java.util.Set; /** * Admin 用户 API 接口 @@ -29,7 +28,7 @@ public interface AdminUserApi { * @param ids 用户 ID 们 * @return 用户对象信息 */ - List getUsers(Collection ids); + List getUserList(Collection ids); /** * 获得指定部门的用户数组 @@ -37,7 +36,7 @@ public interface AdminUserApi { * @param deptIds 部门数组 * @return 用户数组 */ - List getUsersByDeptIds(Collection deptIds); + List getUserListByDeptIds(Collection deptIds); /** * 获得指定岗位的用户数组 @@ -54,7 +53,7 @@ public interface AdminUserApi { * @return 用户 Map */ default Map getUserMap(Collection ids) { - List users = getUsers(ids); + List users = getUserList(ids); return CollectionUtils.convertMap(users, AdminUserRespDTO::getId); } @@ -65,6 +64,6 @@ public interface AdminUserApi { * * @param ids 用户编号数组 */ - void validUsers(Set ids); + void validateUserList(Collection ids); } diff --git a/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/enums/ErrorCodeConstants.java b/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/enums/ErrorCodeConstants.java index b108ca775..8a54ba92e 100644 --- a/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/enums/ErrorCodeConstants.java +++ b/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/enums/ErrorCodeConstants.java @@ -50,7 +50,7 @@ public interface ErrorCodeConstants { ErrorCode DEPT_EXITS_CHILDREN = new ErrorCode(1002004003, "存在子部门,无法删除"); ErrorCode DEPT_PARENT_ERROR = new ErrorCode(1002004004, "不能设置自己为父部门"); ErrorCode DEPT_EXISTS_USER = new ErrorCode(1002004005, "部门中存在员工,无法删除"); - ErrorCode DEPT_NOT_ENABLE = new ErrorCode(1002004006, "部门不处于开启状态,不允许选择"); + ErrorCode DEPT_NOT_ENABLE = new ErrorCode(1002004006, "部门({})不处于开启状态,不允许选择"); ErrorCode DEPT_PARENT_IS_CHILD = new ErrorCode(1002004007, "不能设置自己的子部门为父部门"); // ========== 岗位模块 1002005000 ========== diff --git a/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/enums/permission/MenuIdEnum.java b/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/enums/permission/MenuIdEnum.java deleted file mode 100644 index fc2b72ac4..000000000 --- a/yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/enums/permission/MenuIdEnum.java +++ /dev/null @@ -1,20 +0,0 @@ -package cn.iocoder.yudao.module.system.enums.permission; - -import lombok.AllArgsConstructor; -import lombok.Getter; - -/** - * Menu 编号枚举 - */ -@Getter -@AllArgsConstructor -public enum MenuIdEnum { - - /** - * 根节点 - */ - ROOT(0L); - - private final Long id; - -} diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/dept/DeptApiImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/dept/DeptApiImpl.java index 5721030bb..c1676ca53 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/dept/DeptApiImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/dept/DeptApiImpl.java @@ -28,14 +28,14 @@ public class DeptApiImpl implements DeptApi { } @Override - public List getDepts(Collection ids) { - List depts = deptService.getDepts(ids); + public List getDeptList(Collection ids) { + List depts = deptService.getDeptList(ids); return DeptConvert.INSTANCE.convertList03(depts); } @Override - public void validDepts(Collection ids) { - deptService.validDepts(ids); + public void validateDeptList(Collection ids) { + deptService.validateDeptList(ids); } } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/dept/PostApiImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/dept/PostApiImpl.java index 9454193e7..3d8cdf997 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/dept/PostApiImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/dept/PostApiImpl.java @@ -18,7 +18,8 @@ public class PostApiImpl implements PostApi { private PostService postService; @Override - public void validPosts(Collection ids) { - postService.validPosts(ids); + public void validPostList(Collection ids) { + postService.validatePostList(ids); } + } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/dict/DictDataApiImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/dict/DictDataApiImpl.java index 7de1a43b3..e88771fa7 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/dict/DictDataApiImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/dict/DictDataApiImpl.java @@ -21,8 +21,8 @@ public class DictDataApiImpl implements DictDataApi { private DictDataService dictDataService; @Override - public void validDictDatas(String dictType, Collection values) { - dictDataService.validDictDatas(dictType, values); + public void validateDictDataList(String dictType, Collection values) { + dictDataService.validateDictDataList(dictType, values); } @Override diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/errorcode/ErrorCodeApiImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/errorcode/ErrorCodeApiImpl.java index b68c63215..c9c5f7029 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/errorcode/ErrorCodeApiImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/errorcode/ErrorCodeApiImpl.java @@ -21,7 +21,7 @@ public class ErrorCodeApiImpl implements ErrorCodeApi { private ErrorCodeService errorCodeService; @Override - public void autoGenerateErrorCodes(List autoGenerateDTOs) { + public void autoGenerateErrorCodeList(List autoGenerateDTOs) { errorCodeService.autoGenerateErrorCodes(autoGenerateDTOs); } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/permission/RoleApiImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/permission/RoleApiImpl.java index 2c4f94737..d8622a29a 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/permission/RoleApiImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/permission/RoleApiImpl.java @@ -18,7 +18,7 @@ public class RoleApiImpl implements RoleApi { private RoleService roleService; @Override - public void validRoles(Collection ids) { - roleService.validRoles(ids); + public void validRoleList(Collection ids) { + roleService.validateRoleList(ids); } } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/sms/SmsCodeApiImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/sms/SmsCodeApiImpl.java index 81957e082..23c5e4b3f 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/sms/SmsCodeApiImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/sms/SmsCodeApiImpl.java @@ -1,6 +1,6 @@ package cn.iocoder.yudao.module.system.api.sms; -import cn.iocoder.yudao.module.system.api.sms.dto.code.SmsCodeCheckReqDTO; +import cn.iocoder.yudao.module.system.api.sms.dto.code.SmsCodeValidateReqDTO; import cn.iocoder.yudao.module.system.api.sms.dto.code.SmsCodeSendReqDTO; import cn.iocoder.yudao.module.system.api.sms.dto.code.SmsCodeUseReqDTO; import cn.iocoder.yudao.module.system.service.sms.SmsCodeService; @@ -32,8 +32,8 @@ public class SmsCodeApiImpl implements SmsCodeApi { } @Override - public void checkSmsCode(SmsCodeCheckReqDTO reqDTO) { - smsCodeService.checkSmsCode(reqDTO); + public void validateSmsCode(SmsCodeValidateReqDTO reqDTO) { + smsCodeService.validateSmsCode(reqDTO); } } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/tenant/TenantApiImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/tenant/TenantApiImpl.java index 6ea4c795e..25ea260c5 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/tenant/TenantApiImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/tenant/TenantApiImpl.java @@ -18,12 +18,12 @@ public class TenantApiImpl implements TenantApi { private TenantService tenantService; @Override - public List getTenantIds() { - return tenantService.getTenantIds(); + public List getTenantIdList() { + return tenantService.getTenantIdList(); } @Override - public void validTenant(Long id) { + public void validateTenant(Long id) { tenantService.validTenant(id); } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/user/AdminUserApiImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/user/AdminUserApiImpl.java index d493b747a..2271420c4 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/user/AdminUserApiImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/user/AdminUserApiImpl.java @@ -9,7 +9,6 @@ import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.Collection; import java.util.List; -import java.util.Set; /** * Admin 用户 API 实现类 @@ -29,26 +28,26 @@ public class AdminUserApiImpl implements AdminUserApi { } @Override - public List getUsers(Collection ids) { - List users = userService.getUsers(ids); + public List getUserList(Collection ids) { + List users = userService.getUserList(ids); return UserConvert.INSTANCE.convertList4(users); } @Override - public List getUsersByDeptIds(Collection deptIds) { - List users = userService.getUsersByDeptIds(deptIds); + public List getUserListByDeptIds(Collection deptIds) { + List users = userService.getUserListByDeptIds(deptIds); return UserConvert.INSTANCE.convertList4(users); } @Override public List getUsersByPostIds(Collection postIds) { - List users = userService.getUsersByPostIds(postIds); + List users = userService.getUserListByPostIds(postIds); return UserConvert.INSTANCE.convertList4(users); } @Override - public void validUsers(Set ids) { - userService.validUsers(ids); + public void validateUserList(Collection ids) { + userService.validateUserList(ids); } } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/auth/AuthController.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/auth/AuthController.java index 6acceae52..7ef7012cc 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/auth/AuthController.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/auth/AuthController.java @@ -97,7 +97,7 @@ public class AuthController { } // 获得角色列表 Set roleIds = permissionService.getUserRoleIdsFromCache(getLoginUserId(), singleton(CommonStatusEnum.ENABLE.getStatus())); - List roleList = roleService.getRolesFromCache(roleIds); + List roleList = roleService.getRoleListFromCache(roleIds); // 获得菜单列表 List menuList = permissionService.getRoleMenuListFromCache(roleIds, SetUtils.asSet(MenuTypeEnum.DIR.getType(), MenuTypeEnum.MENU.getType(), MenuTypeEnum.BUTTON.getType()), @@ -108,7 +108,7 @@ public class AuthController { @GetMapping("/list-menus") @Operation(summary = "获得登录用户的菜单列表") - public CommonResult> getMenus() { + public CommonResult> getMenuList() { // 获得角色列表 Set roleIds = permissionService.getUserRoleIdsFromCache(getLoginUserId(), singleton(CommonStatusEnum.ENABLE.getStatus())); // 获得用户拥有的菜单列表 diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/dept/DeptController.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/dept/DeptController.java index 7c9338c40..906ab646a 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/dept/DeptController.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/dept/DeptController.java @@ -57,19 +57,19 @@ public class DeptController { @GetMapping("/list") @Operation(summary = "获取部门列表") @PreAuthorize("@ss.hasPermission('system:dept:query')") - public CommonResult> listDepts(DeptListReqVO reqVO) { - List list = deptService.getSimpleDepts(reqVO); + public CommonResult> getDeptList(DeptListReqVO reqVO) { + List list = deptService.getDeptList(reqVO); list.sort(Comparator.comparing(DeptDO::getSort)); return success(DeptConvert.INSTANCE.convertList(list)); } @GetMapping("/list-all-simple") @Operation(summary = "获取部门精简信息列表", description = "只包含被开启的部门,主要用于前端的下拉选项") - public CommonResult> getSimpleDepts() { + public CommonResult> getSimpleDeptList() { // 获得部门列表,只要开启状态的 DeptListReqVO reqVO = new DeptListReqVO(); reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus()); - List list = deptService.getSimpleDepts(reqVO); + List list = deptService.getDeptList(reqVO); // 排序后,返回给前端 list.sort(Comparator.comparing(DeptDO::getSort)); return success(DeptConvert.INSTANCE.convertList02(list)); diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/dept/PostController.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/dept/PostController.java index 79cd44d3a..70e2d8639 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/dept/PostController.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/dept/PostController.java @@ -70,9 +70,9 @@ public class PostController { @GetMapping("/list-all-simple") @Operation(summary = "获取岗位精简信息列表", description = "只包含被开启的岗位,主要用于前端的下拉选项") - public CommonResult> getSimplePosts() { + public CommonResult> getSimplePostList() { // 获得岗位列表,只要开启状态的 - List list = postService.getPosts(null, Collections.singleton(CommonStatusEnum.ENABLE.getStatus())); + List list = postService.getPostList(null, Collections.singleton(CommonStatusEnum.ENABLE.getStatus())); // 排序后,返回给前端 list.sort(Comparator.comparing(PostDO::getSort)); return success(PostConvert.INSTANCE.convertList02(list)); @@ -90,7 +90,7 @@ public class PostController { @PreAuthorize("@ss.hasPermission('system:post:export')") @OperateLog(type = EXPORT) public void export(HttpServletResponse response, @Validated PostExportReqVO reqVO) throws IOException { - List posts = postService.getPosts(reqVO); + List posts = postService.getPostList(reqVO); List data = PostConvert.INSTANCE.convertList03(posts); // 输出 ExcelUtils.write(response, "岗位数据.xls", "岗位列表", PostExcelVO.class, data); diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/dict/DictDataController.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/dict/DictDataController.java index 37793a904..276587472 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/dict/DictDataController.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/dict/DictDataController.java @@ -61,8 +61,8 @@ public class DictDataController { @GetMapping("/list-all-simple") @Operation(summary = "获得全部字典数据列表", description = "一般用于管理后台缓存字典数据在本地") // 无需添加权限认证,因为前端全局都需要 - public CommonResult> getSimpleDictDatas() { - List list = dictDataService.getDictDatas(); + public CommonResult> getSimpleDictDataList() { + List list = dictDataService.getDictDataList(); return success(DictDataConvert.INSTANCE.convertList(list)); } @@ -86,7 +86,7 @@ public class DictDataController { @PreAuthorize("@ss.hasPermission('system:dict:export')") @OperateLog(type = EXPORT) public void export(HttpServletResponse response, @Valid DictDataExportReqVO reqVO) throws IOException { - List list = dictDataService.getDictDatas(reqVO); + List list = dictDataService.getDictDataList(reqVO); List data = DictDataConvert.INSTANCE.convertList02(list); // 输出 ExcelUtils.write(response, "字典数据.xls", "数据列表", DictDataExcelVO.class, data); diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/dict/DictTypeController.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/dict/DictTypeController.java index d78c62e9a..6fcdcdd9c 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/dict/DictTypeController.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/dict/DictTypeController.java @@ -76,7 +76,7 @@ public class DictTypeController { @GetMapping("/list-all-simple") @Operation(summary = "获得全部字典类型列表", description = "包括开启 + 禁用的字典类型,主要用于前端的下拉选项") // 无需添加权限认证,因为前端全局都需要 - public CommonResult> listSimpleDictTypes() { + public CommonResult> getSimpleDictTypeList() { List list = dictTypeService.getDictTypeList(); return success(DictTypeConvert.INSTANCE.convertList(list)); } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/logger/OperateLogController.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/logger/OperateLogController.java index c794f0ca8..fc035f471 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/logger/OperateLogController.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/logger/OperateLogController.java @@ -71,7 +71,7 @@ public class OperateLogController { @PreAuthorize("@ss.hasPermission('system:operate-log:export')") @OperateLog(type = EXPORT) public void exportOperateLog(HttpServletResponse response, @Valid OperateLogExportReqVO reqVO) throws IOException { - List list = operateLogService.getOperateLogs(reqVO); + List list = operateLogService.getOperateLogList(reqVO); // 获得拼接需要的数据 Collection userIds = CollectionUtils.convertList(list, OperateLogDO::getUserId); diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/notice/NoticeController.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/notice/NoticeController.java index 39d24bf3e..0e1957785 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/notice/NoticeController.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/notice/NoticeController.java @@ -57,8 +57,8 @@ public class NoticeController { @GetMapping("/page") @Operation(summary = "获取通知公告列表") @PreAuthorize("@ss.hasPermission('system:notice:query')") - public CommonResult> pageNotices(@Validated NoticePageReqVO reqVO) { - return success(NoticeConvert.INSTANCE.convertPage(noticeService.pageNotices(reqVO))); + public CommonResult> getNoticePage(@Validated NoticePageReqVO reqVO) { + return success(NoticeConvert.INSTANCE.convertPage(noticeService.getNoticePage(reqVO))); } @GetMapping("/get") diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/oauth2/OAuth2UserController.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/oauth2/OAuth2UserController.java index 865646801..b56d71484 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/oauth2/OAuth2UserController.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/oauth2/OAuth2UserController.java @@ -61,7 +61,7 @@ public class OAuth2UserController { } // 获得岗位信息 if (CollUtil.isNotEmpty(user.getPostIds())) { - List posts = postService.getPosts(user.getPostIds()); + List posts = postService.getPostList(user.getPostIds()); resp.setPosts(OAuth2UserConvert.INSTANCE.convertList(posts)); } return success(resp); diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/permission/MenuController.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/permission/MenuController.java index ad7b14c29..4b007ff72 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/permission/MenuController.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/permission/MenuController.java @@ -57,8 +57,8 @@ public class MenuController { @GetMapping("/list") @Operation(summary = "获取菜单列表", description = "用于【菜单管理】界面") @PreAuthorize("@ss.hasPermission('system:menu:query')") - public CommonResult> getMenus(MenuListReqVO reqVO) { - List list = menuService.getMenus(reqVO); + public CommonResult> getMenuList(MenuListReqVO reqVO) { + List list = menuService.getMenuList(reqVO); list.sort(Comparator.comparing(MenuDO::getSort)); return success(MenuConvert.INSTANCE.convertList(list)); } @@ -66,11 +66,11 @@ public class MenuController { @GetMapping("/list-all-simple") @Operation(summary = "获取菜单精简信息列表", description = "只包含被开启的菜单,用于【角色分配菜单】功能的选项。" + "在多租户的场景下,会只返回租户所在套餐有的菜单") - public CommonResult> getSimpleMenus() { + public CommonResult> getSimpleMenuList() { // 获得菜单列表,只要开启状态的 MenuListReqVO reqVO = new MenuListReqVO(); reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus()); - List list = menuService.getTenantMenus(reqVO); + List list = menuService.getMenuListByTenant(reqVO); // 排序后,返回给前端 list.sort(Comparator.comparing(MenuDO::getSort)); return success(MenuConvert.INSTANCE.convertList02(list)); diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/permission/RoleController.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/permission/RoleController.java index cde85f9e4..2df1e74b0 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/permission/RoleController.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/permission/RoleController.java @@ -20,12 +20,12 @@ import javax.annotation.Resource; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import java.io.IOException; -import java.util.Collections; import java.util.Comparator; import java.util.List; import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success; import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT; +import static java.util.Collections.singleton; @Tag(name = "管理后台 - 角色") @RestController @@ -85,9 +85,9 @@ public class RoleController { @GetMapping("/list-all-simple") @Operation(summary = "获取角色精简信息列表", description = "只包含被开启的角色,主要用于前端的下拉选项") - public CommonResult> getSimpleRoles() { + public CommonResult> getSimpleRoleList() { // 获得角色列表,只要开启状态的 - List list = roleService.getRoles(Collections.singleton(CommonStatusEnum.ENABLE.getStatus())); + List list = roleService.getRoleListByStatus(singleton(CommonStatusEnum.ENABLE.getStatus())); // 排序后,返回给前端 list.sort(Comparator.comparing(RoleDO::getSort)); return success(RoleConvert.INSTANCE.convertList02(list)); diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/sensitiveword/SensitiveWordController.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/sensitiveword/SensitiveWordController.java index 684480be6..ab0a129df 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/sensitiveword/SensitiveWordController.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/sensitiveword/SensitiveWordController.java @@ -90,8 +90,8 @@ public class SensitiveWordController { @GetMapping("/get-tags") @Operation(summary = "获取所有敏感词的标签数组") @PreAuthorize("@ss.hasPermission('system:sensitive-word:query')") - public CommonResult> getSensitiveWordTags() throws IOException { - return success(sensitiveWordService.getSensitiveWordTags()); + public CommonResult> getSensitiveWordTagSet() { + return success(sensitiveWordService.getSensitiveWordTagSet()); } @GetMapping("/validate-text") diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/sms/SmsChannelController.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/sms/SmsChannelController.java index 73057a090..b6512a601 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/sms/SmsChannelController.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/sms/SmsChannelController.java @@ -70,7 +70,7 @@ public class SmsChannelController { @GetMapping("/list-all-simple") @Operation(summary = "获得短信渠道精简列表", description = "包含被禁用的短信渠道") - public CommonResult> getSimpleSmsChannels() { + public CommonResult> getSimpleSmsChannelList() { List list = smsChannelService.getSmsChannelList(); // 排序后,返回给前端 list.sort(Comparator.comparing(SmsChannelDO::getId)); diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/user/UserController.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/user/UserController.java index 2f26b34f4..40efb2d23 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/user/UserController.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/user/UserController.java @@ -111,9 +111,9 @@ public class UserController { @GetMapping("/list-all-simple") @Operation(summary = "获取用户精简信息列表", description = "只包含被开启的用户,主要用于前端的下拉选项") - public CommonResult> getSimpleUsers() { + public CommonResult> getSimpleUserList() { // 获用户列表,只要开启状态的 - List list = userService.getUsersByStatus(CommonStatusEnum.ENABLE.getStatus()); + List list = userService.getUserListByStatus(CommonStatusEnum.ENABLE.getStatus()); // 排序后,返回给前端 return success(UserConvert.INSTANCE.convertList04(list)); } @@ -122,7 +122,7 @@ public class UserController { @Operation(summary = "获得用户详情") @Parameter(name = "id", description = "编号", required = true, example = "1024") @PreAuthorize("@ss.hasPermission('system:user:query')") - public CommonResult getInfo(@RequestParam("id") Long id) { + public CommonResult getUser(@RequestParam("id") Long id) { return success(UserConvert.INSTANCE.convert(userService.getUser(id))); } @@ -130,10 +130,10 @@ public class UserController { @Operation(summary = "导出用户") @PreAuthorize("@ss.hasPermission('system:user:export')") @OperateLog(type = EXPORT) - public void exportUsers(@Validated UserExportReqVO reqVO, - HttpServletResponse response) throws IOException { + public void exportUserList(@Validated UserExportReqVO reqVO, + HttpServletResponse response) throws IOException { // 获得用户列表 - List users = userService.getUsers(reqVO); + List users = userService.getUserList(reqVO); // 获得拼接需要的数据 Collection deptIds = convertList(users, AdminUserDO::getDeptId); @@ -183,7 +183,7 @@ public class UserController { public CommonResult importExcel(@RequestParam("file") MultipartFile file, @RequestParam(value = "updateSupport", required = false, defaultValue = "false") Boolean updateSupport) throws Exception { List list = ExcelUtils.read(file, UserImportExcelVO.class); - return success(userService.importUsers(list, updateSupport)); + return success(userService.importUserList(list, updateSupport)); } } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/user/UserProfileController.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/user/UserProfileController.java index 50e1ef0cd..d9fc4a635 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/user/UserProfileController.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/user/UserProfileController.java @@ -2,7 +2,6 @@ package cn.iocoder.yudao.module.system.controller.admin.user; import cn.hutool.core.collection.CollUtil; import cn.iocoder.yudao.framework.common.enums.UserTypeEnum; -import cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil; import cn.iocoder.yudao.framework.common.pojo.CommonResult; import cn.iocoder.yudao.framework.datapermission.core.annotation.DataPermission; import cn.iocoder.yudao.module.system.controller.admin.user.vo.profile.UserProfileRespVO; @@ -31,6 +30,7 @@ import javax.annotation.Resource; import javax.validation.Valid; import java.util.List; +import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success; import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId; import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.FILE_IS_EMPTY; @@ -63,7 +63,7 @@ public class UserProfileController { AdminUserDO user = userService.getUser(getLoginUserId()); UserProfileRespVO resp = UserConvert.INSTANCE.convert03(user); // 获得用户角色 - List userRoles = roleService.getRolesFromCache(permissionService.getUserRoleIdListByUserId(user.getId())); + List userRoles = roleService.getRoleListFromCache(permissionService.getUserRoleIdListByUserId(user.getId())); resp.setRoles(UserConvert.INSTANCE.convertList(userRoles)); // 获得部门信息 if (user.getDeptId() != null) { @@ -72,7 +72,7 @@ public class UserProfileController { } // 获得岗位信息 if (CollUtil.isNotEmpty(user.getPostIds())) { - List posts = postService.getPosts(user.getPostIds()); + List posts = postService.getPostList(user.getPostIds()); resp.setPosts(UserConvert.INSTANCE.convertList02(posts)); } // 获得社交用户信息 @@ -99,7 +99,7 @@ public class UserProfileController { @Operation(summary = "上传用户个人头像") public CommonResult updateUserAvatar(@RequestParam("avatarFile") MultipartFile file) throws Exception { if (file.isEmpty()) { - throw ServiceExceptionUtil.exception(FILE_IS_EMPTY); + throw exception(FILE_IS_EMPTY); } String avatar = userService.updateUserAvatar(getLoginUserId(), file.getInputStream()); return success(avatar); diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/convert/auth/AuthConvert.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/convert/auth/AuthConvert.java index 38e84ea1d..12fd35b1c 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/convert/auth/AuthConvert.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/convert/auth/AuthConvert.java @@ -9,13 +9,15 @@ import cn.iocoder.yudao.module.system.dal.dataobject.oauth2.OAuth2AccessTokenDO; import cn.iocoder.yudao.module.system.dal.dataobject.permission.MenuDO; import cn.iocoder.yudao.module.system.dal.dataobject.permission.RoleDO; import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO; -import cn.iocoder.yudao.module.system.enums.permission.MenuIdEnum; import org.mapstruct.Mapper; import org.mapstruct.factory.Mappers; import org.slf4j.LoggerFactory; import java.util.*; +import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.filterList; +import static cn.iocoder.yudao.module.system.dal.dataobject.permission.MenuDO.ID_ROOT; + @Mapper public interface AuthConvert { @@ -47,7 +49,7 @@ public interface AuthConvert { Map treeNodeMap = new LinkedHashMap<>(); menuList.forEach(menu -> treeNodeMap.put(menu.getId(), AuthConvert.INSTANCE.convertTreeNode(menu))); // 处理父子关系 - treeNodeMap.values().stream().filter(node -> !node.getParentId().equals(MenuIdEnum.ROOT.getId())).forEach(childNode -> { + treeNodeMap.values().stream().filter(node -> !node.getParentId().equals(ID_ROOT)).forEach(childNode -> { // 获得父节点 AuthMenuRespVO parentNode = treeNodeMap.get(childNode.getParentId()); if (parentNode == null) { @@ -62,7 +64,7 @@ public interface AuthConvert { parentNode.getChildren().add(childNode); }); // 获得到所有的根节点 - return CollectionUtils.filterList(treeNodeMap.values(), node -> MenuIdEnum.ROOT.getId().equals(node.getParentId())); + return filterList(treeNodeMap.values(), node -> ID_ROOT.equals(node.getParentId())); } SocialUserBindReqDTO convert(Long userId, Integer userType, AuthSocialLoginReqVO reqVO); diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/dataobject/permission/MenuDO.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/dataobject/permission/MenuDO.java index 5d77c50da..91e46bbff 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/dataobject/permission/MenuDO.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/dataobject/permission/MenuDO.java @@ -21,7 +21,12 @@ import lombok.EqualsAndHashCode; public class MenuDO extends BaseDO { /** - * 菜单ID + * 菜单编号 - 根节点 + */ + public static final Long ID_ROOT = 0L; + + /** + * 菜单编号 */ @TableId private Long id; diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/dept/DeptMapper.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/dept/DeptMapper.java index a7050a182..def79df69 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/dept/DeptMapper.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/dept/DeptMapper.java @@ -4,7 +4,6 @@ import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX; import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX; import cn.iocoder.yudao.module.system.controller.admin.dept.vo.dept.DeptListReqVO; import cn.iocoder.yudao.module.system.dal.dataobject.dept.DeptDO; -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import org.apache.ibatis.annotations.Mapper; import java.util.List; @@ -19,9 +18,7 @@ public interface DeptMapper extends BaseMapperX { } default DeptDO selectByParentIdAndName(Long parentId, String name) { - return selectOne(new LambdaQueryWrapper() - .eq(DeptDO::getParentId, parentId) - .eq(DeptDO::getName, name)); + return selectOne(DeptDO::getParentId, parentId, DeptDO::getName, name); } default Long selectCountByParentId(Long parentId) { diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/dept/PostMapper.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/dept/PostMapper.java index 6bcb8e2fd..ba062a2c0 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/dept/PostMapper.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/dept/PostMapper.java @@ -2,11 +2,10 @@ package cn.iocoder.yudao.module.system.dal.mysql.dept; import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX; -import cn.iocoder.yudao.framework.mybatis.core.query.QueryWrapperX; +import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX; import cn.iocoder.yudao.module.system.controller.admin.dept.vo.post.PostExportReqVO; import cn.iocoder.yudao.module.system.controller.admin.dept.vo.post.PostPageReqVO; import cn.iocoder.yudao.module.system.dal.dataobject.dept.PostDO; -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import org.apache.ibatis.annotations.Mapper; import java.util.Collection; @@ -16,31 +15,32 @@ import java.util.List; public interface PostMapper extends BaseMapperX { default List selectList(Collection ids, Collection statuses) { - return selectList(new QueryWrapperX().inIfPresent("id", ids) - .inIfPresent("status", statuses)); + return selectList(new LambdaQueryWrapperX() + .inIfPresent(PostDO::getId, ids) + .inIfPresent(PostDO::getStatus, statuses)); } default PageResult selectPage(PostPageReqVO reqVO) { - return selectPage(reqVO, new QueryWrapperX() - .likeIfPresent("code", reqVO.getCode()) - .likeIfPresent("name", reqVO.getName()) - .eqIfPresent("status", reqVO.getStatus()) - .orderByDesc("id")); + return selectPage(reqVO, new LambdaQueryWrapperX() + .likeIfPresent(PostDO::getCode, reqVO.getCode()) + .likeIfPresent(PostDO::getName, reqVO.getName()) + .eqIfPresent(PostDO::getStatus, reqVO.getStatus()) + .orderByDesc(PostDO::getId)); } default List selectList(PostExportReqVO reqVO) { - return selectList(new QueryWrapperX() - .likeIfPresent("code", reqVO.getCode()) - .likeIfPresent("name", reqVO.getName()) - .eqIfPresent("status", reqVO.getStatus())); + return selectList(new LambdaQueryWrapperX() + .likeIfPresent(PostDO::getCode, reqVO.getCode()) + .likeIfPresent(PostDO::getName, reqVO.getName()) + .eqIfPresent(PostDO::getStatus, reqVO.getStatus())); } default PostDO selectByName(String name) { - return selectOne(new QueryWrapper().eq("name", name)); + return selectOne(PostDO::getName, name); } default PostDO selectByCode(String code) { - return selectOne(new QueryWrapper().eq("code", code)); + return selectOne(PostDO::getCode, code); } } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/dept/UserPostMapper.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/dept/UserPostMapper.java index 9d2601e8f..addc67d43 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/dept/UserPostMapper.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/dept/UserPostMapper.java @@ -13,8 +13,7 @@ import java.util.List; public interface UserPostMapper extends BaseMapperX { default List selectListByUserId(Long userId) { - return selectList(new LambdaQueryWrapperX() - .eq(UserPostDO::getUserId, userId)); + return selectList(UserPostDO::getUserId, userId); } default void deleteByUserIdAndPostId(Long userId, Collection postIds) { @@ -24,11 +23,10 @@ public interface UserPostMapper extends BaseMapperX { } default List selectListByPostIds(Collection postIds) { - return selectList(new LambdaQueryWrapperX() - .in(UserPostDO::getPostId, postIds)); + return selectList(UserPostDO::getPostId, postIds); } - default void deleteByUserId(Long userId){ + default void deleteByUserId(Long userId) { delete(Wrappers.lambdaUpdate(UserPostDO.class).eq(UserPostDO::getUserId, userId)); } } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/dict/DictDataMapper.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/dict/DictDataMapper.java index 951ef87af..244825093 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/dict/DictDataMapper.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/dict/DictDataMapper.java @@ -17,13 +17,11 @@ import java.util.List; public interface DictDataMapper extends BaseMapperX { default DictDataDO selectByDictTypeAndValue(String dictType, String value) { - return selectOne(new LambdaQueryWrapper().eq(DictDataDO::getDictType, dictType) - .eq(DictDataDO::getValue, value)); + return selectOne(DictDataDO::getDictType, dictType, DictDataDO::getValue, value); } default DictDataDO selectByDictTypeAndLabel(String dictType, String label) { - return selectOne(new LambdaQueryWrapper().eq(DictDataDO::getDictType, dictType) - .eq(DictDataDO::getLabel, label)); + return selectOne(DictDataDO::getDictType, dictType, DictDataDO::getLabel, label); } default List selectByDictTypeAndValues(String dictType, Collection values) { diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/errorcode/ErrorCodeMapper.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/errorcode/ErrorCodeMapper.java index 3cb6bc8af..93baced06 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/errorcode/ErrorCodeMapper.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/errorcode/ErrorCodeMapper.java @@ -36,11 +36,11 @@ public interface ErrorCodeMapper extends BaseMapperX { } default List selectListByCodes(Collection codes) { - return selectList(new LambdaQueryWrapperX().in(ErrorCodeDO::getCode, codes)); + return selectList(ErrorCodeDO::getCode, codes); } default ErrorCodeDO selectByCode(Integer code) { - return selectOne(new LambdaQueryWrapperX().eq(ErrorCodeDO::getCode, code)); + return selectOne(ErrorCodeDO::getCode, code); } default List selectListByApplicationNameAndUpdateTimeGt(String applicationName, LocalDateTime minUpdateTime) { diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/permission/MenuMapper.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/permission/MenuMapper.java index cdab84b53..3d645bdf2 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/permission/MenuMapper.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/permission/MenuMapper.java @@ -4,7 +4,6 @@ import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX; import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX; import cn.iocoder.yudao.module.system.controller.admin.permission.vo.menu.MenuListReqVO; import cn.iocoder.yudao.module.system.dal.dataobject.permission.MenuDO; -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import org.apache.ibatis.annotations.Mapper; import java.util.List; @@ -13,8 +12,7 @@ import java.util.List; public interface MenuMapper extends BaseMapperX { default MenuDO selectByParentIdAndName(Long parentId, String name) { - return selectOne(new LambdaQueryWrapper().eq(MenuDO::getParentId, parentId) - .eq(MenuDO::getName, name)); + return selectOne(MenuDO::getParentId, parentId, MenuDO::getName, name); } default Long selectCountByParentId(Long parentId) { @@ -22,7 +20,8 @@ public interface MenuMapper extends BaseMapperX { } default List selectList(MenuListReqVO reqVO) { - return selectList(new LambdaQueryWrapperX().likeIfPresent(MenuDO::getName, reqVO.getName()) + return selectList(new LambdaQueryWrapperX() + .likeIfPresent(MenuDO::getName, reqVO.getName()) .eqIfPresent(MenuDO::getStatus, reqVO.getStatus())); } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/social/SocialUserBindMapper.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/social/SocialUserBindMapper.java index 88d0c9227..28619ca51 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/social/SocialUserBindMapper.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/social/SocialUserBindMapper.java @@ -24,9 +24,8 @@ public interface SocialUserBindMapper extends BaseMapperX { } default SocialUserBindDO selectByUserTypeAndSocialUserId(Integer userType, Long socialUserId) { - return selectOne(new LambdaQueryWrapperX() - .eq(SocialUserBindDO::getUserType, userType) - .eq(SocialUserBindDO::getSocialUserId, socialUserId)); + return selectOne(SocialUserBindDO::getUserType, userType, + SocialUserBindDO::getSocialUserId, socialUserId); } default List selectListByUserIdAndUserType(Long userId, Integer userType) { diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/user/AdminUserMapper.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/user/AdminUserMapper.java index e6713bacb..4e0827210 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/user/AdminUserMapper.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/user/AdminUserMapper.java @@ -6,7 +6,6 @@ import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX; import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserExportReqVO; import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserPageReqVO; import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO; -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import org.apache.ibatis.annotations.Mapper; import java.util.Collection; @@ -16,15 +15,15 @@ import java.util.List; public interface AdminUserMapper extends BaseMapperX { default AdminUserDO selectByUsername(String username) { - return selectOne(new LambdaQueryWrapper().eq(AdminUserDO::getUsername, username)); + return selectOne(AdminUserDO::getUsername, username); } default AdminUserDO selectByEmail(String email) { - return selectOne(new LambdaQueryWrapper().eq(AdminUserDO::getEmail, email)); + return selectOne(AdminUserDO::getEmail, email); } default AdminUserDO selectByMobile(String mobile) { - return selectOne(new LambdaQueryWrapper().eq(AdminUserDO::getMobile, mobile)); + return selectOne(AdminUserDO::getMobile, mobile); } default PageResult selectPage(UserPageReqVO reqVO, Collection deptIds) { @@ -50,10 +49,6 @@ public interface AdminUserMapper extends BaseMapperX { return selectList(new LambdaQueryWrapperX().like(AdminUserDO::getNickname, nickname)); } - default List selectListByUsername(String username) { - return selectList(new LambdaQueryWrapperX().like(AdminUserDO::getUsername, username)); - } - default List selectListByStatus(Integer status) { return selectList(AdminUserDO::getStatus, status); } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/auth/AdminAuthServiceImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/auth/AdminAuthServiceImpl.java index 490284242..ca34156eb 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/auth/AdminAuthServiceImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/auth/AdminAuthServiceImpl.java @@ -94,7 +94,7 @@ public class AdminAuthServiceImpl implements AdminAuthService { @Override public AuthLoginRespVO login(AuthLoginReqVO reqVO) { // 校验验证码 - verifyCaptcha(reqVO); + validateCaptcha(reqVO); // 使用账号密码,进行登录 AdminUserDO user = authenticate(reqVO.getUsername(), reqVO.getPassword()); @@ -171,14 +171,8 @@ public class AdminAuthServiceImpl implements AdminAuthService { return createTokenAfterLoginSuccess(user.getId(), user.getUsername(), LoginLogTypeEnum.LOGIN_SOCIAL); } - @Override - public AuthLoginRespVO refreshToken(String refreshToken) { - OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.refreshAccessToken(refreshToken, OAuth2ClientConstants.CLIENT_ID_DEFAULT); - return AuthConvert.INSTANCE.convert(accessTokenDO); - } - @VisibleForTesting - void verifyCaptcha(AuthLoginReqVO reqVO) { + void validateCaptcha(AuthLoginReqVO reqVO) { // 如果验证码关闭,则不进行校验 if (!captchaEnable) { return; @@ -206,6 +200,12 @@ public class AdminAuthServiceImpl implements AdminAuthService { return AuthConvert.INSTANCE.convert(accessTokenDO); } + @Override + public AuthLoginRespVO refreshToken(String refreshToken) { + OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.refreshAccessToken(refreshToken, OAuth2ClientConstants.CLIENT_ID_DEFAULT); + return AuthConvert.INSTANCE.convert(accessTokenDO); + } + @Override public void logout(String token, Integer logType) { // 删除访问令牌 diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/dept/DeptService.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/dept/DeptService.java index a6c30bc10..87033d4b3 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/dept/DeptService.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/dept/DeptService.java @@ -52,7 +52,7 @@ public interface DeptService { * @param reqVO 筛选条件请求 VO * @return 部门列表 */ - List getSimpleDepts(DeptListReqVO reqVO); + List getDeptList(DeptListReqVO reqVO); /** * 获得所有子部门,从缓存中 @@ -61,7 +61,7 @@ public interface DeptService { * @param recursive 是否递归获取所有 * @return 子部门列表 */ - List getDeptsByParentIdFromCache(Long parentId, boolean recursive); + List getDeptListByParentIdFromCache(Long parentId, boolean recursive); /** * 获得部门信息数组 @@ -69,7 +69,21 @@ public interface DeptService { * @param ids 部门编号数组 * @return 部门信息数组 */ - List getDepts(Collection ids); + List getDeptList(Collection ids); + + /** + * 获得指定编号的部门 Map + * + * @param ids 部门编号数组 + * @return 部门 Map + */ + default Map getDeptMap(Collection ids) { + if (CollUtil.isEmpty(ids)) { + return Collections.emptyMap(); + } + List list = getDeptList(ids); + return CollectionUtils.convertMap(list, DeptDO::getId); + } /** * 获得部门信息 @@ -86,27 +100,6 @@ public interface DeptService { * * @param ids 角色编号数组 */ - void validDepts(Collection ids); + void validateDeptList(Collection ids); - /** - * 获得指定编号的部门列表 - * - * @param ids 部门编号数组 - * @return 部门列表 - */ - List getSimpleDepts(Collection ids); - - /** - * 获得指定编号的部门 Map - * - * @param ids 部门编号数组 - * @return 部门 Map - */ - default Map getDeptMap(Collection ids) { - if (CollUtil.isEmpty(ids)) { - return Collections.emptyMap(); - } - List list = getSimpleDepts(ids); - return CollectionUtils.convertMap(list, DeptDO::getId); - } } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/dept/DeptServiceImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/dept/DeptServiceImpl.java index 6262eaf70..1b2bbec04 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/dept/DeptServiceImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/dept/DeptServiceImpl.java @@ -2,8 +2,6 @@ package cn.iocoder.yudao.module.system.service.dept; import cn.hutool.core.collection.CollUtil; import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum; -import cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil; -import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils; import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder; import cn.iocoder.yudao.framework.tenant.core.util.TenantUtils; import cn.iocoder.yudao.module.system.controller.admin.dept.vo.dept.DeptCreateReqVO; @@ -19,13 +17,11 @@ import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Multimap; import lombok.Getter; import lombok.extern.slf4j.Slf4j; -import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import org.springframework.validation.annotation.Validated; import javax.annotation.PostConstruct; import javax.annotation.Resource; -import java.time.LocalDateTime; import java.util.*; import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; @@ -95,7 +91,7 @@ public class DeptServiceImpl implements DeptService { if (reqVO.getParentId() == null) { reqVO.setParentId(DeptIdEnum.ROOT.getId()); } - checkCreateOrUpdate(null, reqVO.getParentId(), reqVO.getName()); + validateForCreateOrUpdate(null, reqVO.getParentId(), reqVO.getName()); // 插入部门 DeptDO dept = DeptConvert.INSTANCE.convert(reqVO); deptMapper.insert(dept); @@ -110,7 +106,7 @@ public class DeptServiceImpl implements DeptService { if (reqVO.getParentId() == null) { reqVO.setParentId(DeptIdEnum.ROOT.getId()); } - checkCreateOrUpdate(reqVO.getId(), reqVO.getParentId(), reqVO.getName()); + validateForCreateOrUpdate(reqVO.getId(), reqVO.getParentId(), reqVO.getName()); // 更新部门 DeptDO updateObj = DeptConvert.INSTANCE.convert(reqVO); deptMapper.updateById(updateObj); @@ -121,10 +117,10 @@ public class DeptServiceImpl implements DeptService { @Override public void deleteDept(Long id) { // 校验是否存在 - checkDeptExists(id); + validateDeptExists(id); // 校验是否有子部门 if (deptMapper.selectCountByParentId(id) > 0) { - throw ServiceExceptionUtil.exception(DEPT_EXITS_CHILDREN); + throw exception(DEPT_EXITS_CHILDREN); } // 删除部门 deptMapper.deleteById(id); @@ -133,20 +129,20 @@ public class DeptServiceImpl implements DeptService { } @Override - public List getSimpleDepts(DeptListReqVO reqVO) { + public List getDeptList(DeptListReqVO reqVO) { return deptMapper.selectList(reqVO); } @Override - public List getDeptsByParentIdFromCache(Long parentId, boolean recursive) { + public List getDeptListByParentIdFromCache(Long parentId, boolean recursive) { if (parentId == null) { return Collections.emptyList(); } - List result = new ArrayList<>(); // TODO 芋艿:待优化,新增缓存,避免每次遍历的计算 + List result = new ArrayList<>(); // 递归,简单粗暴 - this.getDeptsByParentIdFromCache(result, parentId, - recursive ? Integer.MAX_VALUE : 1, // 如果递归获取,则无限;否则,只递归 1 次 - parentDeptCache); + getDeptsByParentIdFromCache(result, parentId, + recursive ? Integer.MAX_VALUE : 1, // 如果递归获取,则无限;否则,只递归 1 次 + parentDeptCache); return result; } @@ -182,65 +178,65 @@ public class DeptServiceImpl implements DeptService { recursiveCount - 1, parentDeptMap)); } - private void checkCreateOrUpdate(Long id, Long parentId, String name) { + private void validateForCreateOrUpdate(Long id, Long parentId, String name) { // 校验自己存在 - checkDeptExists(id); + validateDeptExists(id); // 校验父部门的有效性 - checkParentDeptEnable(id, parentId); + validateParentDeptEnable(id, parentId); // 校验部门名的唯一性 - checkDeptNameUnique(id, parentId, name); + validateDeptNameUnique(id, parentId, name); } - private void checkParentDeptEnable(Long id, Long parentId) { + private void validateParentDeptEnable(Long id, Long parentId) { if (parentId == null || DeptIdEnum.ROOT.getId().equals(parentId)) { return; } // 不能设置自己为父部门 if (parentId.equals(id)) { - throw ServiceExceptionUtil.exception(DEPT_PARENT_ERROR); + throw exception(DEPT_PARENT_ERROR); } // 父岗位不存在 DeptDO dept = deptMapper.selectById(parentId); if (dept == null) { - throw ServiceExceptionUtil.exception(DEPT_PARENT_NOT_EXITS); + throw exception(DEPT_PARENT_NOT_EXITS); } // 父部门被禁用 if (!CommonStatusEnum.ENABLE.getStatus().equals(dept.getStatus())) { - throw ServiceExceptionUtil.exception(DEPT_NOT_ENABLE); + throw exception(DEPT_NOT_ENABLE); } // 父部门不能是原来的子部门 - List children = this.getDeptsByParentIdFromCache(id, true); + List children = getDeptListByParentIdFromCache(id, true); if (children.stream().anyMatch(dept1 -> dept1.getId().equals(parentId))) { - throw ServiceExceptionUtil.exception(DEPT_PARENT_IS_CHILD); + throw exception(DEPT_PARENT_IS_CHILD); } } - private void checkDeptExists(Long id) { + private void validateDeptExists(Long id) { if (id == null) { return; } DeptDO dept = deptMapper.selectById(id); if (dept == null) { - throw ServiceExceptionUtil.exception(DEPT_NOT_FOUND); + throw exception(DEPT_NOT_FOUND); } } - private void checkDeptNameUnique(Long id, Long parentId, String name) { + private void validateDeptNameUnique(Long id, Long parentId, String name) { DeptDO menu = deptMapper.selectByParentIdAndName(parentId, name); if (menu == null) { return; } // 如果 id 为空,说明不用比较是否为相同 id 的岗位 if (id == null) { - throw ServiceExceptionUtil.exception(DEPT_NAME_DUPLICATE); + throw exception(DEPT_NAME_DUPLICATE); } if (!menu.getId().equals(id)) { - throw ServiceExceptionUtil.exception(DEPT_NAME_DUPLICATE); + throw exception(DEPT_NAME_DUPLICATE); } } @Override - public List getDepts(Collection ids) { + public List getDeptList(Collection ids) { return deptMapper.selectBatchIds(ids); } @@ -250,13 +246,12 @@ public class DeptServiceImpl implements DeptService { } @Override - public void validDepts(Collection ids) { + public void validateDeptList(Collection ids) { if (CollUtil.isEmpty(ids)) { return; } // 获得科室信息 - List depts = deptMapper.selectBatchIds(ids); - Map deptMap = CollectionUtils.convertMap(depts, DeptDO::getId); + Map deptMap = getDeptMap(ids); // 校验 ids.forEach(id -> { DeptDO dept = deptMap.get(id); @@ -269,9 +264,4 @@ public class DeptServiceImpl implements DeptService { }); } - @Override - public List getSimpleDepts(Collection ids) { - return deptMapper.selectBatchIds(ids); - } - } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/dept/PostService.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/dept/PostService.java index fc74c944a..c1b84c011 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/dept/PostService.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/dept/PostService.java @@ -49,8 +49,8 @@ public interface PostService { * @param ids 岗位编号数组。如果为空,不进行筛选 * @return 部门列表 */ - default List getPosts(@Nullable Collection ids) { - return getPosts(ids, asSet(CommonStatusEnum.ENABLE.getStatus(), CommonStatusEnum.DISABLE.getStatus())); + default List getPostList(@Nullable Collection ids) { + return getPostList(ids, asSet(CommonStatusEnum.ENABLE.getStatus(), CommonStatusEnum.DISABLE.getStatus())); } /** @@ -60,7 +60,7 @@ public interface PostService { * @param statuses 状态数组。如果为空,不进行筛选 * @return 部门列表 */ - List getPosts(@Nullable Collection ids, @Nullable Collection statuses); + List getPostList(@Nullable Collection ids, @Nullable Collection statuses); /** * 获得岗位分页列表 @@ -76,7 +76,7 @@ public interface PostService { * @param reqVO 查询条件 * @return 部门列表 */ - List getPosts(PostExportReqVO reqVO); + List getPostList(PostExportReqVO reqVO); /** * 获得岗位信息 @@ -93,6 +93,6 @@ public interface PostService { * * @param ids 岗位编号数组 */ - void validPosts(Collection ids); + void validatePostList(Collection ids); } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/dept/PostServiceImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/dept/PostServiceImpl.java index 81e003152..3266a0c92 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/dept/PostServiceImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/dept/PostServiceImpl.java @@ -2,7 +2,6 @@ package cn.iocoder.yudao.module.system.service.dept; import cn.hutool.core.collection.CollUtil; import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum; -import cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil; import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.module.system.controller.admin.dept.vo.post.PostCreateReqVO; import cn.iocoder.yudao.module.system.controller.admin.dept.vo.post.PostExportReqVO; @@ -38,7 +37,8 @@ public class PostServiceImpl implements PostService { @Override public Long createPost(PostCreateReqVO reqVO) { // 校验正确性 - this.checkCreateOrUpdate(null, reqVO.getName(), reqVO.getCode()); + validatePostForCreateOrUpdate(null, reqVO.getName(), reqVO.getCode()); + // 插入岗位 PostDO post = PostConvert.INSTANCE.convert(reqVO); postMapper.insert(post); @@ -48,7 +48,8 @@ public class PostServiceImpl implements PostService { @Override public void updatePost(PostUpdateReqVO reqVO) { // 校验正确性 - this.checkCreateOrUpdate(reqVO.getId(), reqVO.getName(), reqVO.getCode()); + validatePostForCreateOrUpdate(reqVO.getId(), reqVO.getName(), reqVO.getCode()); + // 更新岗位 PostDO updateObj = PostConvert.INSTANCE.convert(reqVO); postMapper.updateById(updateObj); @@ -57,13 +58,59 @@ public class PostServiceImpl implements PostService { @Override public void deletePost(Long id) { // 校验是否存在 - this.checkPostExists(id); + validatePostExists(id); // 删除部门 postMapper.deleteById(id); } + private void validatePostForCreateOrUpdate(Long id, String name, String code) { + // 校验自己存在 + validatePostExists(id); + // 校验岗位名的唯一性 + validatePostNameUnique(id, name); + // 校验岗位编码的唯一性 + validatePostCodeUnique(id, code); + } + + private void validatePostNameUnique(Long id, String name) { + PostDO post = postMapper.selectByName(name); + if (post == null) { + return; + } + // 如果 id 为空,说明不用比较是否为相同 id 的岗位 + if (id == null) { + throw exception(POST_NAME_DUPLICATE); + } + if (!post.getId().equals(id)) { + throw exception(POST_NAME_DUPLICATE); + } + } + + private void validatePostCodeUnique(Long id, String code) { + PostDO post = postMapper.selectByCode(code); + if (post == null) { + return; + } + // 如果 id 为空,说明不用比较是否为相同 id 的岗位 + if (id == null) { + throw exception(POST_CODE_DUPLICATE); + } + if (!post.getId().equals(id)) { + throw exception(POST_CODE_DUPLICATE); + } + } + + private void validatePostExists(Long id) { + if (id == null) { + return; + } + if (postMapper.selectById(id) == null) { + throw exception(POST_NOT_FOUND); + } + } + @Override - public List getPosts(Collection ids, Collection statuses) { + public List getPostList(Collection ids, Collection statuses) { return postMapper.selectList(ids, statuses); } @@ -73,7 +120,7 @@ public class PostServiceImpl implements PostService { } @Override - public List getPosts(PostExportReqVO reqVO) { + public List getPostList(PostExportReqVO reqVO) { return postMapper.selectList(reqVO); } @@ -82,55 +129,8 @@ public class PostServiceImpl implements PostService { return postMapper.selectById(id); } - private void checkCreateOrUpdate(Long id, String name, String code) { - // 校验自己存在 - checkPostExists(id); - // 校验岗位名的唯一性 - checkPostNameUnique(id, name); - // 校验岗位编码的唯一性 - checkPostCodeUnique(id, code); - } - - private void checkPostNameUnique(Long id, String name) { - PostDO post = postMapper.selectByName(name); - if (post == null) { - return; - } - // 如果 id 为空,说明不用比较是否为相同 id 的岗位 - if (id == null) { - throw ServiceExceptionUtil.exception(POST_NAME_DUPLICATE); - } - if (!post.getId().equals(id)) { - throw ServiceExceptionUtil.exception(POST_NAME_DUPLICATE); - } - } - - private void checkPostCodeUnique(Long id, String code) { - PostDO post = postMapper.selectByCode(code); - if (post == null) { - return; - } - // 如果 id 为空,说明不用比较是否为相同 id 的岗位 - if (id == null) { - throw ServiceExceptionUtil.exception(POST_CODE_DUPLICATE); - } - if (!post.getId().equals(id)) { - throw ServiceExceptionUtil.exception(POST_CODE_DUPLICATE); - } - } - - private void checkPostExists(Long id) { - if (id == null) { - return; - } - PostDO post = postMapper.selectById(id); - if (post == null) { - throw ServiceExceptionUtil.exception(POST_NOT_FOUND); - } - } - @Override - public void validPosts(Collection ids) { + public void validatePostList(Collection ids) { if (CollUtil.isEmpty(ids)) { return; } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/dict/DictDataService.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/dict/DictDataService.java index 610fe2a33..d2eb8c519 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/dict/DictDataService.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/dict/DictDataService.java @@ -44,7 +44,7 @@ public interface DictDataService { * * @return 字典数据全列表 */ - List getDictDatas(); + List getDictDataList(); /** * 获得字典数据分页列表 @@ -60,7 +60,7 @@ public interface DictDataService { * @param reqVO 列表请求 * @return 字典数据列表 */ - List getDictDatas(DictDataExportReqVO reqVO); + List getDictDataList(DictDataExportReqVO reqVO); /** * 获得字典数据详情 @@ -86,7 +86,7 @@ public interface DictDataService { * @param dictType 字典类型 * @param values 字典数据值的数组 */ - void validDictDatas(String dictType, Collection values); + void validateDictDataList(String dictType, Collection values); /** * 获得指定的字典数据 diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/dict/DictDataServiceImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/dict/DictDataServiceImpl.java index 0cfdb2b99..eccd2c219 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/dict/DictDataServiceImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/dict/DictDataServiceImpl.java @@ -48,7 +48,7 @@ public class DictDataServiceImpl implements DictDataService { private DictDataMapper dictDataMapper; @Override - public List getDictDatas() { + public List getDictDataList() { List list = dictDataMapper.selectList(); list.sort(COMPARATOR_TYPE_AND_SORT); return list; @@ -60,7 +60,7 @@ public class DictDataServiceImpl implements DictDataService { } @Override - public List getDictDatas(DictDataExportReqVO reqVO) { + public List getDictDataList(DictDataExportReqVO reqVO) { List list = dictDataMapper.selectList(reqVO); list.sort(COMPARATOR_TYPE_AND_SORT); return list; @@ -74,7 +74,7 @@ public class DictDataServiceImpl implements DictDataService { @Override public Long createDictData(DictDataCreateReqVO reqVO) { // 校验正确性 - checkCreateOrUpdate(null, reqVO.getValue(), reqVO.getDictType()); + validateDictDataForCreateOrUpdate(null, reqVO.getValue(), reqVO.getDictType()); // 插入字典类型 DictDataDO dictData = DictDataConvert.INSTANCE.convert(reqVO); @@ -85,7 +85,7 @@ public class DictDataServiceImpl implements DictDataService { @Override public void updateDictData(DictDataUpdateReqVO reqVO) { // 校验正确性 - checkCreateOrUpdate(reqVO.getId(), reqVO.getValue(), reqVO.getDictType()); + validateDictDataForCreateOrUpdate(reqVO.getId(), reqVO.getValue(), reqVO.getDictType()); // 更新字典类型 DictDataDO updateObj = DictDataConvert.INSTANCE.convert(reqVO); @@ -95,7 +95,7 @@ public class DictDataServiceImpl implements DictDataService { @Override public void deleteDictData(Long id) { // 校验是否存在 - checkDictDataExists(id); + validateDictDataExists(id); // 删除字典数据 dictDataMapper.deleteById(id); @@ -106,18 +106,17 @@ public class DictDataServiceImpl implements DictDataService { return dictDataMapper.selectCountByDictType(dictType); } - - private void checkCreateOrUpdate(Long id, String value, String dictType) { + private void validateDictDataForCreateOrUpdate(Long id, String value, String dictType) { // 校验自己存在 - checkDictDataExists(id); + validateDictDataExists(id); // 校验字典类型有效 - checkDictTypeValid(dictType); + validateDictTypeExists(dictType); // 校验字典数据的值的唯一性 - checkDictDataValueUnique(id, dictType, value); + validateDictDataValueUnique(id, dictType, value); } @VisibleForTesting - public void checkDictDataValueUnique(Long id, String dictType, String value) { + public void validateDictDataValueUnique(Long id, String dictType, String value) { DictDataDO dictData = dictDataMapper.selectByDictTypeAndValue(dictType, value); if (dictData == null) { return; @@ -132,7 +131,7 @@ public class DictDataServiceImpl implements DictDataService { } @VisibleForTesting - public void checkDictDataExists(Long id) { + public void validateDictDataExists(Long id) { if (id == null) { return; } @@ -143,7 +142,7 @@ public class DictDataServiceImpl implements DictDataService { } @VisibleForTesting - public void checkDictTypeValid(String type) { + public void validateDictTypeExists(String type) { DictTypeDO dictType = dictTypeService.getDictType(type); if (dictType == null) { throw exception(DICT_TYPE_NOT_EXISTS); @@ -154,7 +153,7 @@ public class DictDataServiceImpl implements DictDataService { } @Override - public void validDictDatas(String dictType, Collection values) { + public void validateDictDataList(String dictType, Collection values) { if (CollUtil.isEmpty(values)) { return; } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/dict/DictTypeServiceImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/dict/DictTypeServiceImpl.java index 07fcf40f3..cc731affe 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/dict/DictTypeServiceImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/dict/DictTypeServiceImpl.java @@ -57,7 +57,8 @@ public class DictTypeServiceImpl implements DictTypeService { @Override public Long createDictType(DictTypeCreateReqVO reqVO) { // 校验正确性 - checkCreateOrUpdate(null, reqVO.getName(), reqVO.getType()); + validateDictTypeForCreateOrUpdate(null, reqVO.getName(), reqVO.getType()); + // 插入字典类型 DictTypeDO dictType = DictTypeConvert.INSTANCE.convert(reqVO) .setDeletedTime(LocalDateTimeUtils.EMPTY); // 唯一索引,避免 null 值 @@ -68,7 +69,8 @@ public class DictTypeServiceImpl implements DictTypeService { @Override public void updateDictType(DictTypeUpdateReqVO reqVO) { // 校验正确性 - checkCreateOrUpdate(reqVO.getId(), reqVO.getName(), null); + validateDictTypeForCreateOrUpdate(reqVO.getId(), reqVO.getName(), null); + // 更新字典类型 DictTypeDO updateObj = DictTypeConvert.INSTANCE.convert(reqVO); dictTypeMapper.updateById(updateObj); @@ -77,7 +79,7 @@ public class DictTypeServiceImpl implements DictTypeService { @Override public void deleteDictType(Long id) { // 校验是否存在 - DictTypeDO dictType = checkDictTypeExists(id); + DictTypeDO dictType = validateDictTypeExists(id); // 校验是否有字典数据 if (dictDataService.countByDictType(dictType.getType()) > 0) { throw exception(DICT_TYPE_HAS_CHILDREN); @@ -91,17 +93,17 @@ public class DictTypeServiceImpl implements DictTypeService { return dictTypeMapper.selectList(); } - private void checkCreateOrUpdate(Long id, String name, String type) { + private void validateDictTypeForCreateOrUpdate(Long id, String name, String type) { // 校验自己存在 - checkDictTypeExists(id); + validateDictTypeExists(id); // 校验字典类型的名字的唯一性 - checkDictTypeNameUnique(id, name); + validateDictTypeNameUnique(id, name); // 校验字典类型的类型的唯一性 - checkDictTypeUnique(id, type); + validateDictTypeUnique(id, type); } @VisibleForTesting - public void checkDictTypeNameUnique(Long id, String name) { + void validateDictTypeNameUnique(Long id, String name) { DictTypeDO dictType = dictTypeMapper.selectByName(name); if (dictType == null) { return; @@ -116,7 +118,7 @@ public class DictTypeServiceImpl implements DictTypeService { } @VisibleForTesting - public void checkDictTypeUnique(Long id, String type) { + void validateDictTypeUnique(Long id, String type) { if (StrUtil.isEmpty(type)) { return; } @@ -134,7 +136,7 @@ public class DictTypeServiceImpl implements DictTypeService { } @VisibleForTesting - public DictTypeDO checkDictTypeExists(Long id) { + DictTypeDO validateDictTypeExists(Long id) { if (id == null) { return null; } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/errorcode/ErrorCodeServiceImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/errorcode/ErrorCodeServiceImpl.java index d28f2baed..ed0712a90 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/errorcode/ErrorCodeServiceImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/errorcode/ErrorCodeServiceImpl.java @@ -58,7 +58,7 @@ public class ErrorCodeServiceImpl implements ErrorCodeService { @Override public void updateErrorCode(ErrorCodeUpdateReqVO updateReqVO) { // 校验存在 - this.validateErrorCodeExists(updateReqVO.getId()); + validateErrorCodeExists(updateReqVO.getId()); // 校验 code 重复 validateCodeDuplicate(updateReqVO.getCode(), updateReqVO.getId()); @@ -71,7 +71,7 @@ public class ErrorCodeServiceImpl implements ErrorCodeService { @Override public void deleteErrorCode(Long id) { // 校验存在 - this.validateErrorCodeExists(id); + validateErrorCodeExists(id); // 删除 errorCodeMapper.deleteById(id); } @@ -100,7 +100,7 @@ public class ErrorCodeServiceImpl implements ErrorCodeService { } @VisibleForTesting - public void validateErrorCodeExists(Long id) { + void validateErrorCodeExists(Long id) { if (errorCodeMapper.selectById(id) == null) { throw exception(ERROR_CODE_NOT_EXISTS); } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/logger/OperateLogService.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/logger/OperateLogService.java index 224a83f19..434ecbc46 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/logger/OperateLogService.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/logger/OperateLogService.java @@ -1,8 +1,6 @@ package cn.iocoder.yudao.module.system.service.logger; import cn.iocoder.yudao.framework.common.pojo.PageResult; -import cn.iocoder.yudao.framework.operatelog.core.service.OperateLog; -import cn.iocoder.yudao.framework.operatelog.core.service.OperateLogFrameworkService; import cn.iocoder.yudao.module.system.api.logger.dto.OperateLogCreateReqDTO; import cn.iocoder.yudao.module.system.controller.admin.logger.vo.operatelog.OperateLogExportReqVO; import cn.iocoder.yudao.module.system.controller.admin.logger.vo.operatelog.OperateLogPageReqVO; @@ -38,6 +36,6 @@ public interface OperateLogService { * @param reqVO 列表条件 * @return 日志列表 */ - List getOperateLogs(OperateLogExportReqVO reqVO); + List getOperateLogList(OperateLogExportReqVO reqVO); } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/logger/OperateLogServiceImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/logger/OperateLogServiceImpl.java index 8ae3d139b..c899696ac 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/logger/OperateLogServiceImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/logger/OperateLogServiceImpl.java @@ -49,7 +49,7 @@ public class OperateLogServiceImpl implements OperateLogService { // 处理基于用户昵称的查询 Collection userIds = null; if (StrUtil.isNotEmpty(reqVO.getUserNickname())) { - userIds = convertSet(userService.getUsersByNickname(reqVO.getUserNickname()), AdminUserDO::getId); + userIds = convertSet(userService.getUserListByNickname(reqVO.getUserNickname()), AdminUserDO::getId); if (CollUtil.isEmpty(userIds)) { return PageResult.empty(); } @@ -59,11 +59,11 @@ public class OperateLogServiceImpl implements OperateLogService { } @Override - public List getOperateLogs(OperateLogExportReqVO reqVO) { + public List getOperateLogList(OperateLogExportReqVO reqVO) { // 处理基于用户昵称的查询 Collection userIds = null; if (StrUtil.isNotEmpty(reqVO.getUserNickname())) { - userIds = convertSet(userService.getUsersByNickname(reqVO.getUserNickname()), AdminUserDO::getId); + userIds = convertSet(userService.getUserListByNickname(reqVO.getUserNickname()), AdminUserDO::getId); if (CollUtil.isEmpty(userIds)) { return Collections.emptyList(); } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/mail/MailSendServiceImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/mail/MailSendServiceImpl.java index d7b17d877..72da3cf89 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/mail/MailSendServiceImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/mail/MailSendServiceImpl.java @@ -3,7 +3,6 @@ package cn.iocoder.yudao.module.system.service.mail; import cn.hutool.core.util.StrUtil; import cn.hutool.extra.mail.MailAccount; import cn.hutool.extra.mail.MailUtil; -import cn.iocoder.yudao.framework.common.core.KeyValue; import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum; import cn.iocoder.yudao.framework.common.enums.UserTypeEnum; import cn.iocoder.yudao.module.system.convert.mail.MailAccountConvert; @@ -20,15 +19,13 @@ import org.springframework.stereotype.Service; import org.springframework.validation.annotation.Validated; import javax.annotation.Resource; -import java.util.List; import java.util.Map; -import java.util.stream.Collectors; import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*; /** - * 邮箱模版 服务实现类 + * 邮箱发送 Service 实现类 * * @author wangjingyi * @since 2022-03-21 @@ -82,13 +79,13 @@ public class MailSendServiceImpl implements MailSendService { public Long sendSingleMail(String mail, Long userId, Integer userType, String templateCode, Map templateParams) { // 校验邮箱模版是否合法 - MailTemplateDO template = checkMailTemplateValid(templateCode); + MailTemplateDO template = validateMailTemplate(templateCode); // 校验邮箱账号是否合法 - MailAccountDO account = checkMailAccountValid(template.getAccountId()); + MailAccountDO account = validateMailAccount(template.getAccountId()); // 校验邮箱是否存在 - mail = checkMail(mail); - checkTemplateParams(template, templateParams); + mail = validateMail(mail); + validateTemplateParams(template, templateParams); // 创建发送日志。如果模板被禁用,则不发送短信,只记录日志 Boolean isSend = CommonStatusEnum.ENABLE.getStatus().equals(template.getStatus()); @@ -106,7 +103,7 @@ public class MailSendServiceImpl implements MailSendService { @Override public void doSendMail(MailSendMessage message) { // 1. 创建发送账号 - MailAccountDO account = checkMailAccountValid(message.getAccountId()); + MailAccountDO account = validateMailAccount(message.getAccountId()); MailAccount mailAccount = MailAccountConvert.INSTANCE.convert(account, message.getNickname()); // 2. 发送邮件 try { @@ -121,7 +118,7 @@ public class MailSendServiceImpl implements MailSendService { } @VisibleForTesting - public MailTemplateDO checkMailTemplateValid(String templateCode) { + MailTemplateDO validateMailTemplate(String templateCode) { // 获得邮件模板。考虑到效率,从缓存中获取 MailTemplateDO template = mailTemplateService.getMailTemplateByCodeFromCache(templateCode); // 邮件模板不存在 @@ -132,7 +129,7 @@ public class MailSendServiceImpl implements MailSendService { } @VisibleForTesting - public MailAccountDO checkMailAccountValid(Long accountId) { + MailAccountDO validateMailAccount(Long accountId) { // 获得邮箱账号。考虑到效率,从缓存中获取 MailAccountDO account = mailAccountService.getMailAccountFromCache(accountId); // 邮箱账号不存在 @@ -143,7 +140,7 @@ public class MailSendServiceImpl implements MailSendService { } @VisibleForTesting - public String checkMail(String mail) { + String validateMail(String mail) { if (StrUtil.isEmpty(mail)) { throw exception(MAIL_SEND_MAIL_NOT_EXISTS); } @@ -157,7 +154,7 @@ public class MailSendServiceImpl implements MailSendService { * @param templateParams 参数列表 */ @VisibleForTesting - public void checkTemplateParams(MailTemplateDO template, Map templateParams) { + void validateTemplateParams(MailTemplateDO template, Map templateParams) { template.getParams().forEach(key -> { Object value = templateParams.get(key); if (value == null) { diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/notice/NoticeService.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/notice/NoticeService.java index 264fc3048..432fe876e 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/notice/NoticeService.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/notice/NoticeService.java @@ -39,7 +39,7 @@ public interface NoticeService { * @param reqVO 分页条件 * @return 部门分页列表 */ - PageResult pageNotices(NoticePageReqVO reqVO); + PageResult getNoticePage(NoticePageReqVO reqVO); /** * 获得岗位公告公告信息 diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/notice/NoticeServiceImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/notice/NoticeServiceImpl.java index 2b796e28c..1930e64c1 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/notice/NoticeServiceImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/notice/NoticeServiceImpl.java @@ -1,18 +1,18 @@ package cn.iocoder.yudao.module.system.service.notice; -import cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil; import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.module.system.controller.admin.notice.vo.NoticeCreateReqVO; import cn.iocoder.yudao.module.system.controller.admin.notice.vo.NoticePageReqVO; import cn.iocoder.yudao.module.system.controller.admin.notice.vo.NoticeUpdateReqVO; import cn.iocoder.yudao.module.system.convert.notice.NoticeConvert; -import cn.iocoder.yudao.module.system.dal.mysql.notice.NoticeMapper; import cn.iocoder.yudao.module.system.dal.dataobject.notice.NoticeDO; +import cn.iocoder.yudao.module.system.dal.mysql.notice.NoticeMapper; import com.google.common.annotations.VisibleForTesting; import org.springframework.stereotype.Service; import javax.annotation.Resource; +import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.NOTICE_NOT_FOUND; /** @@ -36,7 +36,7 @@ public class NoticeServiceImpl implements NoticeService { @Override public void updateNotice(NoticeUpdateReqVO reqVO) { // 校验是否存在 - this.checkNoticeExists(reqVO.getId()); + validateNoticeExists(reqVO.getId()); // 更新通知公告 NoticeDO updateObj = NoticeConvert.INSTANCE.convert(reqVO); noticeMapper.updateById(updateObj); @@ -45,13 +45,13 @@ public class NoticeServiceImpl implements NoticeService { @Override public void deleteNotice(Long id) { // 校验是否存在 - this.checkNoticeExists(id); + validateNoticeExists(id); // 删除通知公告 noticeMapper.deleteById(id); } @Override - public PageResult pageNotices(NoticePageReqVO reqVO) { + public PageResult getNoticePage(NoticePageReqVO reqVO) { return noticeMapper.selectPage(reqVO); } @@ -61,13 +61,13 @@ public class NoticeServiceImpl implements NoticeService { } @VisibleForTesting - public void checkNoticeExists(Long id) { + public void validateNoticeExists(Long id) { if (id == null) { return; } NoticeDO notice = noticeMapper.selectById(id); if (notice == null) { - throw ServiceExceptionUtil.exception(NOTICE_NOT_FOUND); + throw exception(NOTICE_NOT_FOUND); } } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/notify/NotifySendServiceImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/notify/NotifySendServiceImpl.java index 39e685fd5..f71c5fe5c 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/notify/NotifySendServiceImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/notify/NotifySendServiceImpl.java @@ -44,13 +44,13 @@ public class NotifySendServiceImpl implements NotifySendService { @Override public Long sendSingleNotify(Long userId, Integer userType, String templateCode, Map templateParams) { // 校验模版 - NotifyTemplateDO template = checkNotifyTemplateValid(templateCode); + NotifyTemplateDO template = validateNotifyTemplate(templateCode); if (Objects.equals(template.getStatus(), CommonStatusEnum.DISABLE.getStatus())) { log.info("[sendSingleNotify][模版({})已经关闭,无法给用户({}/{})发送]", templateCode, userId, userType); return null; } // 校验参数 - checkTemplateParams(template, templateParams); + validateTemplateParams(template, templateParams); // 发送站内信 String content = notifyTemplateService.formatNotifyTemplateContent(template.getContent(), templateParams); @@ -58,7 +58,7 @@ public class NotifySendServiceImpl implements NotifySendService { } @VisibleForTesting - public NotifyTemplateDO checkNotifyTemplateValid(String templateCode) { + public NotifyTemplateDO validateNotifyTemplate(String templateCode) { // 获得站内信模板。考虑到效率,从缓存中获取 NotifyTemplateDO template = notifyTemplateService.getNotifyTemplateByCodeFromCache(templateCode); // 站内信模板不存在 @@ -75,7 +75,7 @@ public class NotifySendServiceImpl implements NotifySendService { * @param templateParams 参数列表 */ @VisibleForTesting - public void checkTemplateParams(NotifyTemplateDO template, Map templateParams) { + public void validateTemplateParams(NotifyTemplateDO template, Map templateParams) { template.getParams().forEach(key -> { Object value = templateParams.get(key); if (value == null) { diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/notify/NotifyTemplateServiceImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/notify/NotifyTemplateServiceImpl.java index 5ee8b4bbc..5b63ac720 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/notify/NotifyTemplateServiceImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/notify/NotifyTemplateServiceImpl.java @@ -76,7 +76,7 @@ public class NotifyTemplateServiceImpl implements NotifyTemplateService { @Override public Long createNotifyTemplate(NotifyTemplateCreateReqVO createReqVO) { // 校验站内信编码是否重复 - checkNotifyTemplateCodeDuplicate(null, createReqVO.getCode()); + validateNotifyTemplateCodeDuplicate(null, createReqVO.getCode()); // 插入 NotifyTemplateDO notifyTemplate = NotifyTemplateConvert.INSTANCE.convert(createReqVO); @@ -93,7 +93,7 @@ public class NotifyTemplateServiceImpl implements NotifyTemplateService { // 校验存在 validateNotifyTemplateExists(updateReqVO.getId()); // 校验站内信编码是否重复 - checkNotifyTemplateCodeDuplicate(updateReqVO.getId(), updateReqVO.getCode()); + validateNotifyTemplateCodeDuplicate(updateReqVO.getId(), updateReqVO.getCode()); // 更新 NotifyTemplateDO updateObj = NotifyTemplateConvert.INSTANCE.convert(updateReqVO); @@ -136,7 +136,7 @@ public class NotifyTemplateServiceImpl implements NotifyTemplateService { } @VisibleForTesting - public void checkNotifyTemplateCodeDuplicate(Long id, String code) { + public void validateNotifyTemplateCodeDuplicate(Long id, String code) { NotifyTemplateDO template = notifyTemplateMapper.selectByCode(code); if (template == null) { return; diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/permission/MenuService.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/permission/MenuService.java index 2bc192683..02418c077 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/permission/MenuService.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/permission/MenuService.java @@ -47,7 +47,7 @@ public interface MenuService { * * @return 菜单列表 */ - List getMenus(); + List getMenuList(); /** * 基于租户,筛选菜单列表 @@ -56,7 +56,7 @@ public interface MenuService { * @param reqVO 筛选条件请求 VO * @return 菜单列表 */ - List getTenantMenus(MenuListReqVO reqVO); + List getMenuListByTenant(MenuListReqVO reqVO); /** * 筛选菜单列表 @@ -64,7 +64,7 @@ public interface MenuService { * @param reqVO 筛选条件请求 VO * @return 菜单列表 */ - List getMenus(MenuListReqVO reqVO); + List getMenuList(MenuListReqVO reqVO); /** * 获得所有菜单,从缓存中 diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/permission/MenuServiceImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/permission/MenuServiceImpl.java index 32466d592..27d6a3567 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/permission/MenuServiceImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/permission/MenuServiceImpl.java @@ -2,7 +2,6 @@ package cn.iocoder.yudao.module.system.service.permission; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.util.StrUtil; -import cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil; import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils; import cn.iocoder.yudao.module.system.controller.admin.permission.vo.menu.MenuCreateReqVO; import cn.iocoder.yudao.module.system.controller.admin.permission.vo.menu.MenuListReqVO; @@ -10,7 +9,6 @@ import cn.iocoder.yudao.module.system.controller.admin.permission.vo.menu.MenuUp import cn.iocoder.yudao.module.system.convert.permission.MenuConvert; import cn.iocoder.yudao.module.system.dal.dataobject.permission.MenuDO; import cn.iocoder.yudao.module.system.dal.mysql.permission.MenuMapper; -import cn.iocoder.yudao.module.system.enums.permission.MenuIdEnum; import cn.iocoder.yudao.module.system.enums.permission.MenuTypeEnum; import cn.iocoder.yudao.module.system.mq.producer.permission.MenuProducer; import cn.iocoder.yudao.module.system.service.tenant.TenantService; @@ -19,6 +17,7 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Multimap; import lombok.Getter; +import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; @@ -31,6 +30,8 @@ import javax.annotation.Resource; import java.util.*; import java.util.stream.Collectors; +import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; +import static cn.iocoder.yudao.module.system.dal.dataobject.permission.MenuDO.ID_ROOT; import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*; /** @@ -49,6 +50,7 @@ public class MenuServiceImpl implements MenuService { * 这里声明 volatile 修饰的原因是,每次刷新时,直接修改指向 */ @Getter + @Setter private volatile Map menuCache; /** * 权限与菜单缓存 @@ -58,6 +60,7 @@ public class MenuServiceImpl implements MenuService { * 这里声明 volatile 修饰的原因是,每次刷新时,直接修改指向 */ @Getter + @Setter private volatile Multimap permissionMenuCache; @Resource @@ -97,9 +100,10 @@ public class MenuServiceImpl implements MenuService { @Override public Long createMenu(MenuCreateReqVO reqVO) { // 校验父菜单存在 - checkParentResource(reqVO.getParentId(), null); + validateParentMenu(reqVO.getParentId(), null); // 校验菜单(自己) - checkResource(reqVO.getParentId(), reqVO.getName(), null); + validateMenu(reqVO.getParentId(), reqVO.getName(), null); + // 插入数据库 MenuDO menu = MenuConvert.INSTANCE.convert(reqVO); initMenuProperty(menu); @@ -114,12 +118,13 @@ public class MenuServiceImpl implements MenuService { public void updateMenu(MenuUpdateReqVO reqVO) { // 校验更新的菜单是否存在 if (menuMapper.selectById(reqVO.getId()) == null) { - throw ServiceExceptionUtil.exception(MENU_NOT_EXISTS); + throw exception(MENU_NOT_EXISTS); } // 校验父菜单存在 - checkParentResource(reqVO.getParentId(), reqVO.getId()); + validateParentMenu(reqVO.getParentId(), reqVO.getId()); // 校验菜单(自己) - checkResource(reqVO.getParentId(), reqVO.getName(), reqVO.getId()); + validateMenu(reqVO.getParentId(), reqVO.getName(), reqVO.getId()); + // 更新到数据库 MenuDO updateObject = MenuConvert.INSTANCE.convert(reqVO); initMenuProperty(updateObject); @@ -128,21 +133,16 @@ public class MenuServiceImpl implements MenuService { menuProducer.sendMenuRefreshMessage(); } - /** - * 删除菜单 - * - * @param menuId 菜单编号 - */ - @Transactional(rollbackFor = Exception.class) @Override + @Transactional(rollbackFor = Exception.class) public void deleteMenu(Long menuId) { // 校验是否还有子菜单 if (menuMapper.selectCountByParentId(menuId) > 0) { - throw ServiceExceptionUtil.exception(MENU_EXISTS_CHILDREN); + throw exception(MENU_EXISTS_CHILDREN); } // 校验删除的菜单是否存在 if (menuMapper.selectById(menuId) == null) { - throw ServiceExceptionUtil.exception(MENU_NOT_EXISTS); + throw exception(MENU_NOT_EXISTS); } // 标记删除 menuMapper.deleteById(menuId); @@ -160,20 +160,20 @@ public class MenuServiceImpl implements MenuService { } @Override - public List getMenus() { + public List getMenuList() { return menuMapper.selectList(); } @Override - public List getTenantMenus(MenuListReqVO reqVO) { - List menus = getMenus(reqVO); + public List getMenuListByTenant(MenuListReqVO reqVO) { + List menus = getMenuList(reqVO); // 开启多租户的情况下,需要过滤掉未开通的菜单 tenantService.handleTenantMenu(menuIds -> menus.removeIf(menu -> !CollUtil.contains(menuIds, menu.getId()))); return menus; } @Override - public List getMenus(MenuListReqVO reqVO) { + public List getMenuList(MenuListReqVO reqVO) { return menuMapper.selectList(reqVO); } @@ -223,23 +223,23 @@ public class MenuServiceImpl implements MenuService { * @param childId 当前菜单编号 */ @VisibleForTesting - public void checkParentResource(Long parentId, Long childId) { - if (parentId == null || MenuIdEnum.ROOT.getId().equals(parentId)) { + void validateParentMenu(Long parentId, Long childId) { + if (parentId == null || ID_ROOT.equals(parentId)) { return; } // 不能设置自己为父菜单 if (parentId.equals(childId)) { - throw ServiceExceptionUtil.exception(MENU_PARENT_ERROR); + throw exception(MENU_PARENT_ERROR); } MenuDO menu = menuMapper.selectById(parentId); // 父菜单不存在 if (menu == null) { - throw ServiceExceptionUtil.exception(MENU_PARENT_NOT_EXISTS); + throw exception(MENU_PARENT_NOT_EXISTS); } // 父菜单必须是目录或者菜单类型 if (!MenuTypeEnum.DIR.getType().equals(menu.getType()) && !MenuTypeEnum.MENU.getType().equals(menu.getType())) { - throw ServiceExceptionUtil.exception(MENU_PARENT_NOT_DIR_OR_MENU); + throw exception(MENU_PARENT_NOT_DIR_OR_MENU); } } @@ -253,17 +253,17 @@ public class MenuServiceImpl implements MenuService { * @param id 菜单编号 */ @VisibleForTesting - public void checkResource(Long parentId, String name, Long id) { + void validateMenu(Long parentId, String name, Long id) { MenuDO menu = menuMapper.selectByParentIdAndName(parentId, name); if (menu == null) { return; } // 如果 id 为空,说明不用比较是否为相同 id 的菜单 if (id == null) { - throw ServiceExceptionUtil.exception(MENU_NAME_DUPLICATE); + throw exception(MENU_NAME_DUPLICATE); } if (!menu.getId().equals(id)) { - throw ServiceExceptionUtil.exception(MENU_NAME_DUPLICATE); + throw exception(MENU_NAME_DUPLICATE); } } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/permission/PermissionServiceImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/permission/PermissionServiceImpl.java index c40a8e31c..43365cf46 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/permission/PermissionServiceImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/permission/PermissionServiceImpl.java @@ -158,7 +158,7 @@ public class PermissionServiceImpl implements PermissionService { } // 判断角色是否包含超级管理员。如果是超级管理员,获取到全部 - List roleList = roleService.getRolesFromCache(roleIds); + List roleList = roleService.getRoleListFromCache(roleIds); if (roleService.hasAnySuperAdmin(roleList)) { return menuService.getMenuListFromCache(menuTypes, menusStatuses); } @@ -190,7 +190,7 @@ public class PermissionServiceImpl implements PermissionService { public Set getRoleMenuIds(Long roleId) { // 如果是管理员的情况下,获取全部菜单编号 if (roleService.hasAnySuperAdmin(Collections.singleton(roleId))) { - return convertSet(menuService.getMenus(), MenuDO::getId); + return convertSet(menuService.getMenuList(), MenuDO::getId); } // 如果是非管理员的情况下,获得拥有的菜单编号 return convertSet(roleMenuMapper.selectListByRoleId(roleId), RoleMenuDO::getMenuId); @@ -371,7 +371,7 @@ public class PermissionServiceImpl implements PermissionService { if (roleService.hasAnySuperAdmin(roleIds)) { return true; } - Set userRoles = convertSet(roleService.getRolesFromCache(roleIds), + Set userRoles = convertSet(roleService.getRoleListFromCache(roleIds), RoleDO::getCode); return CollUtil.containsAny(userRoles, Sets.newHashSet(roles)); } @@ -388,7 +388,7 @@ public class PermissionServiceImpl implements PermissionService { result.setSelf(true); return result; } - List roles = roleService.getRolesFromCache(roleIds); + List roles = roleService.getRoleListFromCache(roleIds); // 获得用户的部门编号的缓存,通过 Guava 的 Suppliers 惰性求值,即有且仅有第一次发起 DB 的查询 Supplier userDeptIdCache = Suppliers.memoize(() -> userService.getUser(userId).getDeptId()); @@ -418,7 +418,7 @@ public class PermissionServiceImpl implements PermissionService { } // 情况四,DEPT_DEPT_AND_CHILD if (Objects.equals(role.getDataScope(), DataScopeEnum.DEPT_AND_CHILD.getScope())) { - List depts = deptService.getDeptsByParentIdFromCache(userDeptIdCache.get(), true); + List depts = deptService.getDeptListByParentIdFromCache(userDeptIdCache.get(), true); CollUtil.addAll(result.getDeptIds(), CollectionUtils.convertList(depts, DeptDO::getId)); // 添加本身部门编号 CollUtil.addAll(result.getDeptIds(), userDeptIdCache.get()); diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/permission/RoleService.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/permission/RoleService.java index a06095844..70acbdcb7 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/permission/RoleService.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/permission/RoleService.java @@ -79,7 +79,7 @@ public interface RoleService { * @param statuses 筛选的状态。允许空,空时不筛选 * @return 角色列表 */ - List getRoles(@Nullable Collection statuses); + List getRoleListByStatus(@Nullable Collection statuses); /** * 获得角色数组,从缓存中 @@ -87,7 +87,7 @@ public interface RoleService { * @param ids 角色编号数组 * @return 角色数组 */ - List getRolesFromCache(Collection ids); + List getRoleListFromCache(Collection ids); /** * 判断角色数组中,是否有超级管理员 @@ -104,7 +104,7 @@ public interface RoleService { * @return 是否有管理员 */ default boolean hasAnySuperAdmin(Set ids) { - return hasAnySuperAdmin(getRolesFromCache(ids)); + return hasAnySuperAdmin(getRoleListFromCache(ids)); } /** @@ -138,6 +138,6 @@ public interface RoleService { * * @param ids 角色编号数组 */ - void validRoles(Collection ids); + void validateRoleList(Collection ids); } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/permission/RoleServiceImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/permission/RoleServiceImpl.java index 3f9ee1351..30ac2daa0 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/permission/RoleServiceImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/permission/RoleServiceImpl.java @@ -5,7 +5,6 @@ import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.util.ObjectUtil; import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum; import cn.iocoder.yudao.framework.common.pojo.PageResult; -import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils; import cn.iocoder.yudao.framework.tenant.core.util.TenantUtils; import cn.iocoder.yudao.module.system.controller.admin.permission.vo.role.RoleCreateReqVO; import cn.iocoder.yudao.module.system.controller.admin.permission.vo.role.RoleExportReqVO; @@ -34,6 +33,7 @@ import java.util.*; import java.util.stream.Collectors; import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; +import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertMap; import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*; /** @@ -76,7 +76,7 @@ public class RoleServiceImpl implements RoleService { log.info("[initLocalCache][缓存角色,数量为:{}]", roleList.size()); // 第二步:构建缓存 - roleCache = CollectionUtils.convertMap(roleList, RoleDO::getId); + roleCache = convertMap(roleList, RoleDO::getId); }); } @@ -84,7 +84,7 @@ public class RoleServiceImpl implements RoleService { @Transactional public Long createRole(RoleCreateReqVO reqVO, Integer type) { // 校验角色 - checkDuplicateRole(reqVO.getName(), reqVO.getCode(), null); + validateRoleDuplicate(reqVO.getName(), reqVO.getCode(), null); // 插入到数据库 RoleDO role = RoleConvert.INSTANCE.convert(reqVO); role.setType(ObjectUtil.defaultIfNull(type, RoleTypeEnum.CUSTOM.getType())); @@ -105,13 +105,13 @@ public class RoleServiceImpl implements RoleService { @Override public void updateRole(RoleUpdateReqVO reqVO) { // 校验是否可以更新 - checkUpdateRole(reqVO.getId()); + validateRoleForUpdate(reqVO.getId()); // 校验角色的唯一字段是否重复 - checkDuplicateRole(reqVO.getName(), reqVO.getCode(), reqVO.getId()); + validateRoleDuplicate(reqVO.getName(), reqVO.getCode(), reqVO.getId()); // 更新到数据库 - RoleDO updateObject = RoleConvert.INSTANCE.convert(reqVO); - roleMapper.updateById(updateObject); + RoleDO updateObj = RoleConvert.INSTANCE.convert(reqVO); + roleMapper.updateById(updateObj); // 发送刷新消息 roleProducer.sendRoleRefreshMessage(); } @@ -119,12 +119,11 @@ public class RoleServiceImpl implements RoleService { @Override public void updateRoleStatus(Long id, Integer status) { // 校验是否可以更新 - checkUpdateRole(id); + validateRoleForUpdate(id); + // 更新状态 - RoleDO updateObject = new RoleDO(); - updateObject.setId(id); - updateObject.setStatus(status); - roleMapper.updateById(updateObject); + RoleDO updateObj = new RoleDO().setId(id).setStatus(status); + roleMapper.updateById(updateObj); // 发送刷新消息 roleProducer.sendRoleRefreshMessage(); } @@ -132,7 +131,8 @@ public class RoleServiceImpl implements RoleService { @Override public void updateRoleDataScope(Long id, Integer dataScope, Set dataScopeDeptIds) { // 校验是否可以更新 - checkUpdateRole(id); + validateRoleForUpdate(id); + // 更新数据范围 RoleDO updateObject = new RoleDO(); updateObject.setId(id); @@ -147,7 +147,7 @@ public class RoleServiceImpl implements RoleService { @Transactional(rollbackFor = Exception.class) public void deleteRole(Long id) { // 校验是否可以更新 - this.checkUpdateRole(id); + validateRoleForUpdate(id); // 标记删除 roleMapper.deleteById(id); // 删除相关数据 @@ -169,7 +169,7 @@ public class RoleServiceImpl implements RoleService { } @Override - public List getRoles(@Nullable Collection statuses) { + public List getRoleListByStatus(@Nullable Collection statuses) { if (CollUtil.isEmpty(statuses)) { return roleMapper.selectList(); } @@ -177,7 +177,7 @@ public class RoleServiceImpl implements RoleService { } @Override - public List getRolesFromCache(Collection ids) { + public List getRoleListFromCache(Collection ids) { if (CollectionUtil.isEmpty(ids)) { return Collections.emptyList(); } @@ -219,7 +219,7 @@ public class RoleServiceImpl implements RoleService { * @param id 角色编号 */ @VisibleForTesting - public void checkDuplicateRole(String name, String code, Long id) { + void validateRoleDuplicate(String name, String code, Long id) { // 0. 超级管理员,不允许创建 if (RoleCodeEnum.isSuperAdmin(code)) { throw exception(ROLE_ADMIN_CODE_ERROR, code); @@ -246,7 +246,7 @@ public class RoleServiceImpl implements RoleService { * @param id 角色编号 */ @VisibleForTesting - public void checkUpdateRole(Long id) { + void validateRoleForUpdate(Long id) { RoleDO roleDO = roleMapper.selectById(id); if (roleDO == null) { throw exception(ROLE_NOT_EXISTS); @@ -258,13 +258,13 @@ public class RoleServiceImpl implements RoleService { } @Override - public void validRoles(Collection ids) { + public void validateRoleList(Collection ids) { if (CollUtil.isEmpty(ids)) { return; } // 获得角色信息 List roles = roleMapper.selectBatchIds(ids); - Map roleMap = CollectionUtils.convertMap(roles, RoleDO::getId); + Map roleMap = convertMap(roles, RoleDO::getId); // 校验 ids.forEach(id -> { RoleDO role = roleMap.get(id); diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sensitiveword/SensitiveWordService.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sensitiveword/SensitiveWordService.java index 29cd55e6e..a852ec9cf 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sensitiveword/SensitiveWordService.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sensitiveword/SensitiveWordService.java @@ -81,7 +81,7 @@ public interface SensitiveWordService { * * @return 标签数组 */ - Set getSensitiveWordTags(); + Set getSensitiveWordTagSet(); /** * 获得文本所包含的不合法的敏感词数组 diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sensitiveword/SensitiveWordServiceImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sensitiveword/SensitiveWordServiceImpl.java index 53357753f..b82807855 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sensitiveword/SensitiveWordServiceImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sensitiveword/SensitiveWordServiceImpl.java @@ -25,6 +25,7 @@ import javax.annotation.Resource; import java.util.*; import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; +import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.filterList; import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.SENSITIVE_WORD_EXISTS; import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.SENSITIVE_WORD_NOT_EXISTS; @@ -85,7 +86,7 @@ public class SensitiveWordServiceImpl implements SensitiveWordService { private void initSensitiveWordTrie(List wordDOs) { // 过滤禁用的敏感词 - wordDOs = CollectionUtils.filterList(wordDOs, word -> word.getStatus().equals(CommonStatusEnum.ENABLE.getStatus())); + wordDOs = filterList(wordDOs, word -> word.getStatus().equals(CommonStatusEnum.ENABLE.getStatus())); // 初始化默认的 defaultSensitiveWordTrie this.defaultSensitiveWordTrie = new SimpleTrie(CollectionUtils.convertList(wordDOs, SensitiveWordDO::getName)); @@ -107,7 +108,8 @@ public class SensitiveWordServiceImpl implements SensitiveWordService { @Override public Long createSensitiveWord(SensitiveWordCreateReqVO createReqVO) { // 校验唯一性 - checkSensitiveWordNameUnique(null, createReqVO.getName()); + validateSensitiveWordNameUnique(null, createReqVO.getName()); + // 插入 SensitiveWordDO sensitiveWord = SensitiveWordConvert.INSTANCE.convert(createReqVO); sensitiveWordMapper.insert(sensitiveWord); @@ -119,8 +121,9 @@ public class SensitiveWordServiceImpl implements SensitiveWordService { @Override public void updateSensitiveWord(SensitiveWordUpdateReqVO updateReqVO) { // 校验唯一性 - checkSensitiveWordExists(updateReqVO.getId()); - checkSensitiveWordNameUnique(updateReqVO.getId(), updateReqVO.getName()); + validateSensitiveWordExists(updateReqVO.getId()); + validateSensitiveWordNameUnique(updateReqVO.getId(), updateReqVO.getName()); + // 更新 SensitiveWordDO updateObj = SensitiveWordConvert.INSTANCE.convert(updateReqVO); sensitiveWordMapper.updateById(updateObj); @@ -131,14 +134,14 @@ public class SensitiveWordServiceImpl implements SensitiveWordService { @Override public void deleteSensitiveWord(Long id) { // 校验存在 - checkSensitiveWordExists(id); + validateSensitiveWordExists(id); // 删除 sensitiveWordMapper.deleteById(id); // 发送消息,刷新缓存 sensitiveWordProducer.sendSensitiveWordRefreshMessage(); } - private void checkSensitiveWordNameUnique(Long id, String name) { + private void validateSensitiveWordNameUnique(Long id, String name) { SensitiveWordDO word = sensitiveWordMapper.selectByName(name); if (word == null) { return; @@ -152,7 +155,7 @@ public class SensitiveWordServiceImpl implements SensitiveWordService { } } - private void checkSensitiveWordExists(Long id) { + private void validateSensitiveWordExists(Long id) { if (sensitiveWordMapper.selectById(id) == null) { throw exception(SENSITIVE_WORD_NOT_EXISTS); } @@ -179,7 +182,7 @@ public class SensitiveWordServiceImpl implements SensitiveWordService { } @Override - public Set getSensitiveWordTags() { + public Set getSensitiveWordTagSet() { return sensitiveWordTagsCache; } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sms/SmsChannelService.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sms/SmsChannelService.java index fb0b707d7..c0bb3f8cd 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sms/SmsChannelService.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sms/SmsChannelService.java @@ -1,13 +1,12 @@ package cn.iocoder.yudao.module.system.service.sms; -import cn.iocoder.yudao.module.system.dal.dataobject.sms.SmsChannelDO; import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.module.system.controller.admin.sms.vo.channel.SmsChannelCreateReqVO; import cn.iocoder.yudao.module.system.controller.admin.sms.vo.channel.SmsChannelPageReqVO; import cn.iocoder.yudao.module.system.controller.admin.sms.vo.channel.SmsChannelUpdateReqVO; +import cn.iocoder.yudao.module.system.dal.dataobject.sms.SmsChannelDO; import javax.validation.Valid; -import java.util.Collection; import java.util.List; /** @@ -53,14 +52,6 @@ public interface SmsChannelService { */ SmsChannelDO getSmsChannel(Long id); - /** - * 获得短信渠道列表 - * - * @param ids 编号 - * @return 短信渠道列表 - */ - List getSmsChannelList(Collection ids); - /** * 获得所有短信渠道列表 * diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sms/SmsChannelServiceImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sms/SmsChannelServiceImpl.java index d126fbf0f..d6f8aa004 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sms/SmsChannelServiceImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sms/SmsChannelServiceImpl.java @@ -15,7 +15,6 @@ import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; import javax.annotation.Resource; -import java.util.Collection; import java.util.List; import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; @@ -69,7 +68,7 @@ public class SmsChannelServiceImpl implements SmsChannelService { @Override public void updateSmsChannel(SmsChannelUpdateReqVO updateReqVO) { // 校验存在 - this.validateSmsChannelExists(updateReqVO.getId()); + validateSmsChannelExists(updateReqVO.getId()); // 更新 SmsChannelDO updateObj = SmsChannelConvert.INSTANCE.convert(updateReqVO); smsChannelMapper.updateById(updateObj); @@ -80,7 +79,7 @@ public class SmsChannelServiceImpl implements SmsChannelService { @Override public void deleteSmsChannel(Long id) { // 校验存在 - this.validateSmsChannelExists(id); + validateSmsChannelExists(id); // 校验是否有在使用该账号的模版 if (smsTemplateService.countByChannelId(id) > 0) { throw exception(SMS_CHANNEL_HAS_CHILDREN); @@ -102,11 +101,6 @@ public class SmsChannelServiceImpl implements SmsChannelService { return smsChannelMapper.selectById(id); } - @Override - public List getSmsChannelList(Collection ids) { - return smsChannelMapper.selectBatchIds(ids); - } - @Override public List getSmsChannelList() { return smsChannelMapper.selectList(); diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sms/SmsCodeService.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sms/SmsCodeService.java index f71b8a6bd..c310949b2 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sms/SmsCodeService.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sms/SmsCodeService.java @@ -1,7 +1,7 @@ package cn.iocoder.yudao.module.system.service.sms; import cn.iocoder.yudao.framework.common.exception.ServiceException; -import cn.iocoder.yudao.module.system.api.sms.dto.code.SmsCodeCheckReqDTO; +import cn.iocoder.yudao.module.system.api.sms.dto.code.SmsCodeValidateReqDTO; import cn.iocoder.yudao.module.system.api.sms.dto.code.SmsCodeSendReqDTO; import cn.iocoder.yudao.module.system.api.sms.dto.code.SmsCodeUseReqDTO; @@ -35,6 +35,6 @@ public interface SmsCodeService { * * @param reqDTO 校验请求 */ - void checkSmsCode(@Valid SmsCodeCheckReqDTO reqDTO); + void validateSmsCode(@Valid SmsCodeValidateReqDTO reqDTO); } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sms/SmsCodeServiceImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sms/SmsCodeServiceImpl.java index 778445dd9..682b89eff 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sms/SmsCodeServiceImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sms/SmsCodeServiceImpl.java @@ -3,11 +3,9 @@ package cn.iocoder.yudao.module.system.service.sms; import cn.hutool.core.date.LocalDateTimeUtil; import cn.hutool.core.lang.Assert; import cn.hutool.core.map.MapUtil; -import cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil; -import cn.iocoder.yudao.framework.common.util.date.DateUtils; -import cn.iocoder.yudao.module.system.api.sms.dto.code.SmsCodeCheckReqDTO; import cn.iocoder.yudao.module.system.api.sms.dto.code.SmsCodeSendReqDTO; import cn.iocoder.yudao.module.system.api.sms.dto.code.SmsCodeUseReqDTO; +import cn.iocoder.yudao.module.system.api.sms.dto.code.SmsCodeValidateReqDTO; import cn.iocoder.yudao.module.system.dal.dataobject.sms.SmsCodeDO; import cn.iocoder.yudao.module.system.dal.mysql.sms.SmsCodeMapper; import cn.iocoder.yudao.module.system.enums.sms.SmsSceneEnum; @@ -16,11 +14,11 @@ import org.springframework.stereotype.Service; import org.springframework.validation.annotation.Validated; import javax.annotation.Resource; - import java.time.LocalDateTime; -import java.time.temporal.ChronoUnit; import static cn.hutool.core.util.RandomUtil.randomInt; +import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; +import static cn.iocoder.yudao.framework.common.util.date.DateUtils.isToday; import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*; /** @@ -58,11 +56,11 @@ public class SmsCodeServiceImpl implements SmsCodeService { if (lastSmsCode != null) { if (LocalDateTimeUtil.between(lastSmsCode.getCreateTime(), LocalDateTime.now()).toMillis() < smsCodeProperties.getSendFrequency().toMillis()) { // 发送过于频繁 - throw ServiceExceptionUtil.exception(SMS_CODE_SEND_TOO_FAST); + throw exception(SMS_CODE_SEND_TOO_FAST); } - if (DateUtils.isToday(lastSmsCode.getCreateTime()) && // 必须是今天,才能计算超过当天的上限 + if (isToday(lastSmsCode.getCreateTime()) && // 必须是今天,才能计算超过当天的上限 lastSmsCode.getTodayIndex() >= smsCodeProperties.getSendMaximumQuantityPerDay()) { // 超过当天发送的上限。 - throw ServiceExceptionUtil.exception(SMS_CODE_EXCEED_SEND_MAXIMUM_QUANTITY_PER_DAY); + throw exception(SMS_CODE_EXCEED_SEND_MAXIMUM_QUANTITY_PER_DAY); } // TODO 芋艿:提升,每个 IP 每天可发送数量 // TODO 芋艿:提升,每个 IP 每小时可发送数量 @@ -71,7 +69,7 @@ public class SmsCodeServiceImpl implements SmsCodeService { // 创建验证码记录 String code = String.valueOf(randomInt(smsCodeProperties.getBeginCode(), smsCodeProperties.getEndCode() + 1)); SmsCodeDO newSmsCode = SmsCodeDO.builder().mobile(mobile).code(code).scene(scene) - .todayIndex(lastSmsCode != null && DateUtils.isToday(lastSmsCode.getCreateTime()) ? lastSmsCode.getTodayIndex() + 1 : 1) + .todayIndex(lastSmsCode != null && isToday(lastSmsCode.getCreateTime()) ? lastSmsCode.getTodayIndex() + 1 : 1) .createIp(ip).used(false).build(); smsCodeMapper.insert(newSmsCode); return code; @@ -80,32 +78,32 @@ public class SmsCodeServiceImpl implements SmsCodeService { @Override public void useSmsCode(SmsCodeUseReqDTO reqDTO) { // 检测验证码是否有效 - SmsCodeDO lastSmsCode = this.checkSmsCode0(reqDTO.getMobile(), reqDTO.getCode(), reqDTO.getScene()); + SmsCodeDO lastSmsCode = validateSmsCode0(reqDTO.getMobile(), reqDTO.getCode(), reqDTO.getScene()); // 使用验证码 smsCodeMapper.updateById(SmsCodeDO.builder().id(lastSmsCode.getId()) .used(true).usedTime(LocalDateTime.now()).usedIp(reqDTO.getUsedIp()).build()); } @Override - public void checkSmsCode(SmsCodeCheckReqDTO reqDTO) { - checkSmsCode0(reqDTO.getMobile(), reqDTO.getCode(), reqDTO.getScene()); + public void validateSmsCode(SmsCodeValidateReqDTO reqDTO) { + validateSmsCode0(reqDTO.getMobile(), reqDTO.getCode(), reqDTO.getScene()); } - public SmsCodeDO checkSmsCode0(String mobile, String code, Integer scene) { + private SmsCodeDO validateSmsCode0(String mobile, String code, Integer scene) { // 校验验证码 SmsCodeDO lastSmsCode = smsCodeMapper.selectLastByMobile(mobile, code, scene); // 若验证码不存在,抛出异常 if (lastSmsCode == null) { - throw ServiceExceptionUtil.exception(SMS_CODE_NOT_FOUND); + throw exception(SMS_CODE_NOT_FOUND); } // 超过时间 if (LocalDateTimeUtil.between(lastSmsCode.getCreateTime(), LocalDateTime.now()).toMillis() >= smsCodeProperties.getExpireTimes().toMillis()) { // 验证码已过期 - throw ServiceExceptionUtil.exception(SMS_CODE_EXPIRED); + throw exception(SMS_CODE_EXPIRED); } // 判断验证码是否已被使用 if (Boolean.TRUE.equals(lastSmsCode.getUsed())) { - throw ServiceExceptionUtil.exception(SMS_CODE_USED); + throw exception(SMS_CODE_USED); } return lastSmsCode; } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sms/SmsSendServiceImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sms/SmsSendServiceImpl.java index 85fee7ff4..af4aa32fc 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sms/SmsSendServiceImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sms/SmsSendServiceImpl.java @@ -66,7 +66,7 @@ public class SmsSendServiceImpl implements SmsSendService { } } // 执行发送 - return this.sendSingleSms(mobile, userId, UserTypeEnum.ADMIN.getValue(), templateCode, templateParams); + return sendSingleSms(mobile, userId, UserTypeEnum.ADMIN.getValue(), templateCode, templateParams); } @Override @@ -76,21 +76,21 @@ public class SmsSendServiceImpl implements SmsSendService { mobile = memberService.getMemberUserMobile(userId); } // 执行发送 - return this.sendSingleSms(mobile, userId, UserTypeEnum.MEMBER.getValue(), templateCode, templateParams); + return sendSingleSms(mobile, userId, UserTypeEnum.MEMBER.getValue(), templateCode, templateParams); } @Override public Long sendSingleSms(String mobile, Long userId, Integer userType, String templateCode, Map templateParams) { // 校验短信模板是否合法 - SmsTemplateDO template = this.checkSmsTemplateValid(templateCode); + SmsTemplateDO template = validateSmsTemplate(templateCode); // 校验短信渠道是否合法 - SmsChannelDO smsChannel = this.checkSmsChannelValid(template.getChannelId()); + SmsChannelDO smsChannel = validateSmsChannel(template.getChannelId()); // 校验手机号码是否存在 - mobile = this.checkMobile(mobile); + mobile = validateMobile(mobile); // 构建有序的模板参数。为什么放在这个位置,是提前保证模板参数的正确性,而不是到了插入发送日志 - List> newTemplateParams = this.buildTemplateParams(template, templateParams); + List> newTemplateParams = buildTemplateParams(template, templateParams); // 创建发送日志。如果模板被禁用,则不发送短信,只记录日志 Boolean isSend = CommonStatusEnum.ENABLE.getStatus().equals(template.getStatus()) @@ -108,7 +108,7 @@ public class SmsSendServiceImpl implements SmsSendService { } @VisibleForTesting - public SmsChannelDO checkSmsChannelValid(Long channelId) { + SmsChannelDO validateSmsChannel(Long channelId) { // 获得短信模板。考虑到效率,从缓存中获取 SmsChannelDO channelDO = smsChannelService.getSmsChannel(channelId); // 短信模板不存在 @@ -119,7 +119,7 @@ public class SmsSendServiceImpl implements SmsSendService { } @VisibleForTesting - public SmsTemplateDO checkSmsTemplateValid(String templateCode) { + SmsTemplateDO validateSmsTemplate(String templateCode) { // 获得短信模板。考虑到效率,从缓存中获取 SmsTemplateDO template = smsTemplateService.getSmsTemplateByCodeFromCache(templateCode); // 短信模板不存在 @@ -139,7 +139,7 @@ public class SmsSendServiceImpl implements SmsSendService { * @return 处理后的参数 */ @VisibleForTesting - public List> buildTemplateParams(SmsTemplateDO template, Map templateParams) { + List> buildTemplateParams(SmsTemplateDO template, Map templateParams) { return template.getParams().stream().map(key -> { Object value = templateParams.get(key); if (value == null) { @@ -150,7 +150,7 @@ public class SmsSendServiceImpl implements SmsSendService { } @VisibleForTesting - public String checkMobile(String mobile) { + public String validateMobile(String mobile) { if (StrUtil.isEmpty(mobile)) { throw exception(SMS_SEND_MOBILE_NOT_EXISTS); } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sms/SmsTemplateServiceImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sms/SmsTemplateServiceImpl.java index 031edb7cc..20c4ec3f3 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sms/SmsTemplateServiceImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sms/SmsTemplateServiceImpl.java @@ -105,11 +105,11 @@ public class SmsTemplateServiceImpl implements SmsTemplateService { @Override public Long createSmsTemplate(SmsTemplateCreateReqVO createReqVO) { // 校验短信渠道 - SmsChannelDO channelDO = checkSmsChannel(createReqVO.getChannelId()); + SmsChannelDO channelDO = validateSmsChannel(createReqVO.getChannelId()); // 校验短信编码是否重复 - checkSmsTemplateCodeDuplicate(null, createReqVO.getCode()); + validateSmsTemplateCodeDuplicate(null, createReqVO.getCode()); // 校验短信模板 - checkApiTemplate(createReqVO.getChannelId(), createReqVO.getApiTemplateId()); + validateApiTemplate(createReqVO.getChannelId(), createReqVO.getApiTemplateId()); // 插入 SmsTemplateDO template = SmsTemplateConvert.INSTANCE.convert(createReqVO); @@ -125,13 +125,13 @@ public class SmsTemplateServiceImpl implements SmsTemplateService { @Override public void updateSmsTemplate(SmsTemplateUpdateReqVO updateReqVO) { // 校验存在 - this.validateSmsTemplateExists(updateReqVO.getId()); + validateSmsTemplateExists(updateReqVO.getId()); // 校验短信渠道 - SmsChannelDO channelDO = checkSmsChannel(updateReqVO.getChannelId()); + SmsChannelDO channelDO = validateSmsChannel(updateReqVO.getChannelId()); // 校验短信编码是否重复 - checkSmsTemplateCodeDuplicate(updateReqVO.getId(), updateReqVO.getCode()); + validateSmsTemplateCodeDuplicate(updateReqVO.getId(), updateReqVO.getCode()); // 校验短信模板 - checkApiTemplate(updateReqVO.getChannelId(), updateReqVO.getApiTemplateId()); + validateApiTemplate(updateReqVO.getChannelId(), updateReqVO.getApiTemplateId()); // 更新 SmsTemplateDO updateObj = SmsTemplateConvert.INSTANCE.convert(updateReqVO); @@ -145,7 +145,7 @@ public class SmsTemplateServiceImpl implements SmsTemplateService { @Override public void deleteSmsTemplate(Long id) { // 校验存在 - this.validateSmsTemplateExists(id); + validateSmsTemplateExists(id); // 更新 smsTemplateMapper.deleteById(id); // 发送刷新消息 @@ -184,7 +184,7 @@ public class SmsTemplateServiceImpl implements SmsTemplateService { } @VisibleForTesting - public SmsChannelDO checkSmsChannel(Long channelId) { + public SmsChannelDO validateSmsChannel(Long channelId) { SmsChannelDO channelDO = smsChannelService.getSmsChannel(channelId); if (channelDO == null) { throw exception(SMS_CHANNEL_NOT_EXISTS); @@ -196,7 +196,7 @@ public class SmsTemplateServiceImpl implements SmsTemplateService { } @VisibleForTesting - public void checkSmsTemplateCodeDuplicate(Long id, String code) { + public void validateSmsTemplateCodeDuplicate(Long id, String code) { SmsTemplateDO template = smsTemplateMapper.selectByCode(code); if (template == null) { return; @@ -217,7 +217,7 @@ public class SmsTemplateServiceImpl implements SmsTemplateService { * @param apiTemplateId API 模板编号 */ @VisibleForTesting - public void checkApiTemplate(Long channelId, String apiTemplateId) { + public void validateApiTemplate(Long channelId, String apiTemplateId) { // 获得短信模板 SmsClient smsClient = smsClientFactory.getSmsClient(channelId); Assert.notNull(smsClient, String.format("短信客户端(%d) 不存在", channelId)); diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/tenant/TenantPackageServiceImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/tenant/TenantPackageServiceImpl.java index 2528cb905..4e6e60198 100755 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/tenant/TenantPackageServiceImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/tenant/TenantPackageServiceImpl.java @@ -64,9 +64,9 @@ public class TenantPackageServiceImpl implements TenantPackageService { @Override public void deleteTenantPackage(Long id) { // 校验存在 - this.validateTenantPackageExists(id); + validateTenantPackageExists(id); // 校验正在使用 - this.validateTenantUsed(id); + validateTenantUsed(id); // 删除 tenantPackageMapper.deleteById(id); } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/tenant/TenantService.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/tenant/TenantService.java index d9d55e9f4..3dacfefe7 100755 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/tenant/TenantService.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/tenant/TenantService.java @@ -120,7 +120,7 @@ public interface TenantService { * * @return 租户编号数组 */ - List getTenantIds(); + List getTenantIdList(); /** * 校验租户是否合法 diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/tenant/TenantServiceImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/tenant/TenantServiceImpl.java index dc4a67ef0..3a70d31b9 100755 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/tenant/TenantServiceImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/tenant/TenantServiceImpl.java @@ -75,7 +75,7 @@ public class TenantServiceImpl implements TenantService { private PermissionService permissionService; @Override - public List getTenantIds() { + public List getTenantIdList() { List tenants = tenantMapper.selectList(); return CollectionUtils.convertList(tenants, TenantDO::getId); } @@ -138,7 +138,7 @@ public class TenantServiceImpl implements TenantService { @Transactional(rollbackFor = Exception.class) public void updateTenant(TenantUpdateReqVO updateReqVO) { // 校验存在 - TenantDO tenant = checkUpdateTenant(updateReqVO.getId()); + TenantDO tenant = validateUpdateTenant(updateReqVO.getId()); // 校验套餐被禁用 TenantPackageDO tenantPackage = tenantPackageService.validTenantPackage(updateReqVO.getPackageId()); @@ -156,7 +156,7 @@ public class TenantServiceImpl implements TenantService { public void updateTenantRoleMenu(Long tenantId, Set menuIds) { TenantUtils.execute(tenantId, () -> { // 获得所有角色 - List roles = roleService.getRoles(null); + List roles = roleService.getRoleListByStatus(null); roles.forEach(role -> Assert.isTrue(tenantId.equals(role.getTenantId()), "角色({}/{}) 租户不匹配", role.getId(), role.getTenantId(), tenantId)); // 兜底校验 // 重新分配每个角色的权限 @@ -179,12 +179,12 @@ public class TenantServiceImpl implements TenantService { @Override public void deleteTenant(Long id) { // 校验存在 - checkUpdateTenant(id); + validateUpdateTenant(id); // 删除 tenantMapper.deleteById(id); } - private TenantDO checkUpdateTenant(Long id) { + private TenantDO validateUpdateTenant(Long id) { TenantDO tenant = tenantMapper.selectById(id); if (tenant == null) { throw exception(TENANT_NOT_EXISTS); @@ -248,7 +248,7 @@ public class TenantServiceImpl implements TenantService { TenantDO tenant = getTenant(TenantContextHolder.getRequiredTenantId()); Set menuIds; if (isSystemTenant(tenant)) { // 系统租户,菜单是全量的 - menuIds = CollectionUtils.convertSet(menuService.getMenus(), MenuDO::getId); + menuIds = CollectionUtils.convertSet(menuService.getMenuList(), MenuDO::getId); } else { menuIds = tenantPackageService.getTenantPackage(tenant.getPackageId()).getMenuIds(); } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/user/AdminUserService.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/user/AdminUserService.java index ae3245de2..e10b9e997 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/user/AdminUserService.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/user/AdminUserService.java @@ -127,7 +127,7 @@ public interface AdminUserService { * @param deptIds 部门数组 * @return 用户数组 */ - List getUsersByDeptIds(Collection deptIds); + List getUserListByDeptIds(Collection deptIds); /** * 获得指定岗位的用户数组 @@ -135,7 +135,7 @@ public interface AdminUserService { * @param postIds 岗位数组 * @return 用户数组 */ - List getUsersByPostIds(Collection postIds); + List getUserListByPostIds(Collection postIds); /** * 获得用户列表 @@ -143,7 +143,7 @@ public interface AdminUserService { * @param ids 用户编号数组 * @return 用户列表 */ - List getUsers(Collection ids); + List getUserList(Collection ids); /** * 校验用户们是否有效。如下情况,视为无效: @@ -152,7 +152,7 @@ public interface AdminUserService { * * @param ids 用户编号数组 */ - void validUsers(Set ids); + void validateUserList(Collection ids); /** * 获得用户 Map @@ -164,7 +164,7 @@ public interface AdminUserService { if (CollUtil.isEmpty(ids)) { return new HashMap<>(); } - return CollectionUtils.convertMap(getUsers(ids), AdminUserDO::getId); + return CollectionUtils.convertMap(getUserList(ids), AdminUserDO::getId); } /** @@ -173,7 +173,7 @@ public interface AdminUserService { * @param reqVO 列表请求 * @return 用户列表 */ - List getUsers(UserExportReqVO reqVO); + List getUserList(UserExportReqVO reqVO); /** * 获得用户列表,基于昵称模糊匹配 @@ -181,15 +181,7 @@ public interface AdminUserService { * @param nickname 昵称 * @return 用户列表 */ - List getUsersByNickname(String nickname); - - /** - * 获得用户列表,基于用户账号模糊匹配 - * - * @param username 用户账号 - * @return 用户列表 - */ - List getUsersByUsername(String username); + List getUserListByNickname(String nickname); /** * 批量导入用户 @@ -198,7 +190,7 @@ public interface AdminUserService { * @param isUpdateSupport 是否支持更新 * @return 导入结果 */ - UserImportRespVO importUsers(List importUsers, boolean isUpdateSupport); + UserImportRespVO importUserList(List importUsers, boolean isUpdateSupport); /** * 获得指定状态的用户们 @@ -206,7 +198,7 @@ public interface AdminUserService { * @param status 状态 * @return 用户们 */ - List getUsersByStatus(Integer status); + List getUserListByStatus(Integer status); /** * 判断密码是否匹配 diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/user/AdminUserServiceImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/user/AdminUserServiceImpl.java index 1bb180011..bb43a89c2 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/user/AdminUserServiceImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/user/AdminUserServiceImpl.java @@ -8,7 +8,7 @@ import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum; import cn.iocoder.yudao.framework.common.exception.ServiceException; import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils; -import cn.iocoder.yudao.framework.datapermission.core.annotation.DataPermission; +import cn.iocoder.yudao.framework.datapermission.core.util.DataPermissionUtils; import cn.iocoder.yudao.module.infra.api.file.FileApi; import cn.iocoder.yudao.module.system.controller.admin.user.vo.profile.UserProfileUpdatePasswordReqVO; import cn.iocoder.yudao.module.system.controller.admin.user.vo.profile.UserProfileUpdateReqVO; @@ -43,6 +43,7 @@ import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*; /** * 后台用户 Service 实现类 + * * @author 芋道源码 */ @Service("adminUserService") @@ -73,10 +74,6 @@ public class AdminUserServiceImpl implements AdminUserService { @Resource private FileApi fileApi; - @Resource - @Lazy // 循环依赖(自己依赖自己),避免报错 - private AdminUserServiceImpl self; - @Override @Transactional(rollbackFor = Exception.class) public Long createUser(UserCreateReqVO reqVO) { @@ -88,7 +85,7 @@ public class AdminUserServiceImpl implements AdminUserService { } }); // 校验正确性 - self.checkCreateOrUpdate(null, reqVO.getUsername(), reqVO.getMobile(), reqVO.getEmail(), + validateUserForCreateOrUpdate(null, reqVO.getUsername(), reqVO.getMobile(), reqVO.getEmail(), reqVO.getDeptId(), reqVO.getPostIds()); // 插入用户 AdminUserDO user = UserConvert.INSTANCE.convert(reqVO); @@ -107,7 +104,7 @@ public class AdminUserServiceImpl implements AdminUserService { @Transactional(rollbackFor = Exception.class) public void updateUser(UserUpdateReqVO reqVO) { // 校验正确性 - self.checkCreateOrUpdate(reqVO.getId(), reqVO.getUsername(), reqVO.getMobile(), reqVO.getEmail(), + validateUserForCreateOrUpdate(reqVO.getId(), reqVO.getUsername(), reqVO.getMobile(), reqVO.getEmail(), reqVO.getDeptId(), reqVO.getPostIds()); // 更新用户 AdminUserDO updateObj = UserConvert.INSTANCE.convert(reqVO); @@ -141,9 +138,9 @@ public class AdminUserServiceImpl implements AdminUserService { @Override public void updateUserProfile(Long id, UserProfileUpdateReqVO reqVO) { // 校验正确性 - checkUserExists(id); - checkEmailUnique(id, reqVO.getEmail()); - checkMobileUnique(id, reqVO.getMobile()); + validateUserExists(id); + validateEmailUnique(id, reqVO.getEmail()); + validateMobileUnique(id, reqVO.getMobile()); // 执行更新 userMapper.updateById(UserConvert.INSTANCE.convert(reqVO).setId(id)); } @@ -151,7 +148,7 @@ public class AdminUserServiceImpl implements AdminUserService { @Override public void updateUserPassword(Long id, UserProfileUpdatePasswordReqVO reqVO) { // 校验旧密码密码 - checkOldPassword(id, reqVO.getOldPassword()); + validateOldPassword(id, reqVO.getOldPassword()); // 执行更新 AdminUserDO updateObj = new AdminUserDO().setId(id); updateObj.setPassword(encodePassword(reqVO.getNewPassword())); // 加密密码 @@ -160,7 +157,7 @@ public class AdminUserServiceImpl implements AdminUserService { @Override public String updateUserAvatar(Long id, InputStream avatarFile) throws Exception { - checkUserExists(id); + validateUserExists(id); // 存储文件 String avatar = fileApi.createFile(IoUtil.readBytes(avatarFile)); // 更新路径 @@ -174,7 +171,7 @@ public class AdminUserServiceImpl implements AdminUserService { @Override public void updateUserPassword(Long id, String password) { // 校验用户存在 - checkUserExists(id); + validateUserExists(id); // 更新密码 AdminUserDO updateObj = new AdminUserDO(); updateObj.setId(id); @@ -185,7 +182,7 @@ public class AdminUserServiceImpl implements AdminUserService { @Override public void updateUserStatus(Long id, Integer status) { // 校验用户存在 - checkUserExists(id); + validateUserExists(id); // 更新状态 AdminUserDO updateObj = new AdminUserDO(); updateObj.setId(id); @@ -197,7 +194,7 @@ public class AdminUserServiceImpl implements AdminUserService { @Transactional(rollbackFor = Exception.class) public void deleteUser(Long id) { // 校验用户存在 - checkUserExists(id); + validateUserExists(id); // 删除用户 userMapper.deleteById(id); // 删除用户关联数据 @@ -227,7 +224,7 @@ public class AdminUserServiceImpl implements AdminUserService { } @Override - public List getUsersByDeptIds(Collection deptIds) { + public List getUserListByDeptIds(Collection deptIds) { if (CollUtil.isEmpty(deptIds)) { return Collections.emptyList(); } @@ -235,7 +232,7 @@ public class AdminUserServiceImpl implements AdminUserService { } @Override - public List getUsersByPostIds(Collection postIds) { + public List getUserListByPostIds(Collection postIds) { if (CollUtil.isEmpty(postIds)) { return Collections.emptyList(); } @@ -247,7 +244,7 @@ public class AdminUserServiceImpl implements AdminUserService { } @Override - public List getUsers(Collection ids) { + public List getUserList(Collection ids) { if (CollUtil.isEmpty(ids)) { return Collections.emptyList(); } @@ -255,7 +252,7 @@ public class AdminUserServiceImpl implements AdminUserService { } @Override - public void validUsers(Set ids) { + public void validateUserList(Collection ids) { if (CollUtil.isEmpty(ids)) { return; } @@ -275,20 +272,15 @@ public class AdminUserServiceImpl implements AdminUserService { } @Override - public List getUsers(UserExportReqVO reqVO) { + public List getUserList(UserExportReqVO reqVO) { return userMapper.selectList(reqVO, getDeptCondition(reqVO.getDeptId())); } @Override - public List getUsersByNickname(String nickname) { + public List getUserListByNickname(String nickname) { return userMapper.selectListByNickname(nickname); } - @Override - public List getUsersByUsername(String username) { - return userMapper.selectListByUsername(username); - } - /** * 获得部门条件:查询指定部门的子部门编号们,包括自身 * @param deptId 部门编号 @@ -298,31 +290,33 @@ public class AdminUserServiceImpl implements AdminUserService { if (deptId == null) { return Collections.emptySet(); } - Set deptIds = convertSet(deptService.getDeptsByParentIdFromCache( + Set deptIds = convertSet(deptService.getDeptListByParentIdFromCache( deptId, true), DeptDO::getId); deptIds.add(deptId); // 包括自身 return deptIds; } - @DataPermission(enable = false) // 关闭数据权限,避免因为没有数据权限,查询不到数据,进而导致唯一校验不正确 - public void checkCreateOrUpdate(Long id, String username, String mobile, String email, - Long deptId, Set postIds) { - // 校验用户存在 - checkUserExists(id); - // 校验用户名唯一 - checkUsernameUnique(id, username); - // 校验手机号唯一 - checkMobileUnique(id, mobile); - // 校验邮箱唯一 - checkEmailUnique(id, email); - // 校验部门处于开启状态 - deptService.validDepts(CollectionUtils.singleton(deptId)); - // 校验岗位处于开启状态 - postService.validPosts(postIds); + private void validateUserForCreateOrUpdate(Long id, String username, String mobile, String email, + Long deptId, Set postIds) { + // 关闭数据权限,避免因为没有数据权限,查询不到数据,进而导致唯一校验不正确 + DataPermissionUtils.executeIgnore(() -> { + // 校验用户存在 + validateUserExists(id); + // 校验用户名唯一 + validateUsernameUnique(id, username); + // 校验手机号唯一 + validateMobileUnique(id, mobile); + // 校验邮箱唯一 + validateEmailUnique(id, email); + // 校验部门处于开启状态 + deptService.validateDeptList(CollectionUtils.singleton(deptId)); + // 校验岗位处于开启状态 + postService.validatePostList(postIds); + }); } @VisibleForTesting - public void checkUserExists(Long id) { + void validateUserExists(Long id) { if (id == null) { return; } @@ -333,7 +327,7 @@ public class AdminUserServiceImpl implements AdminUserService { } @VisibleForTesting - public void checkUsernameUnique(Long id, String username) { + void validateUsernameUnique(Long id, String username) { if (StrUtil.isBlank(username)) { return; } @@ -351,7 +345,7 @@ public class AdminUserServiceImpl implements AdminUserService { } @VisibleForTesting - public void checkEmailUnique(Long id, String email) { + void validateEmailUnique(Long id, String email) { if (StrUtil.isBlank(email)) { return; } @@ -369,7 +363,7 @@ public class AdminUserServiceImpl implements AdminUserService { } @VisibleForTesting - public void checkMobileUnique(Long id, String mobile) { + void validateMobileUnique(Long id, String mobile) { if (StrUtil.isBlank(mobile)) { return; } @@ -392,7 +386,7 @@ public class AdminUserServiceImpl implements AdminUserService { * @param oldPassword 旧密码 */ @VisibleForTesting - public void checkOldPassword(Long id, String oldPassword) { + void validateOldPassword(Long id, String oldPassword) { AdminUserDO user = userMapper.selectById(id); if (user == null) { throw exception(USER_NOT_EXISTS); @@ -404,7 +398,7 @@ public class AdminUserServiceImpl implements AdminUserService { @Override @Transactional(rollbackFor = Exception.class) // 添加事务,异常则回滚所有导入 - public UserImportRespVO importUsers(List importUsers, boolean isUpdateSupport) { + public UserImportRespVO importUserList(List importUsers, boolean isUpdateSupport) { if (CollUtil.isEmpty(importUsers)) { throw exception(USER_IMPORT_LIST_IS_EMPTY); } @@ -413,7 +407,7 @@ public class AdminUserServiceImpl implements AdminUserService { importUsers.forEach(importUser -> { // 校验,判断是否有不符合的原因 try { - checkCreateOrUpdate(null, null, importUser.getMobile(), importUser.getEmail(), + validateUserForCreateOrUpdate(null, null, importUser.getMobile(), importUser.getEmail(), importUser.getDeptId(), null); } catch (ServiceException ex) { respVO.getFailureUsernames().put(importUser.getUsername(), ex.getMessage()); @@ -441,7 +435,7 @@ public class AdminUserServiceImpl implements AdminUserService { } @Override - public List getUsersByStatus(Integer status) { + public List getUserListByStatus(Integer status) { return userMapper.selectListByStatus(status); } diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/auth/AdminAuthServiceImplTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/auth/AdminAuthServiceImplTest.java index dc607b7ce..16e48ec4a 100644 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/auth/AdminAuthServiceImplTest.java +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/auth/AdminAuthServiceImplTest.java @@ -1,31 +1,43 @@ package cn.iocoder.yudao.module.system.service.auth; +import cn.hutool.core.util.ReflectUtil; import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum; import cn.iocoder.yudao.framework.common.enums.UserTypeEnum; import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; -import cn.iocoder.yudao.framework.test.core.util.AssertUtils; import cn.iocoder.yudao.module.system.api.sms.SmsCodeApi; +import cn.iocoder.yudao.module.system.api.social.dto.SocialUserBindReqDTO; +import cn.iocoder.yudao.module.system.controller.admin.auth.vo.*; import cn.iocoder.yudao.module.system.dal.dataobject.oauth2.OAuth2AccessTokenDO; import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO; import cn.iocoder.yudao.module.system.enums.logger.LoginLogTypeEnum; import cn.iocoder.yudao.module.system.enums.logger.LoginResultEnum; +import cn.iocoder.yudao.module.system.enums.sms.SmsSceneEnum; +import cn.iocoder.yudao.module.system.enums.social.SocialTypeEnum; import cn.iocoder.yudao.module.system.service.logger.LoginLogService; import cn.iocoder.yudao.module.system.service.member.MemberService; import cn.iocoder.yudao.module.system.service.oauth2.OAuth2TokenService; import cn.iocoder.yudao.module.system.service.social.SocialUserService; import cn.iocoder.yudao.module.system.service.user.AdminUserService; +import com.xingyuv.captcha.model.common.ResponseModel; import com.xingyuv.captcha.service.CaptchaService; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import javax.annotation.Resource; +import javax.validation.ConstraintViolationException; +import javax.validation.Validation; import javax.validation.Validator; +import static cn.hutool.core.util.RandomUtil.randomEle; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; +import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomString; import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.*; @@ -42,17 +54,24 @@ public class AdminAuthServiceImplTest extends BaseDbUnitTest { @MockBean private LoginLogService loginLogService; @MockBean - private SocialUserService socialService; + private SocialUserService socialUserService; @MockBean private SmsCodeApi smsCodeApi; @MockBean private OAuth2TokenService oauth2TokenService; @MockBean private MemberService memberService; - @MockBean private Validator validator; + @BeforeEach + public void setUp() { + ReflectUtil.setFieldValue(authService, "captchaEnable", true); + // 注入一个 Validator 对象 + ReflectUtil.setFieldValue(authService, "validator", + Validation.buildDefaultValidatorFactory().getValidator()); + } + @Test public void testAuthenticate_success() { // 准备参数 @@ -78,7 +97,7 @@ public class AdminAuthServiceImplTest extends BaseDbUnitTest { String password = randomString(); // 调用, 并断言异常 - AssertUtils.assertServiceException(() -> authService.authenticate(username, password), + assertServiceException(() -> authService.authenticate(username, password), AUTH_LOGIN_BAD_CREDENTIALS); verify(loginLogService).createLoginLog( argThat(o -> o.getLogType().equals(LoginLogTypeEnum.LOGIN_USERNAME.getType()) @@ -98,7 +117,7 @@ public class AdminAuthServiceImplTest extends BaseDbUnitTest { when(userService.getUserByUsername(eq(username))).thenReturn(user); // 调用, 并断言异常 - AssertUtils.assertServiceException(() -> authService.authenticate(username, password), + assertServiceException(() -> authService.authenticate(username, password), AUTH_LOGIN_BAD_CREDENTIALS); verify(loginLogService).createLoginLog( argThat(o -> o.getLogType().equals(LoginLogTypeEnum.LOGIN_USERNAME.getType()) @@ -120,7 +139,7 @@ public class AdminAuthServiceImplTest extends BaseDbUnitTest { when(userService.isPasswordMatch(eq(password), eq(user.getPassword()))).thenReturn(true); // 调用, 并断言异常 - AssertUtils.assertServiceException(() -> authService.authenticate(username, password), + assertServiceException(() -> authService.authenticate(username, password), AUTH_LOGIN_USER_DISABLED); verify(loginLogService).createLoginLog( argThat(o -> o.getLogType().equals(LoginLogTypeEnum.LOGIN_USERNAME.getType()) @@ -129,82 +148,194 @@ public class AdminAuthServiceImplTest extends BaseDbUnitTest { ); } -// @Test -// public void testCaptcha_success() { -// // 准备参数 -// AuthLoginReqVO reqVO = randomPojo(AuthLoginReqVO.class); -// -// // mock 验证码正确 -// when(captchaService.getCaptchaCode(reqVO.getUuid())).thenReturn(reqVO.getCode()); -// -// // 调用 -// authService.verifyCaptcha(reqVO); -// // 断言 -// verify(captchaService).deleteCaptchaCode(reqVO.getUuid()); -// } -// -// @Test -// public void testCaptcha_notFound() { -// // 准备参数 -// AuthLoginReqVO reqVO = randomPojo(AuthLoginReqVO.class); -// -// // 调用, 并断言异常 -// assertServiceException(() -> authService.verifyCaptcha(reqVO), AUTH_LOGIN_CAPTCHA_NOT_FOUND); -// // 校验调用参数 -// verify(loginLogService, times(1)).createLoginLog( -// argThat(o -> o.getLogType().equals(LoginLogTypeEnum.LOGIN_USERNAME.getType()) -// && o.getResult().equals(LoginResultEnum.CAPTCHA_NOT_FOUND.getResult())) -// ); -// } + @Test + public void testLogin_success() { + // 准备参数 + AuthLoginReqVO reqVO = randomPojo(AuthLoginReqVO.class, o -> + o.setUsername("test_username").setPassword("test_password") + .setSocialType(randomEle(SocialTypeEnum.values()).getType())); -// @Test -// public void testCaptcha_codeError() { -// // 准备参数 -// AuthLoginReqVO reqVO = randomPojo(AuthLoginReqVO.class); -// -// // mock 验证码不正确 -// String code = randomString(); -// when(captchaService.getCaptchaCode(reqVO.getUuid())).thenReturn(code); -// -// // 调用, 并断言异常 -// assertServiceException(() -> authService.verifyCaptcha(reqVO), AUTH_LOGIN_CAPTCHA_CODE_ERROR); -// // 校验调用参数 -// verify(loginLogService).createLoginLog( -// argThat(o -> o.getLogType().equals(LoginLogTypeEnum.LOGIN_USERNAME.getType()) -// && o.getResult().equals(LoginResultEnum.CAPTCHA_CODE_ERROR.getResult())) -// ); -// } + // mock 验证码正确 + ReflectUtil.setFieldValue(authService, "captchaEnable", false); + // mock user 数据 + AdminUserDO user = randomPojo(AdminUserDO.class, o -> o.setId(1L).setUsername("test_username") + .setPassword("test_password").setStatus(CommonStatusEnum.ENABLE.getStatus())); + when(userService.getUserByUsername(eq("test_username"))).thenReturn(user); + // mock password 匹配 + when(userService.isPasswordMatch(eq("test_password"), eq(user.getPassword()))).thenReturn(true); + // mock 缓存登录用户到 Redis + OAuth2AccessTokenDO accessTokenDO = randomPojo(OAuth2AccessTokenDO.class, o -> o.setUserId(1L) + .setUserType(UserTypeEnum.ADMIN.getValue())); + when(oauth2TokenService.createAccessToken(eq(1L), eq(UserTypeEnum.ADMIN.getValue()), eq("default"), isNull())) + .thenReturn(accessTokenDO); -// @Test -// public void testLogin_success() { -// // 准备参数 -// AuthLoginReqVO reqVO = randomPojo(AuthLoginReqVO.class, o -> -// o.setUsername("test_username").setPassword("test_password")); -// -// // mock 验证码正确 -// when(captchaService.getCaptchaCode(reqVO.getUuid())).thenReturn(reqVO.getCode()); -// // mock user 数据 -// AdminUserDO user = randomPojo(AdminUserDO.class, o -> o.setId(1L).setUsername("test_username") -// .setPassword("test_password").setStatus(CommonStatusEnum.ENABLE.getStatus())); -// when(userService.getUserByUsername(eq("test_username"))).thenReturn(user); -// // mock password 匹配 -// when(userService.isPasswordMatch(eq("test_password"), eq(user.getPassword()))).thenReturn(true); -// // mock 缓存登录用户到 Redis -// OAuth2AccessTokenDO accessTokenDO = randomPojo(OAuth2AccessTokenDO.class, o -> o.setUserId(1L) -// .setUserType(UserTypeEnum.ADMIN.getValue())); -// when(oauth2TokenService.createAccessToken(eq(1L), eq(UserTypeEnum.ADMIN.getValue()), eq("default"), isNull())) -// .thenReturn(accessTokenDO); -// -// // 调用, 并断言异常 -// AuthLoginRespVO loginRespVO = authService.login(reqVO); -// assertPojoEquals(accessTokenDO, loginRespVO); -// // 校验调用参数 -// verify(loginLogService).createLoginLog( -// argThat(o -> o.getLogType().equals(LoginLogTypeEnum.LOGIN_USERNAME.getType()) -// && o.getResult().equals(LoginResultEnum.SUCCESS.getResult()) -// && o.getUserId().equals(user.getId())) -// ); -// } + // 调用,并校验 + AuthLoginRespVO loginRespVO = authService.login(reqVO); + assertPojoEquals(accessTokenDO, loginRespVO); + // 校验调用参数 + verify(loginLogService).createLoginLog( + argThat(o -> o.getLogType().equals(LoginLogTypeEnum.LOGIN_USERNAME.getType()) + && o.getResult().equals(LoginResultEnum.SUCCESS.getResult()) + && o.getUserId().equals(user.getId())) + ); + verify(socialUserService).bindSocialUser(eq(new SocialUserBindReqDTO( + user.getId(), UserTypeEnum.ADMIN.getValue(), + reqVO.getSocialType(), reqVO.getSocialCode(), reqVO.getSocialState()))); + } + + @Test + public void testSendSmsCode() { + // 准备参数 + String mobile = randomString(); + Integer scene = randomEle(SmsSceneEnum.values()).getScene(); + AuthSmsSendReqVO reqVO = new AuthSmsSendReqVO(mobile, scene); + // mock 方法(用户信息) + AdminUserDO user = randomPojo(AdminUserDO.class); + when(userService.getUserByMobile(eq(mobile))).thenReturn(user); + + // 调用 + authService.sendSmsCode(reqVO); + // 断言 + verify(smsCodeApi).sendSmsCode(argThat(sendReqDTO -> { + assertEquals(mobile, sendReqDTO.getMobile()); + assertEquals(scene, sendReqDTO.getScene()); + return true; + })); + } + + @Test + public void testSmsLogin_success() { + // 准备参数 + String mobile = randomString(); + String scene = randomString(); + AuthSmsLoginReqVO reqVO = new AuthSmsLoginReqVO(mobile, scene); + // mock 方法(用户信息) + AdminUserDO user = randomPojo(AdminUserDO.class, o -> o.setId(1L)); + when(userService.getUserByMobile(eq(mobile))).thenReturn(user); + // mock 缓存登录用户到 Redis + OAuth2AccessTokenDO accessTokenDO = randomPojo(OAuth2AccessTokenDO.class, o -> o.setUserId(1L) + .setUserType(UserTypeEnum.ADMIN.getValue())); + when(oauth2TokenService.createAccessToken(eq(1L), eq(UserTypeEnum.ADMIN.getValue()), eq("default"), isNull())) + .thenReturn(accessTokenDO); + + // 调用,并断言 + AuthLoginRespVO loginRespVO = authService.smsLogin(reqVO); + assertPojoEquals(accessTokenDO, loginRespVO); + // 断言调用 + verify(loginLogService).createLoginLog( + argThat(o -> o.getLogType().equals(LoginLogTypeEnum.LOGIN_MOBILE.getType()) + && o.getResult().equals(LoginResultEnum.SUCCESS.getResult()) + && o.getUserId().equals(user.getId())) + ); + } + + @Test + public void testSocialLogin_success() { + // 准备参数 + AuthSocialLoginReqVO reqVO = randomPojo(AuthSocialLoginReqVO.class); + // mock 方法(绑定的用户编号) + Long userId = 1L; + when(socialUserService.getBindUserId(eq(UserTypeEnum.ADMIN.getValue()), eq(reqVO.getType()), + eq(reqVO.getCode()), eq(reqVO.getState()))).thenReturn(userId); + // mock(用户) + AdminUserDO user = randomPojo(AdminUserDO.class, o -> o.setId(userId)); + when(userService.getUser(eq(userId))).thenReturn(user); + // mock 缓存登录用户到 Redis + OAuth2AccessTokenDO accessTokenDO = randomPojo(OAuth2AccessTokenDO.class, o -> o.setUserId(1L) + .setUserType(UserTypeEnum.ADMIN.getValue())); + when(oauth2TokenService.createAccessToken(eq(1L), eq(UserTypeEnum.ADMIN.getValue()), eq("default"), isNull())) + .thenReturn(accessTokenDO); + + // 调用,并断言 + AuthLoginRespVO loginRespVO = authService.socialLogin(reqVO); + assertPojoEquals(accessTokenDO, loginRespVO); + // 断言调用 + verify(loginLogService).createLoginLog( + argThat(o -> o.getLogType().equals(LoginLogTypeEnum.LOGIN_SOCIAL.getType()) + && o.getResult().equals(LoginResultEnum.SUCCESS.getResult()) + && o.getUserId().equals(user.getId())) + ); + } + + @Test + public void testValidateCaptcha_successWithEnable() { + // 准备参数 + AuthLoginReqVO reqVO = randomPojo(AuthLoginReqVO.class); + + // mock 验证码打开 + ReflectUtil.setFieldValue(authService, "captchaEnable", true); + // mock 验证通过 + when(captchaService.verification(argThat(captchaVO -> { + assertEquals(reqVO.getCaptchaVerification(), captchaVO.getCaptchaVerification()); + return true; + }))).thenReturn(ResponseModel.success()); + + // 调用,无需断言 + authService.validateCaptcha(reqVO); + } + + @Test + public void testValidateCaptcha_successWithDisable() { + // 准备参数 + AuthLoginReqVO reqVO = randomPojo(AuthLoginReqVO.class); + + // mock 验证码关闭 + ReflectUtil.setFieldValue(authService, "captchaEnable", false); + + // 调用,无需断言 + authService.validateCaptcha(reqVO); + } + + @Test + public void testValidateCaptcha_constraintViolationException() { + // 准备参数 + AuthLoginReqVO reqVO = randomPojo(AuthLoginReqVO.class).setCaptchaVerification(null); + + // mock 验证码打开 + ReflectUtil.setFieldValue(authService, "captchaEnable", true); + + // 调用,并断言异常 + assertThrows(ConstraintViolationException.class, () -> authService.validateCaptcha(reqVO), + "验证码不能为空"); + } + + + @Test + public void testCaptcha_fail() { + // 准备参数 + AuthLoginReqVO reqVO = randomPojo(AuthLoginReqVO.class); + + // mock 验证码打开 + ReflectUtil.setFieldValue(authService, "captchaEnable", true); + // mock 验证通过 + when(captchaService.verification(argThat(captchaVO -> { + assertEquals(reqVO.getCaptchaVerification(), captchaVO.getCaptchaVerification()); + return true; + }))).thenReturn(ResponseModel.errorMsg("就是不对")); + + // 调用, 并断言异常 + assertServiceException(() -> authService.validateCaptcha(reqVO), AUTH_LOGIN_CAPTCHA_CODE_ERROR, "就是不对"); + // 校验调用参数 + verify(loginLogService).createLoginLog( + argThat(o -> o.getLogType().equals(LoginLogTypeEnum.LOGIN_USERNAME.getType()) + && o.getResult().equals(LoginResultEnum.CAPTCHA_CODE_ERROR.getResult())) + ); + } + + @Test + public void testRefreshToken() { + // 准备参数 + String refreshToken = randomString(); + // mock 方法 + OAuth2AccessTokenDO accessTokenDO = randomPojo(OAuth2AccessTokenDO.class); + when(oauth2TokenService.refreshAccessToken(eq(refreshToken), eq("default"))) + .thenReturn(accessTokenDO); + + // 调用 + AuthLoginRespVO loginRespVO = authService.refreshToken(refreshToken); + // 断言 + assertPojoEquals(accessTokenDO, loginRespVO); + } @Test public void testLogout_success() { @@ -221,6 +352,8 @@ public class AdminAuthServiceImplTest extends BaseDbUnitTest { verify(loginLogService).createLoginLog(argThat(o -> o.getLogType().equals(LoginLogTypeEnum.LOGOUT_SELF.getType()) && o.getResult().equals(LoginResultEnum.SUCCESS.getResult())) ); + // 调用,并校验 + } @Test diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/dept/DeptServiceTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/dept/DeptServiceImplTest.java similarity index 69% rename from yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/dept/DeptServiceTest.java rename to yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/dept/DeptServiceImplTest.java index 6b4ff1028..3771fc33e 100644 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/dept/DeptServiceTest.java +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/dept/DeptServiceImplTest.java @@ -19,6 +19,7 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import javax.annotation.Resource; +import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.function.Consumer; @@ -28,8 +29,8 @@ import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEq import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*; +import static java.util.Collections.singletonList; import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; /** @@ -38,7 +39,7 @@ import static org.mockito.Mockito.verify; * @author niudehua */ @Import(DeptServiceImpl.class) -public class DeptServiceTest extends BaseDbUnitTest { +public class DeptServiceImplTest extends BaseDbUnitTest { @Resource private DeptServiceImpl deptService; @@ -76,7 +77,7 @@ public class DeptServiceTest extends BaseDbUnitTest { } @Test - void testListDepts() { + public void testListDepts() { // mock 数据 DeptDO dept = randomPojo(DeptDO.class, o -> { // 等会查询到 o.setName("开发部"); @@ -91,21 +92,22 @@ public class DeptServiceTest extends BaseDbUnitTest { DeptListReqVO reqVO = new DeptListReqVO(); reqVO.setName("开"); reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus()); + // 调用 - List sysDeptDOS = deptService.getSimpleDepts(reqVO); + List sysDeptDOS = deptService.getDeptList(reqVO); // 断言 assertEquals(1, sysDeptDOS.size()); assertPojoEquals(dept, sysDeptDOS.get(0)); } @Test - void testCreateDept_success() { + public void testCreateDept_success() { // 准备参数 - DeptCreateReqVO reqVO = randomPojo(DeptCreateReqVO.class, - o -> { - o.setParentId(DeptIdEnum.ROOT.getId()); - o.setStatus(randomCommonStatus()); - }); + DeptCreateReqVO reqVO = randomPojo(DeptCreateReqVO.class, o -> { + o.setParentId(DeptIdEnum.ROOT.getId()); + o.setStatus(randomCommonStatus()); + }); + // 调用 Long deptId = deptService.createDept(reqVO); // 断言 @@ -114,11 +116,11 @@ public class DeptServiceTest extends BaseDbUnitTest { DeptDO deptDO = deptMapper.selectById(deptId); assertPojoEquals(reqVO, deptDO); // 校验调用 - verify(deptProducer, times(1)).sendDeptRefreshMessage(); + verify(deptProducer).sendDeptRefreshMessage(); } @Test - void testUpdateDept_success() { + public void testUpdateDept_success() { // mock 数据 DeptDO dbDeptDO = randomPojo(DeptDO.class, o -> o.setStatus(randomCommonStatus())); deptMapper.insert(dbDeptDO);// @Sql: 先插入出一条存在的数据 @@ -129,28 +131,34 @@ public class DeptServiceTest extends BaseDbUnitTest { o.setId(dbDeptDO.getId()); o.setStatus(randomCommonStatus()); }); + // 调用 deptService.updateDept(reqVO); // 校验是否更新正确 DeptDO deptDO = deptMapper.selectById(reqVO.getId()); // 获取最新的 assertPojoEquals(reqVO, deptDO); + // 校验调用 + verify(deptProducer).sendDeptRefreshMessage(); } @Test - void testDeleteDept_success() { + public void testDeleteDept_success() { // mock 数据 DeptDO dbDeptDO = randomPojo(DeptDO.class, o -> o.setStatus(randomCommonStatus())); deptMapper.insert(dbDeptDO);// @Sql: 先插入出一条存在的数据 // 准备参数 Long id = dbDeptDO.getId(); + // 调用 deptService.deleteDept(id); // 校验数据不存在了 assertNull(deptMapper.selectById(id)); + // 校验调用 + verify(deptProducer).sendDeptRefreshMessage(); } @Test - void testCheckDept_nameDuplicateForUpdate() { + public void testValidateDept_nameDuplicateForUpdate() { // mock 数据 DeptDO deptDO = randomDeptDO(); // 设置根节点部门 @@ -162,37 +170,40 @@ public class DeptServiceTest extends BaseDbUnitTest { nameDeptDO.setParentId(DeptIdEnum.ROOT.getId()); deptMapper.insert(nameDeptDO); // 准备参数 - DeptUpdateReqVO reqVO = randomPojo(DeptUpdateReqVO.class, - o -> { - // 设置根节点部门 - o.setParentId(DeptIdEnum.ROOT.getId()); - // 设置更新的 ID - o.setId(deptDO.getId()); - // 模拟 name 重复 - o.setName(nameDeptDO.getName()); - }); + DeptUpdateReqVO reqVO = randomPojo(DeptUpdateReqVO.class, o -> { + // 设置根节点部门 + o.setParentId(DeptIdEnum.ROOT.getId()); + // 设置更新的 ID + o.setId(deptDO.getId()); + // 模拟 name 重复 + o.setName(nameDeptDO.getName()); + }); + // 调用, 并断言异常 assertServiceException(() -> deptService.updateDept(reqVO), DEPT_NAME_DUPLICATE); } @Test - void testCheckDept_parentNotExitsForCreate() { + public void testValidateDept_parentNotExitsForCreate() { + // 准备参数 DeptCreateReqVO reqVO = randomPojo(DeptCreateReqVO.class, o -> o.setStatus(randomCommonStatus())); + // 调用,并断言异常 assertServiceException(() -> deptService.createDept(reqVO), DEPT_PARENT_NOT_EXITS); } @Test - void testCheckDept_notFoundForDelete() { + public void testValidateDept_notFoundForDelete() { // 准备参数 Long id = randomLongId(); + // 调用, 并断言异常 assertServiceException(() -> deptService.deleteDept(id), DEPT_NOT_FOUND); } @Test - void testCheckDept_exitsChildrenForDelete() { + public void testValidateDept_exitsChildrenForDelete() { // mock 数据 DeptDO parentDept = randomPojo(DeptDO.class, o -> o.setStatus(randomCommonStatus())); deptMapper.insert(parentDept);// @Sql: 先插入出一条存在的数据 @@ -208,39 +219,39 @@ public class DeptServiceTest extends BaseDbUnitTest { } @Test - void testCheckDept_parentErrorForUpdate() { + public void testValidateDept_parentErrorForUpdate() { // mock 数据 DeptDO dbDeptDO = randomPojo(DeptDO.class, o -> o.setStatus(randomCommonStatus())); deptMapper.insert(dbDeptDO); // 准备参数 - DeptUpdateReqVO reqVO = randomPojo(DeptUpdateReqVO.class, - o -> { - // 设置自己为父部门 - o.setParentId(dbDeptDO.getId()); - // 设置更新的 ID - o.setId(dbDeptDO.getId()); - }); + DeptUpdateReqVO reqVO = randomPojo(DeptUpdateReqVO.class, o -> { + // 设置自己为父部门 + o.setParentId(dbDeptDO.getId()); + // 设置更新的 ID + o.setId(dbDeptDO.getId()); + }); + // 调用, 并断言异常 assertServiceException(() -> deptService.updateDept(reqVO), DEPT_PARENT_ERROR); } @Test - void testCheckDept_notEnableForCreate() { + public void testValidateDept_notEnableForCreate() { // mock 数据 DeptDO deptDO = randomPojo(DeptDO.class, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus())); deptMapper.insert(deptDO); // 准备参数 - DeptCreateReqVO reqVO = randomPojo(DeptCreateReqVO.class, - o -> { - // 设置未启用的部门为副部门 - o.setParentId(deptDO.getId()); - }); + DeptCreateReqVO reqVO = randomPojo(DeptCreateReqVO.class, o -> { + // 设置未启用的部门为父部门 + o.setParentId(deptDO.getId()); + }); + // 调用, 并断言异常 assertServiceException(() -> deptService.createDept(reqVO), DEPT_NOT_ENABLE); } @Test - void testCheckDept_parentIsChildForUpdate() { + public void testCheckDept_parentIsChildForUpdate() { // mock 数据 DeptDO parentDept = randomPojo(DeptDO.class, o -> o.setStatus(CommonStatusEnum.ENABLE.getStatus())); deptMapper.insert(parentDept); @@ -251,18 +262,84 @@ public class DeptServiceTest extends BaseDbUnitTest { deptMapper.insert(childDept); // 初始化本地缓存 deptService.initLocalCache(); + // 准备参数 - DeptUpdateReqVO reqVO = randomPojo(DeptUpdateReqVO.class, - o -> { - // 设置自己的子部门为父部门 - o.setParentId(childDept.getId()); - // 设置更新的 ID - o.setId(parentDept.getId()); - }); + DeptUpdateReqVO reqVO = randomPojo(DeptUpdateReqVO.class, o -> { + // 设置自己的子部门为父部门 + o.setParentId(childDept.getId()); + // 设置更新的 ID + o.setId(parentDept.getId()); + }); + // 调用, 并断言异常 assertServiceException(() -> deptService.updateDept(reqVO), DEPT_PARENT_IS_CHILD); } + @Test + public void testGetDeptList() { + // mock 数据 + DeptDO deptDO01 = randomDeptDO(); + deptMapper.insert(deptDO01); + DeptDO deptDO02 = randomDeptDO(); + deptMapper.insert(deptDO02); + // 准备参数 + List ids = Arrays.asList(deptDO01.getId(), deptDO02.getId()); + + // 调用 + List deptDOList = deptService.getDeptList(ids); + // 断言 + assertEquals(2, deptDOList.size()); + assertEquals(deptDO01, deptDOList.get(0)); + assertEquals(deptDO02, deptDOList.get(1)); + } + + @Test + public void testGetDept() { + // mock 数据 + DeptDO deptDO = randomDeptDO(); + deptMapper.insert(deptDO); + // 准备参数 + Long id = deptDO.getId(); + + // 调用 + DeptDO dbDept = deptService.getDept(id); + // 断言 + assertEquals(deptDO, dbDept); + } + + @Test + public void testValidateDeptList_success() { + // mock 数据 + DeptDO deptDO = randomDeptDO().setStatus(CommonStatusEnum.ENABLE.getStatus()); + deptMapper.insert(deptDO); + // 准备参数 + List ids = singletonList(deptDO.getId()); + + // 调用,无需断言 + deptService.validateDeptList(ids); + } + + @Test + public void testValidateDeptList_notFound() { + // 准备参数 + List ids = singletonList(randomLongId()); + + // 调用, 并断言异常 + assertServiceException(() -> deptService.validateDeptList(ids), DEPT_NOT_FOUND); + } + + @Test + public void testValidateDeptList_notEnable() { + // mock 数据 + DeptDO deptDO = randomDeptDO().setStatus(CommonStatusEnum.DISABLE.getStatus()); + deptMapper.insert(deptDO); + // 准备参数 + List ids = singletonList(deptDO.getId()); + + // 调用, 并断言异常 + assertServiceException(() -> deptService.validateDeptList(ids), DEPT_NOT_ENABLE, deptDO.getName()); + } + @SafeVarargs private static DeptDO randomDeptDO(Consumer... consumers) { Consumer consumer = (o) -> { diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/dept/PostServiceTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/dept/PostServiceImplTest.java similarity index 61% rename from yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/dept/PostServiceTest.java rename to yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/dept/PostServiceImplTest.java index 30e546f66..87c44b346 100644 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/dept/PostServiceTest.java +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/dept/PostServiceImplTest.java @@ -1,41 +1,136 @@ package cn.iocoder.yudao.module.system.service.dept; -import cn.iocoder.yudao.module.system.dal.dataobject.dept.PostDO; import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum; import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.common.util.collection.ArrayUtils; -import cn.iocoder.yudao.framework.common.util.object.ObjectUtils; +import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import cn.iocoder.yudao.module.system.controller.admin.dept.vo.post.PostCreateReqVO; import cn.iocoder.yudao.module.system.controller.admin.dept.vo.post.PostExportReqVO; import cn.iocoder.yudao.module.system.controller.admin.dept.vo.post.PostPageReqVO; import cn.iocoder.yudao.module.system.controller.admin.dept.vo.post.PostUpdateReqVO; +import cn.iocoder.yudao.module.system.dal.dataobject.dept.PostDO; import cn.iocoder.yudao.module.system.dal.mysql.dept.PostMapper; -import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import org.junit.jupiter.api.Test; import org.springframework.context.annotation.Import; import javax.annotation.Resource; +import java.util.Arrays; import java.util.List; import java.util.function.Consumer; import static cn.hutool.core.util.RandomUtil.randomEle; +import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; -import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomLongId; -import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo; +import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*; +import static java.util.Collections.singletonList; import static org.junit.jupiter.api.Assertions.*; +/** + * {@link PostServiceImpl} 的单元测试类 + * + * @author niudehua + */ @Import(PostServiceImpl.class) -public class PostServiceTest extends BaseDbUnitTest { +public class PostServiceImplTest extends BaseDbUnitTest { @Resource private PostServiceImpl postService; + @Resource private PostMapper postMapper; @Test - void testPagePosts() { + public void testCreatePost_success() { + // 准备参数 + PostCreateReqVO reqVO = randomPojo(PostCreateReqVO.class, + o -> o.setStatus(randomEle(CommonStatusEnum.values()).getStatus())); + // 调用 + Long postId = postService.createPost(reqVO); + + // 断言 + assertNotNull(postId); + // 校验记录的属性是否正确 + PostDO post = postMapper.selectById(postId); + assertPojoEquals(reqVO, post); + } + + @Test + public void testUpdatePost_success() { + // mock 数据 + PostDO postDO = randomPostDO(); + postMapper.insert(postDO);// @Sql: 先插入出一条存在的数据 + // 准备参数 + PostUpdateReqVO reqVO = randomPojo(PostUpdateReqVO.class, o -> { + // 设置更新的 ID + o.setId(postDO.getId()); + o.setStatus(randomEle(CommonStatusEnum.values()).getStatus()); + }); + + // 调用 + postService.updatePost(reqVO); + // 校验是否更新正确 + PostDO post = postMapper.selectById(reqVO.getId()); + assertPojoEquals(reqVO, post); + } + + @Test + public void testDeletePost_success() { + // mock 数据 + PostDO postDO = randomPostDO(); + postMapper.insert(postDO); + // 准备参数 + Long id = postDO.getId(); + + // 调用 + postService.deletePost(id); + assertNull(postMapper.selectById(id)); + } + + @Test + public void testValidatePost_notFoundForDelete() { + // 准备参数 + Long id = randomLongId(); + + // 调用, 并断言异常 + assertServiceException(() -> postService.deletePost(id), POST_NOT_FOUND); + } + + @Test + public void testValidatePost_nameDuplicateForCreate() { + // mock 数据 + PostDO postDO = randomPostDO(); + postMapper.insert(postDO);// @Sql: 先插入出一条存在的数据 + // 准备参数 + PostCreateReqVO reqVO = randomPojo(PostCreateReqVO.class, + // 模拟 name 重复 + o -> o.setName(postDO.getName())); + assertServiceException(() -> postService.createPost(reqVO), POST_NAME_DUPLICATE); + } + + @Test + public void testValidatePost_codeDuplicateForUpdate() { + // mock 数据 + PostDO postDO = randomPostDO(); + postMapper.insert(postDO); + // mock 数据:稍后模拟重复它的 code + PostDO codePostDO = randomPostDO(); + postMapper.insert(codePostDO); + // 准备参数 + PostUpdateReqVO reqVO = randomPojo(PostUpdateReqVO.class, o -> { + // 设置更新的 ID + o.setId(postDO.getId()); + // 模拟 code 重复 + o.setCode(codePostDO.getCode()); + }); + + // 调用, 并断言异常 + assertServiceException(() -> postService.updatePost(reqVO), POST_CODE_DUPLICATE); + } + + @Test + public void testGetPostPage() { // mock 数据 PostDO postDO = randomPojo(PostDO.class, o -> { o.setName("码仔"); @@ -43,10 +138,9 @@ public class PostServiceTest extends BaseDbUnitTest { }); postMapper.insert(postDO); // 测试 name 不匹配 - postMapper.insert(ObjectUtils.cloneIgnoreId(postDO, o -> o.setName("程序员"))); + postMapper.insert(cloneIgnoreId(postDO, o -> o.setName("程序员"))); // 测试 status 不匹配 - postMapper.insert(ObjectUtils.cloneIgnoreId(postDO, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus()))); - + postMapper.insert(cloneIgnoreId(postDO, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus()))); // 准备参数 PostPageReqVO reqVO = new PostPageReqVO(); reqVO.setName("码"); @@ -54,7 +148,6 @@ public class PostServiceTest extends BaseDbUnitTest { // 调用 PageResult pageResult = postService.getPostPage(reqVO); - // 断言 assertEquals(1, pageResult.getTotal()); assertEquals(1, pageResult.getList().size()); @@ -62,7 +155,7 @@ public class PostServiceTest extends BaseDbUnitTest { } @Test - void testListPosts() { + public void testGetPostList_export() { // mock 数据 PostDO postDO = randomPojo(PostDO.class, o -> { o.setName("码仔"); @@ -70,23 +163,41 @@ public class PostServiceTest extends BaseDbUnitTest { }); postMapper.insert(postDO); // 测试 name 不匹配 - postMapper.insert(ObjectUtils.cloneIgnoreId(postDO, o -> o.setName("程序员"))); + postMapper.insert(cloneIgnoreId(postDO, o -> o.setName("程序员"))); // 测试 status 不匹配 - postMapper.insert(ObjectUtils.cloneIgnoreId(postDO, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus()))); + postMapper.insert(cloneIgnoreId(postDO, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus()))); // 准备参数 PostExportReqVO reqVO = new PostExportReqVO(); reqVO.setName("码"); reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus()); // 调用 - List list = postService.getPosts(reqVO); + List list = postService.getPostList(reqVO); // 断言 assertEquals(1, list.size()); assertPojoEquals(postDO, list.get(0)); } @Test - void testGetPost() { + public void testGetPostList() { + // mock 数据 + PostDO postDO01 = randomPojo(PostDO.class, o -> o.setStatus(CommonStatusEnum.ENABLE.getStatus())); + postMapper.insert(postDO01); + // 测试 status 不匹配 + PostDO postDO02 = randomPojo(PostDO.class, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus())); + postMapper.insert(postDO02); + // 准备参数 + List ids = Arrays.asList(postDO01.getId(), postDO02.getId()); + + // 调用 + List list = postService.getPostList(ids, singletonList(CommonStatusEnum.ENABLE.getStatus())); + // 断言 + assertEquals(1, list.size()); + assertPojoEquals(postDO01, list.get(0)); + } + + @Test + public void testGetPost() { // mock 数据 PostDO dbPostDO = randomPostDO(); postMapper.insert(dbPostDO); @@ -100,94 +211,43 @@ public class PostServiceTest extends BaseDbUnitTest { } @Test - void testCreatePost_success() { - // 准备参数 - PostCreateReqVO reqVO = randomPojo(PostCreateReqVO.class, - o -> o.setStatus(randomEle(CommonStatusEnum.values()).getStatus())); - // 调用 - Long postId = postService.createPost(reqVO); - // 断言 - assertNotNull(postId); - // 校验记录的属性是否正确 - PostDO post = postMapper.selectById(postId); - assertPojoEquals(reqVO, post); - } - - @Test - void testUpdatePost_success() { + public void testValidatePostList_success() { // mock 数据 - PostDO postDO = randomPostDO(); - postMapper.insert(postDO);// @Sql: 先插入出一条存在的数据 - // 准备参数 - PostUpdateReqVO reqVO = randomPojo(PostUpdateReqVO.class, - o -> { - // 设置更新的 ID - o.setId(postDO.getId()); - o.setStatus(randomEle(CommonStatusEnum.values()).getStatus()); - }); - // 调用 - postService.updatePost(reqVO); - // 校验是否更新正确 - PostDO post = postMapper.selectById(reqVO.getId());// 获取最新的 - assertPojoEquals(reqVO, post); - } - - @Test - void testDeletePost_success() { - // mock 数据 - PostDO postDO = randomPostDO(); + PostDO postDO = randomPostDO().setStatus(CommonStatusEnum.ENABLE.getStatus()); postMapper.insert(postDO); // 准备参数 - Long id = postDO.getId(); - // 调用 - postService.deletePost(id); - assertNull(postMapper.selectById(id)); + List ids = singletonList(postDO.getId()); + + // 调用,无需断言 + postService.validatePostList(ids); } @Test - void testCheckPost_notFoundForDelete() { + public void testValidatePostList_notFound() { // 准备参数 - Long id = randomLongId(); + List ids = singletonList(randomLongId()); + // 调用, 并断言异常 - assertServiceException(() -> postService.deletePost(id), POST_NOT_FOUND); + assertServiceException(() -> postService.validatePostList(ids), POST_NOT_FOUND); } @Test - void testCheckPost_nameDuplicateForCreate() { + public void testValidatePostList_notEnable() { // mock 数据 - PostDO postDO = randomPostDO(); - postMapper.insert(postDO);// @Sql: 先插入出一条存在的数据 - // 准备参数 - PostCreateReqVO reqVO = randomPojo(PostCreateReqVO.class, - // 模拟 name 重复 - o -> o.setName(postDO.getName())); - assertServiceException(() -> postService.createPost(reqVO), POST_NAME_DUPLICATE); - } - - @Test - void testCheckPost_codeDuplicateForUpdate() { - // mock 数据 - PostDO postDO = randomPostDO(); + PostDO postDO = randomPostDO().setStatus(CommonStatusEnum.DISABLE.getStatus()); postMapper.insert(postDO); - // mock 数据 稍后模拟重复它的 code - PostDO codePostDO = randomPostDO(); - postMapper.insert(codePostDO); // 准备参数 - PostUpdateReqVO reqVO = randomPojo(PostUpdateReqVO.class, - o -> { - // 设置更新的 ID - o.setId(postDO.getId()); - // 模拟 code 重复 - o.setCode(codePostDO.getCode()); - }); + List ids = singletonList(postDO.getId()); + // 调用, 并断言异常 - assertServiceException(() -> postService.updatePost(reqVO), POST_CODE_DUPLICATE); + assertServiceException(() -> postService.validatePostList(ids), POST_NOT_ENABLE, + postDO.getName()); } @SafeVarargs private static PostDO randomPostDO(Consumer... consumers) { Consumer consumer = (o) -> { - o.setStatus(randomEle(CommonStatusEnum.values()).getStatus()); // 保证 status 的范围 + o.setStatus(randomCommonStatus()); // 保证 status 的范围 }; return randomPojo(PostDO.class, ArrayUtils.append(consumer, consumers)); } diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/dict/DictDataServiceTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/dict/DictDataServiceImplTest.java similarity index 55% rename from yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/dict/DictDataServiceTest.java rename to yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/dict/DictDataServiceImplTest.java index 02fba6c21..1e4dc9f90 100644 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/dict/DictDataServiceTest.java +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/dict/DictDataServiceImplTest.java @@ -3,7 +3,6 @@ package cn.iocoder.yudao.module.system.service.dict; import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum; import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.common.util.collection.ArrayUtils; -import cn.iocoder.yudao.framework.common.util.object.ObjectUtils; import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import cn.iocoder.yudao.module.system.controller.admin.dict.vo.data.DictDataCreateReqVO; import cn.iocoder.yudao.module.system.controller.admin.dict.vo.data.DictDataExportReqVO; @@ -20,16 +19,18 @@ import javax.annotation.Resource; import java.util.List; import java.util.function.Consumer; +import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*; +import static java.util.Collections.singletonList; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; @Import(DictDataServiceImpl.class) -public class DictDataServiceTest extends BaseDbUnitTest { +public class DictDataServiceImplTest extends BaseDbUnitTest { @Resource private DictDataServiceImpl dictDataService; @@ -39,6 +40,23 @@ public class DictDataServiceTest extends BaseDbUnitTest { @MockBean private DictTypeService dictTypeService; + @Test + public void testGetDictDataList() { + // mock 数据 + DictDataDO dictDataDO01 = randomDictDataDO().setDictType("yunai").setSort(2); + dictDataMapper.insert(dictDataDO01); + DictDataDO dictDataDO02 = randomDictDataDO().setDictType("yunai").setSort(1); + dictDataMapper.insert(dictDataDO02); + // 准备参数 + + // 调用 + List dictDataDOList = dictDataService.getDictDataList(); + // 断言 + assertEquals(2, dictDataDOList.size()); + assertPojoEquals(dictDataDO02, dictDataDOList.get(0)); + assertPojoEquals(dictDataDO01, dictDataDOList.get(1)); + } + @Test public void testGetDictDataPage() { // mock 数据 @@ -49,11 +67,11 @@ public class DictDataServiceTest extends BaseDbUnitTest { }); dictDataMapper.insert(dbDictData); // 测试 label 不匹配 - dictDataMapper.insert(ObjectUtils.cloneIgnoreId(dbDictData, o -> o.setLabel("艿"))); + dictDataMapper.insert(cloneIgnoreId(dbDictData, o -> o.setLabel("艿"))); // 测试 dictType 不匹配 - dictDataMapper.insert(ObjectUtils.cloneIgnoreId(dbDictData, o -> o.setDictType("nai"))); + dictDataMapper.insert(cloneIgnoreId(dbDictData, o -> o.setDictType("nai"))); // 测试 status 不匹配 - dictDataMapper.insert(ObjectUtils.cloneIgnoreId(dbDictData, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus()))); + dictDataMapper.insert(cloneIgnoreId(dbDictData, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus()))); // 准备参数 DictDataPageReqVO reqVO = new DictDataPageReqVO(); reqVO.setLabel("芋"); @@ -69,7 +87,7 @@ public class DictDataServiceTest extends BaseDbUnitTest { } @Test - public void testGetDictDataList() { + public void testGetDictDataList_export() { // mock 数据 DictDataDO dbDictData = randomPojo(DictDataDO.class, o -> { // 等会查询到 o.setLabel("芋艿"); @@ -78,11 +96,11 @@ public class DictDataServiceTest extends BaseDbUnitTest { }); dictDataMapper.insert(dbDictData); // 测试 label 不匹配 - dictDataMapper.insert(ObjectUtils.cloneIgnoreId(dbDictData, o -> o.setLabel("艿"))); + dictDataMapper.insert(cloneIgnoreId(dbDictData, o -> o.setLabel("艿"))); // 测试 dictType 不匹配 - dictDataMapper.insert(ObjectUtils.cloneIgnoreId(dbDictData, o -> o.setDictType("nai"))); + dictDataMapper.insert(cloneIgnoreId(dbDictData, o -> o.setDictType("nai"))); // 测试 status 不匹配 - dictDataMapper.insert(ObjectUtils.cloneIgnoreId(dbDictData, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus()))); + dictDataMapper.insert(cloneIgnoreId(dbDictData, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus()))); // 准备参数 DictDataExportReqVO reqVO = new DictDataExportReqVO(); reqVO.setLabel("芋"); @@ -90,12 +108,26 @@ public class DictDataServiceTest extends BaseDbUnitTest { reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus()); // 调用 - List list = dictDataService.getDictDatas(reqVO); + List list = dictDataService.getDictDataList(reqVO); // 断言 assertEquals(1, list.size()); assertPojoEquals(dbDictData, list.get(0)); } + @Test + public void testGetDictData() { + // mock 数据 + DictDataDO dbDictData = randomDictDataDO(); + dictDataMapper.insert(dbDictData); + // 准备参数 + Long id = dbDictData.getId(); + + // 调用 + DictDataDO dictData = dictDataService.getDictData(id); + // 断言 + assertPojoEquals(dbDictData, dictData); + } + @Test public void testCreateDictData_success() { // 准备参数 @@ -148,54 +180,54 @@ public class DictDataServiceTest extends BaseDbUnitTest { } @Test - public void testCheckDictDataExists_success() { + public void testValidateDictDataExists_success() { // mock 数据 DictDataDO dbDictData = randomDictDataDO(); dictDataMapper.insert(dbDictData);// @Sql: 先插入出一条存在的数据 // 调用成功 - dictDataService.checkDictDataExists(dbDictData.getId()); + dictDataService.validateDictDataExists(dbDictData.getId()); } @Test - public void testCheckDictDataExists_notExists() { - assertServiceException(() -> dictDataService.checkDictDataExists(randomLongId()), DICT_DATA_NOT_EXISTS); + public void testValidateDictDataExists_notExists() { + assertServiceException(() -> dictDataService.validateDictDataExists(randomLongId()), DICT_DATA_NOT_EXISTS); } @Test - public void testCheckDictTypeValid_success() { + public void testValidateDictTypeExists_success() { // mock 方法,数据类型被禁用 String type = randomString(); when(dictTypeService.getDictType(eq(type))).thenReturn(randomDictTypeDO(type)); // 调用, 成功 - dictDataService.checkDictTypeValid(type); + dictDataService.validateDictTypeExists(type); } @Test - public void testCheckDictTypeValid_notExists() { - assertServiceException(() -> dictDataService.checkDictTypeValid(randomString()), DICT_TYPE_NOT_EXISTS); + public void testValidateDictTypeExists_notExists() { + assertServiceException(() -> dictDataService.validateDictTypeExists(randomString()), DICT_TYPE_NOT_EXISTS); } @Test - public void testCheckDictTypeValid_notEnable() { + public void testValidateDictTypeExists_notEnable() { // mock 方法,数据类型被禁用 String dictType = randomString(); when(dictTypeService.getDictType(eq(dictType))).thenReturn( randomPojo(DictTypeDO.class, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus()))); // 调用, 并断言异常 - assertServiceException(() -> dictDataService.checkDictTypeValid(dictType), DICT_TYPE_NOT_ENABLE); + assertServiceException(() -> dictDataService.validateDictTypeExists(dictType), DICT_TYPE_NOT_ENABLE); } @Test - public void testCheckDictDataValueUnique_success() { + public void testValidateDictDataValueUnique_success() { // 调用,成功 - dictDataService.checkDictDataValueUnique(randomLongId(), randomString(), randomString()); + dictDataService.validateDictDataValueUnique(randomLongId(), randomString(), randomString()); } @Test - public void testCheckDictDataValueUnique_valueDuplicateForCreate() { + public void testValidateDictDataValueUnique_valueDuplicateForCreate() { // 准备参数 String dictType = randomString(); String value = randomString(); @@ -206,12 +238,12 @@ public class DictDataServiceTest extends BaseDbUnitTest { })); // 调用,校验异常 - assertServiceException(() -> dictDataService.checkDictDataValueUnique(null, dictType, value), + assertServiceException(() -> dictDataService.validateDictDataValueUnique(null, dictType, value), DICT_DATA_VALUE_DUPLICATE); } @Test - public void testCheckDictDataValueUnique_valueDuplicateForUpdate() { + public void testValidateDictDataValueUnique_valueDuplicateForUpdate() { // 准备参数 Long id = randomLongId(); String dictType = randomString(); @@ -223,10 +255,96 @@ public class DictDataServiceTest extends BaseDbUnitTest { })); // 调用,校验异常 - assertServiceException(() -> dictDataService.checkDictDataValueUnique(id, dictType, value), + assertServiceException(() -> dictDataService.validateDictDataValueUnique(id, dictType, value), DICT_DATA_VALUE_DUPLICATE); } + @Test + public void testCountByDictType() { + // mock 数据 + dictDataMapper.insert(randomDictDataDO(o -> o.setDictType("yunai"))); + dictDataMapper.insert(randomDictDataDO(o -> o.setDictType("tudou"))); + dictDataMapper.insert(randomDictDataDO(o -> o.setDictType("yunai"))); + // 准备参数 + String dictType = "yunai"; + + // 调用 + long count = dictDataService.countByDictType(dictType); + // 校验 + assertEquals(2L, count); + } + + @Test + public void testValidateDictDataList_success() { + // mock 数据 + DictDataDO dictDataDO = randomDictDataDO().setStatus(CommonStatusEnum.ENABLE.getStatus()); + dictDataMapper.insert(dictDataDO); + // 准备参数 + String dictType = dictDataDO.getDictType(); + List values = singletonList(dictDataDO.getValue()); + + // 调用,无需断言 + dictDataService.validateDictDataList(dictType, values); + } + + @Test + public void testValidateDictDataList_notFound() { + // 准备参数 + String dictType = randomString(); + List values = singletonList(randomString()); + + // 调用, 并断言异常 + assertServiceException(() -> dictDataService.validateDictDataList(dictType, values), DICT_DATA_NOT_EXISTS); + } + + @Test + public void testValidateDictDataList_notEnable() { + // mock 数据 + DictDataDO dictDataDO = randomDictDataDO().setStatus(CommonStatusEnum.DISABLE.getStatus()); + dictDataMapper.insert(dictDataDO); + // 准备参数 + String dictType = dictDataDO.getDictType(); + List values = singletonList(dictDataDO.getValue()); + + // 调用, 并断言异常 + assertServiceException(() -> dictDataService.validateDictDataList(dictType, values), + DICT_DATA_NOT_ENABLE, dictDataDO.getLabel()); + } + + @Test + public void testGetDictData_dictType() { + // mock 数据 + DictDataDO dictDataDO = randomDictDataDO().setDictType("yunai").setValue("1"); + dictDataMapper.insert(dictDataDO); + DictDataDO dictDataDO02 = randomDictDataDO().setDictType("yunai").setValue("2"); + dictDataMapper.insert(dictDataDO02); + // 准备参数 + String dictType = "yunai"; + String value = "1"; + + // 调用 + DictDataDO dbDictData = dictDataService.getDictData(dictType, value); + // 断言 + assertEquals(dictDataDO, dbDictData); + } + + @Test + public void testParseDictData() { + // mock 数据 + DictDataDO dictDataDO = randomDictDataDO().setDictType("yunai").setLabel("1"); + dictDataMapper.insert(dictDataDO); + DictDataDO dictDataDO02 = randomDictDataDO().setDictType("yunai").setLabel("2"); + dictDataMapper.insert(dictDataDO02); + // 准备参数 + String dictType = "yunai"; + String label = "1"; + + // 调用 + DictDataDO dbDictData = dictDataService.parseDictData(dictType, label); + // 断言 + assertEquals(dictDataDO, dbDictData); + } + // ========== 随机对象 ========== @SafeVarargs diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/dict/DictTypeServiceTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/dict/DictTypeServiceImplTest.java similarity index 70% rename from yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/dict/DictTypeServiceTest.java rename to yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/dict/DictTypeServiceImplTest.java index 5c39b32e6..fc9387019 100644 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/dict/DictTypeServiceTest.java +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/dict/DictTypeServiceImplTest.java @@ -2,36 +2,36 @@ package cn.iocoder.yudao.module.system.service.dict; import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum; import cn.iocoder.yudao.framework.common.pojo.PageResult; +import cn.iocoder.yudao.framework.common.util.collection.ArrayUtils; +import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import cn.iocoder.yudao.module.system.controller.admin.dict.vo.type.DictTypeCreateReqVO; -import cn.iocoder.yudao.module.system.controller.admin.dict.vo.type.DictTypeUpdateReqVO; import cn.iocoder.yudao.module.system.controller.admin.dict.vo.type.DictTypeExportReqVO; import cn.iocoder.yudao.module.system.controller.admin.dict.vo.type.DictTypePageReqVO; +import cn.iocoder.yudao.module.system.controller.admin.dict.vo.type.DictTypeUpdateReqVO; import cn.iocoder.yudao.module.system.dal.dataobject.dict.DictTypeDO; import cn.iocoder.yudao.module.system.dal.mysql.dict.DictTypeMapper; -import cn.iocoder.yudao.framework.common.util.collection.ArrayUtils; -import cn.iocoder.yudao.framework.common.util.object.ObjectUtils; -import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import org.junit.jupiter.api.Test; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import javax.annotation.Resource; -import java.time.LocalDateTime; import java.util.List; import java.util.function.Consumer; import static cn.hutool.core.util.RandomUtil.randomEle; -import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*; +import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildBetweenTime; +import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildTime; +import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; -import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildTime; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; +import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; @Import(DictTypeServiceImpl.class) -public class DictTypeServiceTest extends BaseDbUnitTest { +public class DictTypeServiceImplTest extends BaseDbUnitTest { @Resource private DictTypeServiceImpl dictTypeService; @@ -52,19 +52,19 @@ public class DictTypeServiceTest extends BaseDbUnitTest { }); dictTypeMapper.insert(dbDictType); // 测试 name 不匹配 - dictTypeMapper.insert(ObjectUtils.cloneIgnoreId(dbDictType, o -> o.setName("tudou"))); + dictTypeMapper.insert(cloneIgnoreId(dbDictType, o -> o.setName("tudou"))); // 测试 type 不匹配 - dictTypeMapper.insert(ObjectUtils.cloneIgnoreId(dbDictType, o -> o.setType("土豆"))); + dictTypeMapper.insert(cloneIgnoreId(dbDictType, o -> o.setType("土豆"))); // 测试 status 不匹配 - dictTypeMapper.insert(ObjectUtils.cloneIgnoreId(dbDictType, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus()))); + dictTypeMapper.insert(cloneIgnoreId(dbDictType, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus()))); // 测试 createTime 不匹配 - dictTypeMapper.insert(ObjectUtils.cloneIgnoreId(dbDictType, o -> o.setCreateTime(buildTime(2021, 1, 1)))); + dictTypeMapper.insert(cloneIgnoreId(dbDictType, o -> o.setCreateTime(buildTime(2021, 1, 1)))); // 准备参数 DictTypePageReqVO reqVO = new DictTypePageReqVO(); reqVO.setName("nai"); reqVO.setType("艿"); reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus()); - reqVO.setCreateTime((new LocalDateTime[]{buildTime(2021, 1, 10),buildTime(2021, 1, 20)})); + reqVO.setCreateTime(buildBetweenTime(2021, 1, 10, 2021, 1, 20)); // 调用 PageResult pageResult = dictTypeService.getDictTypePage(reqVO); @@ -75,7 +75,7 @@ public class DictTypeServiceTest extends BaseDbUnitTest { } @Test - public void testGetDictTypeList() { + public void testGetDictTypeList_export() { // mock 数据 DictTypeDO dbDictType = randomPojo(DictTypeDO.class, o -> { // 等会查询到 o.setName("yunai"); @@ -85,19 +85,19 @@ public class DictTypeServiceTest extends BaseDbUnitTest { }); dictTypeMapper.insert(dbDictType); // 测试 name 不匹配 - dictTypeMapper.insert(ObjectUtils.cloneIgnoreId(dbDictType, o -> o.setName("tudou"))); + dictTypeMapper.insert(cloneIgnoreId(dbDictType, o -> o.setName("tudou"))); // 测试 type 不匹配 - dictTypeMapper.insert(ObjectUtils.cloneIgnoreId(dbDictType, o -> o.setType("土豆"))); + dictTypeMapper.insert(cloneIgnoreId(dbDictType, o -> o.setType("土豆"))); // 测试 status 不匹配 - dictTypeMapper.insert(ObjectUtils.cloneIgnoreId(dbDictType, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus()))); + dictTypeMapper.insert(cloneIgnoreId(dbDictType, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus()))); // 测试 createTime 不匹配 - dictTypeMapper.insert(ObjectUtils.cloneIgnoreId(dbDictType, o -> o.setCreateTime(buildTime(2021, 1, 1)))); + dictTypeMapper.insert(cloneIgnoreId(dbDictType, o -> o.setCreateTime(buildTime(2021, 1, 1)))); // 准备参数 DictTypeExportReqVO reqVO = new DictTypeExportReqVO(); reqVO.setName("nai"); reqVO.setType("艿"); reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus()); - reqVO.setCreateTime((new LocalDateTime[]{buildTime(2021, 1, 10),buildTime(2021, 1, 20)})); + reqVO.setCreateTime(buildBetweenTime(2021, 1, 10, 2021, 1, 20)); // 调用 List list = dictTypeService.getDictTypeList(reqVO); @@ -107,7 +107,22 @@ public class DictTypeServiceTest extends BaseDbUnitTest { } @Test - public void testGetDictType() { + public void testGetDictType_id() { + // mock 数据 + DictTypeDO dbDictType = randomDictTypeDO(); + dictTypeMapper.insert(dbDictType); + // 准备参数 + Long id = dbDictType.getId(); + + // 调用 + DictTypeDO dictType = dictTypeService.getDictType(id); + // 断言 + assertNotNull(dictType); + assertPojoEquals(dbDictType, dictType); + } + + @Test + public void testGetDictType_type() { // mock 数据 DictTypeDO dbDictType = randomDictTypeDO(); dictTypeMapper.insert(dbDictType); @@ -183,40 +198,57 @@ public class DictTypeServiceTest extends BaseDbUnitTest { } @Test - public void testCheckDictDataExists_success() { + public void testGetDictTypeList() { + // 准备参数 + DictTypeDO dictTypeDO01 = randomDictTypeDO(); + dictTypeMapper.insert(dictTypeDO01); + DictTypeDO dictTypeDO02 = randomDictTypeDO(); + dictTypeMapper.insert(dictTypeDO02); + // mock 方法 + + // 调用 + List dictTypeDOList = dictTypeService.getDictTypeList(); + // 断言 + assertEquals(2, dictTypeDOList.size()); + assertPojoEquals(dictTypeDO01, dictTypeDOList.get(0)); + assertPojoEquals(dictTypeDO02, dictTypeDOList.get(1)); + } + + @Test + public void testValidateDictDataExists_success() { // mock 数据 DictTypeDO dbDictType = randomDictTypeDO(); dictTypeMapper.insert(dbDictType);// @Sql: 先插入出一条存在的数据 // 调用成功 - dictTypeService.checkDictTypeExists(dbDictType.getId()); + dictTypeService.validateDictTypeExists(dbDictType.getId()); } @Test - public void testCheckDictDataExists_notExists() { - assertServiceException(() -> dictTypeService.checkDictTypeExists(randomLongId()), DICT_TYPE_NOT_EXISTS); + public void testValidateDictDataExists_notExists() { + assertServiceException(() -> dictTypeService.validateDictTypeExists(randomLongId()), DICT_TYPE_NOT_EXISTS); } @Test - public void testCheckDictTypeUnique_success() { + public void testValidateDictTypeUnique_success() { // 调用,成功 - dictTypeService.checkDictTypeUnique(randomLongId(), randomString()); + dictTypeService.validateDictTypeUnique(randomLongId(), randomString()); } @Test - public void testCheckDictTypeUnique_valueDuplicateForCreate() { + public void testValidateDictTypeUnique_valueDuplicateForCreate() { // 准备参数 String type = randomString(); // mock 数据 dictTypeMapper.insert(randomDictTypeDO(o -> o.setType(type))); // 调用,校验异常 - assertServiceException(() -> dictTypeService.checkDictTypeUnique(null, type), + assertServiceException(() -> dictTypeService.validateDictTypeUnique(null, type), DICT_TYPE_TYPE_DUPLICATE); } @Test - public void testCheckDictTypeUnique_valueDuplicateForUpdate() { + public void testValidateDictTypeUnique_valueDuplicateForUpdate() { // 准备参数 Long id = randomLongId(); String type = randomString(); @@ -224,30 +256,30 @@ public class DictTypeServiceTest extends BaseDbUnitTest { dictTypeMapper.insert(randomDictTypeDO(o -> o.setType(type))); // 调用,校验异常 - assertServiceException(() -> dictTypeService.checkDictTypeUnique(id, type), + assertServiceException(() -> dictTypeService.validateDictTypeUnique(id, type), DICT_TYPE_TYPE_DUPLICATE); } @Test - public void testCheckDictTypNameUnique_success() { + public void testValidateDictTypNameUnique_success() { // 调用,成功 - dictTypeService.checkDictTypeNameUnique(randomLongId(), randomString()); + dictTypeService.validateDictTypeNameUnique(randomLongId(), randomString()); } @Test - public void testCheckDictTypeNameUnique_nameDuplicateForCreate() { + public void testValidateDictTypeNameUnique_nameDuplicateForCreate() { // 准备参数 String name = randomString(); // mock 数据 dictTypeMapper.insert(randomDictTypeDO(o -> o.setName(name))); // 调用,校验异常 - assertServiceException(() -> dictTypeService.checkDictTypeNameUnique(null, name), + assertServiceException(() -> dictTypeService.validateDictTypeNameUnique(null, name), DICT_TYPE_NAME_DUPLICATE); } @Test - public void testCheckDictTypeNameUnique_nameDuplicateForUpdate() { + public void testValidateDictTypeNameUnique_nameDuplicateForUpdate() { // 准备参数 Long id = randomLongId(); String name = randomString(); @@ -255,7 +287,7 @@ public class DictTypeServiceTest extends BaseDbUnitTest { dictTypeMapper.insert(randomDictTypeDO(o -> o.setName(name))); // 调用,校验异常 - assertServiceException(() -> dictTypeService.checkDictTypeNameUnique(id, name), + assertServiceException(() -> dictTypeService.validateDictTypeNameUnique(id, name), DICT_TYPE_NAME_DUPLICATE); } diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/errorcode/ErrorCodeServiceTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/errorcode/ErrorCodeServiceTest.java index 163a2cda3..cd5e01307 100644 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/errorcode/ErrorCodeServiceTest.java +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/errorcode/ErrorCodeServiceTest.java @@ -2,9 +2,9 @@ package cn.iocoder.yudao.module.system.service.errorcode; import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.common.util.collection.ArrayUtils; -import cn.iocoder.yudao.framework.common.util.object.ObjectUtils; import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import cn.iocoder.yudao.module.system.api.errorcode.dto.ErrorCodeAutoGenerateReqDTO; +import cn.iocoder.yudao.module.system.api.errorcode.dto.ErrorCodeRespDTO; import cn.iocoder.yudao.module.system.controller.admin.errorcode.vo.ErrorCodeCreateReqVO; import cn.iocoder.yudao.module.system.controller.admin.errorcode.vo.ErrorCodeExportReqVO; import cn.iocoder.yudao.module.system.controller.admin.errorcode.vo.ErrorCodePageReqVO; @@ -22,7 +22,9 @@ import java.util.List; import java.util.function.Consumer; import static cn.hutool.core.util.RandomUtil.randomEle; +import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildBetweenTime; import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildTime; +import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; @@ -57,7 +59,7 @@ public class ErrorCodeServiceTest extends BaseDbUnitTest { @Test public void testUpdateErrorCode_success() { // mock 数据 - ErrorCodeDO dbErrorCode = randomInfErrorCodeDO(); + ErrorCodeDO dbErrorCode = randomErrorCodeDO(); errorCodeMapper.insert(dbErrorCode);// @Sql: 先插入出一条存在的数据 // 准备参数 ErrorCodeUpdateReqVO reqVO = randomPojo(ErrorCodeUpdateReqVO.class, o -> { @@ -75,7 +77,7 @@ public class ErrorCodeServiceTest extends BaseDbUnitTest { @Test public void testDeleteErrorCode_success() { // mock 数据 - ErrorCodeDO dbErrorCode = randomInfErrorCodeDO(); + ErrorCodeDO dbErrorCode = randomErrorCodeDO(); errorCodeMapper.insert(dbErrorCode);// @Sql: 先插入出一条存在的数据 // 准备参数 Long id = dbErrorCode.getId(); @@ -96,7 +98,7 @@ public class ErrorCodeServiceTest extends BaseDbUnitTest { reqVO.setApplicationName("tu"); reqVO.setCode(1); reqVO.setMessage("ma"); - reqVO.setCreateTime((new LocalDateTime[]{buildTime(2020, 11, 1),buildTime(2020, 11, 30)})); + reqVO.setCreateTime(buildBetweenTime(2020, 11, 1, 2020, 11, 30)); // 调用 PageResult pageResult = errorCodeService.getErrorCodePage(reqVO); @@ -110,7 +112,7 @@ public class ErrorCodeServiceTest extends BaseDbUnitTest { * 初始化 getErrorCodePage 方法的测试数据 */ private ErrorCodeDO initGetErrorCodePage() { - ErrorCodeDO dbErrorCode = randomInfErrorCodeDO(o -> { // 等会查询到 + ErrorCodeDO dbErrorCode = randomErrorCodeDO(o -> { // 等会查询到 o.setType(ErrorCodeTypeEnum.AUTO_GENERATION.getType()); o.setApplicationName("tudou"); o.setCode(1); @@ -119,20 +121,20 @@ public class ErrorCodeServiceTest extends BaseDbUnitTest { }); errorCodeMapper.insert(dbErrorCode); // 测试 type 不匹配 - errorCodeMapper.insert(ObjectUtils.cloneIgnoreId(dbErrorCode, o -> o.setType(ErrorCodeTypeEnum.MANUAL_OPERATION.getType()))); + errorCodeMapper.insert(cloneIgnoreId(dbErrorCode, o -> o.setType(ErrorCodeTypeEnum.MANUAL_OPERATION.getType()))); // 测试 applicationName 不匹配 - errorCodeMapper.insert(ObjectUtils.cloneIgnoreId(dbErrorCode, o -> o.setApplicationName("yuan"))); + errorCodeMapper.insert(cloneIgnoreId(dbErrorCode, o -> o.setApplicationName("yuan"))); // 测试 code 不匹配 - errorCodeMapper.insert(ObjectUtils.cloneIgnoreId(dbErrorCode, o -> o.setCode(2))); + errorCodeMapper.insert(cloneIgnoreId(dbErrorCode, o -> o.setCode(2))); // 测试 message 不匹配 - errorCodeMapper.insert(ObjectUtils.cloneIgnoreId(dbErrorCode, o -> o.setMessage("nai"))); + errorCodeMapper.insert(cloneIgnoreId(dbErrorCode, o -> o.setMessage("nai"))); // 测试 createTime 不匹配 - errorCodeMapper.insert(ObjectUtils.cloneIgnoreId(dbErrorCode, o -> o.setCreateTime(buildTime(2020, 12, 12)))); + errorCodeMapper.insert(cloneIgnoreId(dbErrorCode, o -> o.setCreateTime(buildTime(2020, 12, 12)))); return dbErrorCode; } @Test - public void testGetErrorCodeList() { + public void testGetErrorCodeList_export() { // mock 数据 ErrorCodeDO dbErrorCode = initGetErrorCodePage(); // 准备参数 @@ -141,7 +143,7 @@ public class ErrorCodeServiceTest extends BaseDbUnitTest { reqVO.setApplicationName("tu"); reqVO.setCode(1); reqVO.setMessage("ma"); - reqVO.setCreateTime((new LocalDateTime[]{buildTime(2020, 11, 1),buildTime(2020, 11, 30)})); + reqVO.setCreateTime(buildBetweenTime(2020, 11, 1, 2020, 11, 30)); // 调用 List list = errorCodeService.getErrorCodeList(reqVO); @@ -155,7 +157,7 @@ public class ErrorCodeServiceTest extends BaseDbUnitTest { // 准备参数 Integer code = randomInteger(); // mock 数据 - errorCodeMapper.insert(randomInfErrorCodeDO(o -> o.setCode(code))); + errorCodeMapper.insert(randomErrorCodeDO(o -> o.setCode(code))); // 调用,校验异常 assertServiceException(() -> errorCodeService.validateCodeDuplicate(code, null), @@ -168,7 +170,7 @@ public class ErrorCodeServiceTest extends BaseDbUnitTest { Long id = randomLongId(); Integer code = randomInteger(); // mock 数据 - errorCodeMapper.insert(randomInfErrorCodeDO(o -> o.setCode(code))); + errorCodeMapper.insert(randomErrorCodeDO(o -> o.setCode(code))); // 调用,校验异常 assertServiceException(() -> errorCodeService.validateCodeDuplicate(code, id), @@ -204,7 +206,7 @@ public class ErrorCodeServiceTest extends BaseDbUnitTest { @Test public void testAutoGenerateErrorCodes_021() { // mock 数据 - ErrorCodeDO dbErrorCode = randomInfErrorCodeDO(o -> o.setType(ErrorCodeTypeEnum.MANUAL_OPERATION.getType())); + ErrorCodeDO dbErrorCode = randomErrorCodeDO(o -> o.setType(ErrorCodeTypeEnum.MANUAL_OPERATION.getType())); errorCodeMapper.insert(dbErrorCode); // 准备参数 ErrorCodeAutoGenerateReqDTO generateReqDTO = randomPojo(ErrorCodeAutoGenerateReqDTO.class, @@ -224,7 +226,7 @@ public class ErrorCodeServiceTest extends BaseDbUnitTest { @Test public void testAutoGenerateErrorCodes_022() { // mock 数据 - ErrorCodeDO dbErrorCode = randomInfErrorCodeDO(o -> o.setType(ErrorCodeTypeEnum.AUTO_GENERATION.getType())); + ErrorCodeDO dbErrorCode = randomErrorCodeDO(o -> o.setType(ErrorCodeTypeEnum.AUTO_GENERATION.getType())); errorCodeMapper.insert(dbErrorCode); // 准备参数 ErrorCodeAutoGenerateReqDTO generateReqDTO = randomPojo(ErrorCodeAutoGenerateReqDTO.class, @@ -244,7 +246,7 @@ public class ErrorCodeServiceTest extends BaseDbUnitTest { @Test public void testAutoGenerateErrorCodes_023() { // mock 数据 - ErrorCodeDO dbErrorCode = randomInfErrorCodeDO(o -> o.setType(ErrorCodeTypeEnum.AUTO_GENERATION.getType())); + ErrorCodeDO dbErrorCode = randomErrorCodeDO(o -> o.setType(ErrorCodeTypeEnum.AUTO_GENERATION.getType())); errorCodeMapper.insert(dbErrorCode); // 准备参数 ErrorCodeAutoGenerateReqDTO generateReqDTO = randomPojo(ErrorCodeAutoGenerateReqDTO.class, @@ -265,7 +267,7 @@ public class ErrorCodeServiceTest extends BaseDbUnitTest { @Test public void testAutoGenerateErrorCodes_024() { // mock 数据 - ErrorCodeDO dbErrorCode = randomInfErrorCodeDO(o -> o.setType(ErrorCodeTypeEnum.AUTO_GENERATION.getType())); + ErrorCodeDO dbErrorCode = randomErrorCodeDO(o -> o.setType(ErrorCodeTypeEnum.AUTO_GENERATION.getType())); errorCodeMapper.insert(dbErrorCode); // 准备参数 ErrorCodeAutoGenerateReqDTO generateReqDTO = randomPojo(ErrorCodeAutoGenerateReqDTO.class, @@ -279,10 +281,44 @@ public class ErrorCodeServiceTest extends BaseDbUnitTest { assertPojoEquals(generateReqDTO, errorCode); } + @Test + public void testGetErrorCode() { + // 准备参数 + ErrorCodeDO errorCodeDO = randomErrorCodeDO(); + errorCodeMapper.insert(errorCodeDO); + // mock 方法 + Long id = errorCodeDO.getId(); + + // 调用 + ErrorCodeDO dbErrorCode = errorCodeService.getErrorCode(id); + // 断言 + assertPojoEquals(errorCodeDO, dbErrorCode); + } + + @Test + public void testGetErrorCodeList() { + // 准备参数 + ErrorCodeDO errorCodeDO01 = randomErrorCodeDO( + o -> o.setApplicationName("yunai_server").setUpdateTime(buildTime(2022, 1, 10))); + errorCodeMapper.insert(errorCodeDO01); + ErrorCodeDO errorCodeDO02 = randomErrorCodeDO( + o -> o.setApplicationName("yunai_server").setUpdateTime(buildTime(2022, 1, 12))); + errorCodeMapper.insert(errorCodeDO02); + // mock 方法 + String applicationName = "yunai_server"; + LocalDateTime minUpdateTime = buildTime(2022, 1, 11); + + // 调用 + List errorCodeList = errorCodeService.getErrorCodeList(applicationName, minUpdateTime); + // 断言 + assertEquals(1, errorCodeList.size()); + assertPojoEquals(errorCodeDO02, errorCodeList.get(0)); + } + // ========== 随机对象 ========== @SafeVarargs - private static ErrorCodeDO randomInfErrorCodeDO(Consumer... consumers) { + private static ErrorCodeDO randomErrorCodeDO(Consumer... consumers) { Consumer consumer = (o) -> { o.setType(randomEle(ErrorCodeTypeEnum.values()).getType()); // 保证 key 的范围 }; diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/logger/LoginLogServiceImplTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/logger/LoginLogServiceImplTest.java index 101abe7d3..66eebc0bd 100644 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/logger/LoginLogServiceImplTest.java +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/logger/LoginLogServiceImplTest.java @@ -1,29 +1,25 @@ package cn.iocoder.yudao.module.system.service.logger; -import cn.hutool.core.util.RandomUtil; -import cn.iocoder.yudao.framework.common.enums.UserTypeEnum; import cn.iocoder.yudao.framework.common.pojo.PageResult; -import cn.iocoder.yudao.framework.common.util.monitor.TracerUtils; -import cn.iocoder.yudao.framework.common.util.object.ObjectUtils; import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; -import cn.iocoder.yudao.framework.test.core.util.RandomUtils; import cn.iocoder.yudao.module.system.api.logger.dto.LoginLogCreateReqDTO; import cn.iocoder.yudao.module.system.controller.admin.logger.vo.loginlog.LoginLogExportReqVO; import cn.iocoder.yudao.module.system.controller.admin.logger.vo.loginlog.LoginLogPageReqVO; import cn.iocoder.yudao.module.system.dal.dataobject.logger.LoginLogDO; import cn.iocoder.yudao.module.system.dal.mysql.logger.LoginLogMapper; -import cn.iocoder.yudao.module.system.enums.logger.LoginLogTypeEnum; import org.junit.jupiter.api.Test; import org.springframework.context.annotation.Import; import javax.annotation.Resource; -import java.time.LocalDateTime; import java.util.List; -import static cn.hutool.core.util.RandomUtil.randomEle; +import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildBetweenTime; import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildTime; +import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; -import static cn.iocoder.yudao.module.system.enums.logger.LoginResultEnum.*; +import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo; +import static cn.iocoder.yudao.module.system.enums.logger.LoginResultEnum.CAPTCHA_CODE_ERROR; +import static cn.iocoder.yudao.module.system.enums.logger.LoginResultEnum.SUCCESS; import static org.junit.jupiter.api.Assertions.assertEquals; @Import(LoginLogServiceImpl.class) @@ -37,42 +33,31 @@ public class LoginLogServiceImplTest extends BaseDbUnitTest { @Test public void testGetLoginLogPage() { - // 构造测试数据 - // 登录成功的 - LoginLogDO loginLogDO = RandomUtils.randomPojo(LoginLogDO.class, logDO -> { - logDO.setLogType(RandomUtil.randomEle(cn.iocoder.yudao.module.system.enums.logger.LoginLogTypeEnum.values()).getType()); - logDO.setTraceId(TracerUtils.getTraceId()); - logDO.setUserType(RandomUtil.randomEle(UserTypeEnum.values()).getValue()); - - logDO.setUserIp("192.168.199.16"); - logDO.setUsername("wangkai"); - logDO.setCreateTime(buildTime(2021, 3, 6)); - logDO.setResult(SUCCESS.getResult()); + // mock 数据 + LoginLogDO loginLogDO = randomPojo(LoginLogDO.class, o -> { + o.setUserIp("192.168.199.16"); + o.setUsername("wang"); + o.setResult(SUCCESS.getResult()); + o.setCreateTime(buildTime(2021, 3, 6)); }); loginLogMapper.insert(loginLogDO); - - // 下面几个都是不匹配的数据 - // 登录失败的 - loginLogMapper.insert(ObjectUtils.cloneIgnoreId(loginLogDO, logDO -> logDO.setResult(CAPTCHA_CODE_ERROR.getResult()))); - // 不同ip段的 - loginLogMapper.insert(ObjectUtils.cloneIgnoreId(loginLogDO, logDO -> logDO.setUserIp("192.168.128.18"))); - // 不同username - loginLogMapper.insert(ObjectUtils.cloneIgnoreId(loginLogDO, logDO -> logDO.setUsername("yunai"))); - // 构造一个早期时间 2021-02-06 00:00:00 - loginLogMapper.insert(ObjectUtils.cloneIgnoreId(loginLogDO, logDO -> logDO.setCreateTime(buildTime(2021, 2, 6)))); - - + // 测试 status 不匹配 + loginLogMapper.insert(cloneIgnoreId(loginLogDO, o -> o.setResult(CAPTCHA_CODE_ERROR.getResult()))); + // 测试 ip 不匹配 + loginLogMapper.insert(cloneIgnoreId(loginLogDO, o -> o.setUserIp("192.168.128.18"))); + // 测试 username 不匹配 + loginLogMapper.insert(cloneIgnoreId(loginLogDO, o -> o.setUsername("yunai"))); + // 测试 createTime 不匹配 + loginLogMapper.insert(cloneIgnoreId(loginLogDO, o -> o.setCreateTime(buildTime(2021, 2, 6)))); // 构造调用参数 LoginLogPageReqVO reqVO = new LoginLogPageReqVO(); - reqVO.setUsername("wangkai"); + reqVO.setUsername("wang"); reqVO.setUserIp("192.168.199"); reqVO.setStatus(true); - reqVO.setCreateTime((new LocalDateTime[]{buildTime(2021, 3, 5), - buildTime(2021, 3, 7)})); + reqVO.setCreateTime(buildBetweenTime(2021, 3, 5, 2021, 3, 7)); - // 调用service方法 + // 调用 PageResult pageResult = loginLogService.getLoginLogPage(reqVO); - // 断言,只查到了一条符合条件的 assertEquals(1, pageResult.getTotal()); assertEquals(1, pageResult.getList().size()); @@ -81,62 +66,45 @@ public class LoginLogServiceImplTest extends BaseDbUnitTest { @Test public void testGetLoginLogList() { - // 构造测试数据 - - // 登录成功的 - LoginLogDO loginLogDO = RandomUtils.randomPojo(LoginLogDO.class, logDO -> { - logDO.setLogType(RandomUtil.randomEle(cn.iocoder.yudao.module.system.enums.logger.LoginLogTypeEnum.values()).getType()); - logDO.setTraceId(TracerUtils.getTraceId()); - logDO.setUserType(RandomUtil.randomEle(UserTypeEnum.values()).getValue()); - - logDO.setUserIp("192.168.111.16"); - logDO.setUsername("wangxiaokai"); - logDO.setCreateTime(buildTime(2021, 3, 6)); - logDO.setResult(SUCCESS.getResult()); + // mock 数据 + LoginLogDO loginLogDO = randomPojo(LoginLogDO.class, o -> { + o.setUserIp("192.168.199.16"); + o.setUsername("wang"); + o.setResult(SUCCESS.getResult()); + o.setCreateTime(buildTime(2021, 3, 6)); }); loginLogMapper.insert(loginLogDO); - - // 下面几个都是不匹配的数据 - // 登录失败的 - loginLogMapper.insert(ObjectUtils.cloneIgnoreId(loginLogDO, logDO -> logDO.setResult(CAPTCHA_CODE_ERROR.getResult()))); - // 不同ip段的 - loginLogMapper.insert(ObjectUtils.cloneIgnoreId(loginLogDO, logDO -> logDO.setUserIp("192.168.128.18"))); - // 不同username - loginLogMapper.insert(ObjectUtils.cloneIgnoreId(loginLogDO, logDO -> logDO.setUsername("yunai"))); - // 构造一个早期时间 2021-02-06 00:00:00 - loginLogMapper.insert(ObjectUtils.cloneIgnoreId(loginLogDO, logDO -> logDO.setCreateTime(buildTime(2021, 2, 6)))); - + // 测试 status 不匹配 + loginLogMapper.insert(cloneIgnoreId(loginLogDO, o -> o.setResult(CAPTCHA_CODE_ERROR.getResult()))); + // 测试 ip 不匹配 + loginLogMapper.insert(cloneIgnoreId(loginLogDO, o -> o.setUserIp("192.168.128.18"))); + // 测试 username 不匹配 + loginLogMapper.insert(cloneIgnoreId(loginLogDO, o -> o.setUsername("yunai"))); + // 测试 createTime 不匹配 + loginLogMapper.insert(cloneIgnoreId(loginLogDO, o -> o.setCreateTime(buildTime(2021, 2, 6)))); // 构造调用参数 LoginLogExportReqVO reqVO = new LoginLogExportReqVO(); - reqVO.setUsername("wangxiaokai"); - reqVO.setUserIp("192.168.111"); + reqVO.setUsername("wang"); + reqVO.setUserIp("192.168.199"); reqVO.setStatus(true); - reqVO.setCreateTime((new LocalDateTime[]{buildTime(2021, 3, 5), - buildTime(2021, 3, 7)})); + reqVO.setCreateTime(buildBetweenTime(2021, 3, 5, 2021, 3, 7)); // 调用service方法 - List loginLogList = loginLogService.getLoginLogList(reqVO); - + List list = loginLogService.getLoginLogList(reqVO); // 断言 - assertEquals(1, loginLogList.size()); - assertPojoEquals(loginLogDO, loginLogList.get(0)); + assertEquals(1, list.size()); + assertPojoEquals(loginLogDO, list.get(0)); } @Test public void testCreateLoginLog() { - LoginLogCreateReqDTO reqDTO = RandomUtils.randomPojo(LoginLogCreateReqDTO.class, vo -> { - // 指定随机的范围,避免超出范围入库失败 - vo.setUserType(randomEle(UserTypeEnum.values()).getValue()); - vo.setLogType(randomEle(LoginLogTypeEnum.values()).getType()); - vo.setResult(randomEle(values()).getResult()); - vo.setTraceId(TracerUtils.getTraceId()); - }); + LoginLogCreateReqDTO reqDTO = randomPojo(LoginLogCreateReqDTO.class); // 调用 loginLogService.createLoginLog(reqDTO); - // 断言,忽略基本字段 - LoginLogDO sysLoginLogDO = loginLogMapper.selectOne(null); - assertPojoEquals(reqDTO, sysLoginLogDO); + // 断言 + LoginLogDO loginLogDO = loginLogMapper.selectOne(null); + assertPojoEquals(reqDTO, loginLogDO); } } diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/logger/OperateLogServiceImplTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/logger/OperateLogServiceImplTest.java index 86be2a8bd..14b007e25 100644 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/logger/OperateLogServiceImplTest.java +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/logger/OperateLogServiceImplTest.java @@ -5,8 +5,6 @@ import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum; import cn.iocoder.yudao.framework.common.enums.UserTypeEnum; import cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants; import cn.iocoder.yudao.framework.common.pojo.PageResult; -import cn.iocoder.yudao.framework.common.util.monitor.TracerUtils; -import cn.iocoder.yudao.framework.common.util.object.ObjectUtils; import cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum; import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import cn.iocoder.yudao.framework.test.core.util.RandomUtils; @@ -16,20 +14,20 @@ import cn.iocoder.yudao.module.system.controller.admin.logger.vo.operatelog.Oper import cn.iocoder.yudao.module.system.dal.dataobject.logger.OperateLogDO; import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO; import cn.iocoder.yudao.module.system.dal.mysql.logger.OperateLogMapper; -import cn.iocoder.yudao.module.system.enums.common.SexEnum; import cn.iocoder.yudao.module.system.service.user.AdminUserService; import org.junit.jupiter.api.Test; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import javax.annotation.Resource; -import java.time.LocalDateTime; import java.util.Collections; import java.util.List; import static cn.hutool.core.util.RandomUtil.randomEle; import static cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants.BAD_REQUEST; +import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildBetweenTime; import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildTime; +import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomLongId; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -49,34 +47,28 @@ public class OperateLogServiceImplTest extends BaseDbUnitTest { @Test public void testCreateOperateLogAsync() { - String traceId = TracerUtils.getTraceId(); - OperateLogCreateReqDTO reqVO = RandomUtils.randomPojo(OperateLogCreateReqDTO.class, o -> { - o.setTraceId(traceId); - o.setUserId(randomLongId()); - o.setUserType(randomEle(UserTypeEnum.values()).getValue()); - o.setExts(MapUtil.builder("orderId", randomLongId()).build()); - }); + OperateLogCreateReqDTO reqVO = RandomUtils.randomPojo(OperateLogCreateReqDTO.class, + o -> o.setExts(MapUtil.builder("orderId", randomLongId()).build())); - // 执行service方法 + // 调研 operateLogServiceImpl.createOperateLog(reqVO); - // 断言插入是否正确 - OperateLogDO sysOperateLogDO = operateLogMapper.selectOne("trace_id", traceId); - assertPojoEquals(reqVO, sysOperateLogDO); + // 断言 + OperateLogDO operateLogDO = operateLogMapper.selectOne(null); + assertPojoEquals(reqVO, operateLogDO); } @Test public void testGetOperateLogPage() { - // 构造测试数据 - // 先构造用户 + // mock(用户信息) AdminUserDO user = RandomUtils.randomPojo(AdminUserDO.class, o -> { - o.setNickname("wangkai"); - o.setSex(SexEnum.MALE.getSex()); + o.setNickname("wang"); o.setStatus(CommonStatusEnum.ENABLE.getStatus()); }); - when(userService.getUsersByNickname("wangkai")).thenReturn(Collections.singletonList(user)); + when(userService.getUserListByNickname("wang")).thenReturn(Collections.singletonList(user)); Long userId = user.getId(); + // 构造操作日志 - OperateLogDO sysOperateLogDO = RandomUtils.randomPojo(OperateLogDO.class, o -> { + OperateLogDO operateLogDO = RandomUtils.randomPojo(OperateLogDO.class, o -> { o.setUserId(userId); o.setUserType(randomEle(UserTypeEnum.values()).getValue()); o.setModule("order"); @@ -85,50 +77,46 @@ public class OperateLogServiceImplTest extends BaseDbUnitTest { o.setResultCode(GlobalErrorCodeConstants.SUCCESS.getCode()); o.setExts(MapUtil.builder("orderId", randomLongId()).build()); }); - operateLogMapper.insert(sysOperateLogDO); - - // 下面几个是不匹配的数据 - // 随机 userId - operateLogMapper.insert(ObjectUtils.cloneIgnoreId(sysOperateLogDO, logDO -> logDO.setUserId(userId + 1))); - // module 不同 - operateLogMapper.insert(ObjectUtils.cloneIgnoreId(sysOperateLogDO, logDO -> logDO.setModule("user"))); - // type 不同 - operateLogMapper.insert(ObjectUtils.cloneIgnoreId(sysOperateLogDO, logDO -> logDO.setType(OperateTypeEnum.IMPORT.getType()))); - // createTime 不同 - operateLogMapper.insert(ObjectUtils.cloneIgnoreId(sysOperateLogDO, logDO -> logDO.setStartTime(buildTime(2021, 2, 6)))); - // resultCode 不同 - operateLogMapper.insert(ObjectUtils.cloneIgnoreId(sysOperateLogDO, logDO -> logDO.setResultCode(BAD_REQUEST.getCode()))); + operateLogMapper.insert(operateLogDO); + // 测试 userId 不匹配 + operateLogMapper.insert(cloneIgnoreId(operateLogDO, o -> o.setUserId(userId + 1))); + // 测试 module 不匹配 + operateLogMapper.insert(cloneIgnoreId(operateLogDO, o -> o.setModule("user"))); + // 测试 type 不匹配 + operateLogMapper.insert(cloneIgnoreId(operateLogDO, o -> o.setType(OperateTypeEnum.IMPORT.getType()))); + // 测试 createTime 不匹配 + operateLogMapper.insert(cloneIgnoreId(operateLogDO, o -> o.setStartTime(buildTime(2021, 2, 6)))); + // 测试 resultCode 不匹配 + operateLogMapper.insert(cloneIgnoreId(operateLogDO, o -> o.setResultCode(BAD_REQUEST.getCode()))); // 构造调用参数 OperateLogPageReqVO reqVO = new OperateLogPageReqVO(); - reqVO.setUserNickname("wangkai"); + reqVO.setUserNickname("wang"); reqVO.setModule("order"); reqVO.setType(OperateTypeEnum.CREATE.getType()); - reqVO.setStartTime((new LocalDateTime[]{buildTime(2021, 3, 5), - buildTime(2021, 3, 7)})); + reqVO.setStartTime(buildBetweenTime(2021, 3, 5, 2021, 3, 7)); reqVO.setSuccess(true); - // 调用service方法 + // 调用 PageResult pageResult = operateLogServiceImpl.getOperateLogPage(reqVO); // 断言,只查到了一条符合条件的 assertEquals(1, pageResult.getTotal()); assertEquals(1, pageResult.getList().size()); - assertPojoEquals(sysOperateLogDO, pageResult.getList().get(0)); + assertPojoEquals(operateLogDO, pageResult.getList().get(0)); } @Test public void testGetOperateLogs() { - // 构造测试数据 - // 先构造用户 + // mock(用户信息) AdminUserDO user = RandomUtils.randomPojo(AdminUserDO.class, o -> { - o.setNickname("wangkai"); - o.setSex(SexEnum.MALE.getSex()); + o.setNickname("wang"); o.setStatus(CommonStatusEnum.ENABLE.getStatus()); }); - when(userService.getUsersByNickname("wangkai")).thenReturn(Collections.singletonList(user)); + when(userService.getUserListByNickname("wang")).thenReturn(Collections.singletonList(user)); Long userId = user.getId(); + // 构造操作日志 - OperateLogDO sysOperateLogDO = RandomUtils.randomPojo(OperateLogDO.class, o -> { + OperateLogDO operateLogDO = RandomUtils.randomPojo(OperateLogDO.class, o -> { o.setUserId(userId); o.setUserType(randomEle(UserTypeEnum.values()).getValue()); o.setModule("order"); @@ -137,33 +125,31 @@ public class OperateLogServiceImplTest extends BaseDbUnitTest { o.setResultCode(GlobalErrorCodeConstants.SUCCESS.getCode()); o.setExts(MapUtil.builder("orderId", randomLongId()).build()); }); - operateLogMapper.insert(sysOperateLogDO); - - // 下面几个是不匹配的数据 - // 随机 userId - operateLogMapper.insert(ObjectUtils.cloneIgnoreId(sysOperateLogDO, logDO -> logDO.setUserId(userId + 1))); - // module 不同 - operateLogMapper.insert(ObjectUtils.cloneIgnoreId(sysOperateLogDO, logDO -> logDO.setModule("user"))); - // type 不同 - operateLogMapper.insert(ObjectUtils.cloneIgnoreId(sysOperateLogDO, logDO -> logDO.setType(OperateTypeEnum.IMPORT.getType()))); - // createTime 不同 - operateLogMapper.insert(ObjectUtils.cloneIgnoreId(sysOperateLogDO, logDO -> logDO.setStartTime(buildTime(2021, 2, 6)))); - // resultCode 不同 - operateLogMapper.insert(ObjectUtils.cloneIgnoreId(sysOperateLogDO, logDO -> logDO.setResultCode(BAD_REQUEST.getCode()))); + operateLogMapper.insert(operateLogDO); + // 测试 userId 不匹配 + operateLogMapper.insert(cloneIgnoreId(operateLogDO, o -> o.setUserId(userId + 1))); + // 测试 module 不匹配 + operateLogMapper.insert(cloneIgnoreId(operateLogDO, o -> o.setModule("user"))); + // 测试 type 不匹配 + operateLogMapper.insert(cloneIgnoreId(operateLogDO, o -> o.setType(OperateTypeEnum.IMPORT.getType()))); + // 测试 createTime 不匹配 + operateLogMapper.insert(cloneIgnoreId(operateLogDO, o -> o.setStartTime(buildTime(2021, 2, 6)))); + // 测试 resultCode 不匹配 + operateLogMapper.insert(cloneIgnoreId(operateLogDO, o -> o.setResultCode(BAD_REQUEST.getCode()))); // 构造调用参数 OperateLogExportReqVO reqVO = new OperateLogExportReqVO(); - reqVO.setUserNickname("wangkai"); + reqVO.setUserNickname("wang"); reqVO.setModule("order"); reqVO.setType(OperateTypeEnum.CREATE.getType()); - reqVO.setStartTime((new LocalDateTime[]{buildTime(2021, 3, 5),buildTime(2021, 3, 7)})); + reqVO.setStartTime(buildBetweenTime(2021, 3, 5, 2021, 3, 7)); reqVO.setSuccess(true); // 调用 service 方法 - List list = operateLogServiceImpl.getOperateLogs(reqVO); + List list = operateLogServiceImpl.getOperateLogList(reqVO); // 断言,只查到了一条符合条件的 assertEquals(1, list.size()); - assertPojoEquals(sysOperateLogDO, list.get(0)); + assertPojoEquals(operateLogDO, list.get(0)); } } diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/mail/MailAccountServiceImplTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/mail/MailAccountServiceImplTest.java index ffca4b1b6..a0e41f75c 100755 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/mail/MailAccountServiceImplTest.java +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/mail/MailAccountServiceImplTest.java @@ -6,7 +6,6 @@ import cn.iocoder.yudao.module.system.controller.admin.mail.vo.account.MailAccou import cn.iocoder.yudao.module.system.controller.admin.mail.vo.account.MailAccountPageReqVO; import cn.iocoder.yudao.module.system.controller.admin.mail.vo.account.MailAccountUpdateReqVO; import cn.iocoder.yudao.module.system.dal.dataobject.mail.MailAccountDO; -import cn.iocoder.yudao.module.system.dal.dataobject.permission.RoleDO; import cn.iocoder.yudao.module.system.dal.mysql.mail.MailAccountMapper; import cn.iocoder.yudao.module.system.mq.producer.mail.MailProducer; import org.junit.jupiter.api.Test; @@ -14,7 +13,7 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import javax.annotation.Resource; - +import java.util.List; import java.util.Map; import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId; @@ -23,7 +22,9 @@ import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServic import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.MAIL_ACCOUNT_NOT_EXISTS; import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; /** * {@link MailAccountServiceImpl} 的单元测试类 @@ -109,6 +110,8 @@ public class MailAccountServiceImplTest extends BaseDbUnitTest { mailAccountMapper.insert(dbMailAccount);// @Sql: 先插入出一条存在的数据 // 准备参数 Long id = dbMailAccount.getId(); + // mock 方法(无关联模版) + when(mailTemplateService.countByAccountId(eq(id))).thenReturn(0L); // 调用 mailAccountService.deleteMailAccount(id); @@ -117,6 +120,21 @@ public class MailAccountServiceImplTest extends BaseDbUnitTest { verify(mailProducer).sendMailAccountRefreshMessage(); } + @Test + public void testGetMailAccountFromCache() { + // mock 数据 + MailAccountDO dbMailAccount = randomPojo(MailAccountDO.class); + mailAccountMapper.insert(dbMailAccount);// @Sql: 先插入出一条存在的数据 + mailAccountService.initLocalCache(); + // 准备参数 + Long id = dbMailAccount.getId(); + + // 调用 + MailAccountDO mailAccount = mailAccountService.getMailAccountFromCache(id); + // 断言 + assertPojoEquals(dbMailAccount, mailAccount); + } + @Test public void testDeleteMailAccount_notExists() { // 准备参数 @@ -151,4 +169,35 @@ public class MailAccountServiceImplTest extends BaseDbUnitTest { assertPojoEquals(dbMailAccount, pageResult.getList().get(0)); } + @Test + public void testGetMailAccount() { + // mock 数据 + MailAccountDO dbMailAccount = randomPojo(MailAccountDO.class); + mailAccountMapper.insert(dbMailAccount);// @Sql: 先插入出一条存在的数据 + // 准备参数 + Long id = dbMailAccount.getId(); + + // 调用 + MailAccountDO mailAccount = mailAccountService.getMailAccount(id); + // 断言 + assertPojoEquals(dbMailAccount, mailAccount); + } + + @Test + public void testGetMailAccountList() { + // mock 数据 + MailAccountDO dbMailAccount01 = randomPojo(MailAccountDO.class); + mailAccountMapper.insert(dbMailAccount01); + MailAccountDO dbMailAccount02 = randomPojo(MailAccountDO.class); + mailAccountMapper.insert(dbMailAccount02); + // 准备参数 + + // 调用 + List list = mailAccountService.getMailAccountList(); + // 断言 + assertEquals(2, list.size()); + assertPojoEquals(dbMailAccount01, list.get(0)); + assertPojoEquals(dbMailAccount02, list.get(1)); + } + } diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/mail/MailLogServiceImplTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/mail/MailLogServiceImplTest.java index ccf4ba737..53acd0ef0 100755 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/mail/MailLogServiceImplTest.java +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/mail/MailLogServiceImplTest.java @@ -116,6 +116,20 @@ public class MailLogServiceImplTest extends BaseDbUnitTest { assertEquals("NullPointerException: 测试异常", dbLog.getSendException()); } + @Test + public void testGetMailLog() { + // mock 数据 + MailLogDO dbMailLog = randomPojo(MailLogDO.class, o -> o.setTemplateParams(randomTemplateParams())); + mailLogMapper.insert(dbMailLog); + // 准备参数 + Long id = dbMailLog.getId(); + + // 调用 + MailLogDO mailLog = mailLogService.getMailLog(id); + // 断言 + assertPojoEquals(dbMailLog, mailLog); + } + @Test public void testGetMailLogPage() { // mock 数据 diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/mail/MailSendServiceImplTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/mail/MailSendServiceImplTest.java index e1be7e8d6..911e91c89 100644 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/mail/MailSendServiceImplTest.java +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/mail/MailSendServiceImplTest.java @@ -6,14 +6,20 @@ import cn.hutool.extra.mail.MailUtil; import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum; import cn.iocoder.yudao.framework.common.enums.UserTypeEnum; import cn.iocoder.yudao.framework.test.core.ut.BaseMockitoUnitTest; +import cn.iocoder.yudao.framework.test.core.util.RandomUtils; import cn.iocoder.yudao.module.system.dal.dataobject.mail.MailAccountDO; import cn.iocoder.yudao.module.system.dal.dataobject.mail.MailTemplateDO; +import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO; +import cn.iocoder.yudao.module.system.mq.message.mail.MailSendMessage; import cn.iocoder.yudao.module.system.mq.producer.mail.MailProducer; +import cn.iocoder.yudao.module.system.service.member.MemberService; +import cn.iocoder.yudao.module.system.service.user.AdminUserService; import org.assertj.core.util.Lists; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.MockedStatic; import java.util.HashMap; import java.util.Map; @@ -23,6 +29,7 @@ import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServic import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.*; @@ -31,6 +38,10 @@ class MailSendServiceImplTest extends BaseMockitoUnitTest { @InjectMocks private MailSendServiceImpl mailSendService; + @Mock + private AdminUserService adminUserService; + @Mock + private MemberService memberService; @Mock private MailAccountService mailAccountService; @Mock @@ -55,6 +66,82 @@ class MailSendServiceImplTest extends BaseMockitoUnitTest { System.out.println("发送结果:" + messageId); } + @Test + public void testSendSingleMailToAdmin() { + // 准备参数 + Long userId = randomLongId(); + String templateCode = RandomUtils.randomString(); + Map templateParams = MapUtil.builder().put("code", "1234") + .put("op", "login").build(); + // mock adminUserService 的方法 + AdminUserDO user = randomPojo(AdminUserDO.class, o -> o.setMobile("15601691300")); + when(adminUserService.getUser(eq(userId))).thenReturn(user); + + // mock MailTemplateService 的方法 + MailTemplateDO template = randomPojo(MailTemplateDO.class, o -> { + o.setStatus(CommonStatusEnum.ENABLE.getStatus()); + o.setContent("验证码为{code}, 操作为{op}"); + o.setParams(Lists.newArrayList("code", "op")); + }); + when(mailTemplateService.getMailTemplateByCodeFromCache(eq(templateCode))).thenReturn(template); + String content = RandomUtils.randomString(); + when(mailTemplateService.formatMailTemplateContent(eq(template.getContent()), eq(templateParams))) + .thenReturn(content); + // mock MailAccountService 的方法 + MailAccountDO account = randomPojo(MailAccountDO.class); + when(mailAccountService.getMailAccountFromCache(eq(template.getAccountId()))).thenReturn(account); + // mock MailLogService 的方法 + Long mailLogId = randomLongId(); + when(mailLogService.createMailLog(eq(userId), eq(UserTypeEnum.ADMIN.getValue()), eq(user.getEmail()), + eq(account), eq(template), eq(content), eq(templateParams), eq(true))).thenReturn(mailLogId); + + // 调用 + Long resultMailLogId = mailSendService.sendSingleMailToAdmin(null, userId, templateCode, templateParams); + // 断言 + assertEquals(mailLogId, resultMailLogId); + // 断言调用 + verify(mailProducer).sendMailSendMessage(eq(mailLogId), eq(user.getEmail()), + eq(account.getId()), eq(template.getNickname()), eq(template.getTitle()), eq(content)); + } + + @Test + public void testSendSingleMailToMember() { + // 准备参数 + Long userId = randomLongId(); + String templateCode = RandomUtils.randomString(); + Map templateParams = MapUtil.builder().put("code", "1234") + .put("op", "login").build(); + // mock memberService 的方法 + String mail = randomEmail(); + when(memberService.getMemberUserEmail(eq(userId))).thenReturn(mail); + + // mock MailTemplateService 的方法 + MailTemplateDO template = randomPojo(MailTemplateDO.class, o -> { + o.setStatus(CommonStatusEnum.ENABLE.getStatus()); + o.setContent("验证码为{code}, 操作为{op}"); + o.setParams(Lists.newArrayList("code", "op")); + }); + when(mailTemplateService.getMailTemplateByCodeFromCache(eq(templateCode))).thenReturn(template); + String content = RandomUtils.randomString(); + when(mailTemplateService.formatMailTemplateContent(eq(template.getContent()), eq(templateParams))) + .thenReturn(content); + // mock MailAccountService 的方法 + MailAccountDO account = randomPojo(MailAccountDO.class); + when(mailAccountService.getMailAccountFromCache(eq(template.getAccountId()))).thenReturn(account); + // mock MailLogService 的方法 + Long mailLogId = randomLongId(); + when(mailLogService.createMailLog(eq(userId), eq(UserTypeEnum.MEMBER.getValue()), eq(mail), + eq(account), eq(template), eq(content), eq(templateParams), eq(true))).thenReturn(mailLogId); + + // 调用 + Long resultMailLogId = mailSendService.sendSingleMailToMember(null, userId, templateCode, templateParams); + // 断言 + assertEquals(mailLogId, resultMailLogId); + // 断言调用 + verify(mailProducer).sendMailSendMessage(eq(mailLogId), eq(mail), + eq(account.getId()), eq(template.getNickname()), eq(template.getTitle()), eq(content)); + } + /** * 发送成功,当短信模板开启时 */ @@ -64,7 +151,7 @@ class MailSendServiceImplTest extends BaseMockitoUnitTest { String mail = randomEmail(); Long userId = randomLongId(); Integer userType = randomEle(UserTypeEnum.values()).getValue(); - String templateCode = randomString(); + String templateCode = RandomUtils.randomString(); Map templateParams = MapUtil.builder().put("code", "1234") .put("op", "login").build(); // mock MailTemplateService 的方法 @@ -74,7 +161,7 @@ class MailSendServiceImplTest extends BaseMockitoUnitTest { o.setParams(Lists.newArrayList("code", "op")); }); when(mailTemplateService.getMailTemplateByCodeFromCache(eq(templateCode))).thenReturn(template); - String content = randomString(); + String content = RandomUtils.randomString(); when(mailTemplateService.formatMailTemplateContent(eq(template.getContent()), eq(templateParams))) .thenReturn(content); // mock MailAccountService 的方法 @@ -103,7 +190,7 @@ class MailSendServiceImplTest extends BaseMockitoUnitTest { String mail = randomEmail(); Long userId = randomLongId(); Integer userType = randomEle(UserTypeEnum.values()).getValue(); - String templateCode = randomString(); + String templateCode = RandomUtils.randomString(); Map templateParams = MapUtil.builder().put("code", "1234") .put("op", "login").build(); // mock MailTemplateService 的方法 @@ -113,7 +200,7 @@ class MailSendServiceImplTest extends BaseMockitoUnitTest { o.setParams(Lists.newArrayList("code", "op")); }); when(mailTemplateService.getMailTemplateByCodeFromCache(eq(templateCode))).thenReturn(template); - String content = randomString(); + String content = RandomUtils.randomString(); when(mailTemplateService.formatMailTemplateContent(eq(template.getContent()), eq(templateParams))) .thenReturn(content); // mock MailAccountService 的方法 @@ -134,18 +221,18 @@ class MailSendServiceImplTest extends BaseMockitoUnitTest { } @Test - public void testCheckMailTemplateValid_notExists() { + public void testValidateMailTemplateValid_notExists() { // 准备参数 - String templateCode = randomString(); + String templateCode = RandomUtils.randomString(); // mock 方法 // 调用,并断言异常 - assertServiceException(() -> mailSendService.checkMailTemplateValid(templateCode), + assertServiceException(() -> mailSendService.validateMailTemplate(templateCode), MAIL_TEMPLATE_NOT_EXISTS); } @Test - public void testCheckTemplateParams_paramMiss() { + public void testValidateTemplateParams_paramMiss() { // 准备参数 MailTemplateDO template = randomPojo(MailTemplateDO.class, o -> o.setParams(Lists.newArrayList("code"))); @@ -153,18 +240,80 @@ class MailSendServiceImplTest extends BaseMockitoUnitTest { // mock 方法 // 调用,并断言异常 - assertServiceException(() -> mailSendService.checkTemplateParams(template, templateParams), + assertServiceException(() -> mailSendService.validateTemplateParams(template, templateParams), MAIL_SEND_TEMPLATE_PARAM_MISS, "code"); } @Test - public void testCheckMail_notExists() { + public void testValidateMail_notExists() { // 准备参数 // mock 方法 // 调用,并断言异常 - assertServiceException(() -> mailSendService.checkMail(null), + assertServiceException(() -> mailSendService.validateMail(null), MAIL_SEND_MAIL_NOT_EXISTS); } + @Test + public void testDoSendMail_success() { + try (MockedStatic mailUtilMock = mockStatic(MailUtil.class)) { + // 准备参数 + MailSendMessage message = randomPojo(MailSendMessage.class, o -> o.setNickname("芋艿")); + // mock 方法(获得邮箱账号) + MailAccountDO account = randomPojo(MailAccountDO.class, o -> o.setMail("7685@qq.com")); + when(mailAccountService.getMailAccountFromCache(eq(message.getAccountId()))) + .thenReturn(account); + + // mock 方法(发送邮件) + String messageId = randomString(); + mailUtilMock.when(() -> MailUtil.send(argThat(mailAccount -> { + assertEquals("芋艿 <7685@qq.com>", mailAccount.getFrom()); + assertTrue(mailAccount.isAuth()); + assertEquals(account.getUsername(), mailAccount.getUser()); + assertEquals(account.getPassword(), mailAccount.getPass()); + assertEquals(account.getHost(), mailAccount.getHost()); + assertEquals(account.getPort(), mailAccount.getPort()); + assertEquals(account.getSslEnable(), mailAccount.isSslEnable()); + return true; + }), eq(message.getMail()), eq(message.getTitle()), eq(message.getContent()), eq(true))) + .thenReturn(messageId); + + // 调用 + mailSendService.doSendMail(message); + // 断言 + verify(mailLogService).updateMailSendResult(eq(message.getLogId()), eq(messageId), isNull()); + } + } + + @Test + public void testDoSendMail_exception() { + try (MockedStatic mailUtilMock = mockStatic(MailUtil.class)) { + // 准备参数 + MailSendMessage message = randomPojo(MailSendMessage.class, o -> o.setNickname("芋艿")); + // mock 方法(获得邮箱账号) + MailAccountDO account = randomPojo(MailAccountDO.class, o -> o.setMail("7685@qq.com")); + when(mailAccountService.getMailAccountFromCache(eq(message.getAccountId()))) + .thenReturn(account); + + // mock 方法(发送邮件) + Exception e = new NullPointerException("啦啦啦"); + mailUtilMock.when(() -> MailUtil.send(argThat(mailAccount -> { + assertEquals("芋艿 <7685@qq.com>", mailAccount.getFrom()); + assertTrue(mailAccount.isAuth()); + assertEquals(account.getUsername(), mailAccount.getUser()); + assertEquals(account.getPassword(), mailAccount.getPass()); + assertEquals(account.getHost(), mailAccount.getHost()); + assertEquals(account.getPort(), mailAccount.getPort()); + assertEquals(account.getSslEnable(), mailAccount.isSslEnable()); + return true; + }), eq(message.getMail()), eq(message.getTitle()), eq(message.getContent()), eq(true))) + .thenThrow(e); + + // 调用 + mailSendService.doSendMail(message); + // 断言 + verify(mailLogService).updateMailSendResult(eq(message.getLogId()), isNull(), same(e)); + } + } + } diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/mail/MailTemplateServiceImplTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/mail/MailTemplateServiceImplTest.java index ab005822b..83f23e92e 100755 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/mail/MailTemplateServiceImplTest.java +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/mail/MailTemplateServiceImplTest.java @@ -6,7 +6,6 @@ import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import cn.iocoder.yudao.module.system.controller.admin.mail.vo.template.MailTemplateCreateReqVO; import cn.iocoder.yudao.module.system.controller.admin.mail.vo.template.MailTemplatePageReqVO; import cn.iocoder.yudao.module.system.controller.admin.mail.vo.template.MailTemplateUpdateReqVO; -import cn.iocoder.yudao.module.system.dal.dataobject.mail.MailAccountDO; import cn.iocoder.yudao.module.system.dal.dataobject.mail.MailTemplateDO; import cn.iocoder.yudao.module.system.dal.mysql.mail.MailTemplateMapper; import cn.iocoder.yudao.module.system.mq.producer.mail.MailProducer; @@ -15,7 +14,8 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import javax.annotation.Resource; - +import java.util.HashMap; +import java.util.List; import java.util.Map; import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildBetweenTime; @@ -27,6 +27,7 @@ import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomLongId import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo; import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.MAIL_TEMPLATE_NOT_EXISTS; import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.verify; /** * {@link MailTemplateServiceImpl} 的单元测试类 @@ -72,6 +73,7 @@ public class MailTemplateServiceImplTest extends BaseDbUnitTest { // 校验记录的属性是否正确 MailTemplateDO mailTemplate = mailTemplateMapper.selectById(mailTemplateId); assertPojoEquals(reqVO, mailTemplate); + verify(mailProducer).sendMailTemplateRefreshMessage(); } @Test @@ -89,6 +91,7 @@ public class MailTemplateServiceImplTest extends BaseDbUnitTest { // 校验是否更新正确 MailTemplateDO mailTemplate = mailTemplateMapper.selectById(reqVO.getId()); // 获取最新的 assertPojoEquals(reqVO, mailTemplate); + verify(mailProducer).sendMailTemplateRefreshMessage(); } @Test @@ -110,8 +113,9 @@ public class MailTemplateServiceImplTest extends BaseDbUnitTest { // 调用 mailTemplateService.deleteMailTemplate(id); - // 校验数据不存在了 - assertNull(mailTemplateMapper.selectById(id)); + // 校验数据不存在了 + assertNull(mailTemplateMapper.selectById(id)); + verify(mailProducer).sendMailTemplateRefreshMessage(); } @Test @@ -160,4 +164,77 @@ public class MailTemplateServiceImplTest extends BaseDbUnitTest { assertPojoEquals(dbMailTemplate, pageResult.getList().get(0)); } + @Test + public void testGetMailTemplateList() { + // mock 数据 + MailTemplateDO dbMailTemplate01 = randomPojo(MailTemplateDO.class); + mailTemplateMapper.insert(dbMailTemplate01); + MailTemplateDO dbMailTemplate02 = randomPojo(MailTemplateDO.class); + mailTemplateMapper.insert(dbMailTemplate02); + + // 调用 + List list = mailTemplateService.getMailTemplateList(); + // 断言 + assertEquals(2, list.size()); + assertEquals(dbMailTemplate01, list.get(0)); + assertEquals(dbMailTemplate02, list.get(1)); + } + + @Test + public void testGetMailTemplate() { + // mock 数据 + MailTemplateDO dbMailTemplate = randomPojo(MailTemplateDO.class); + mailTemplateMapper.insert(dbMailTemplate); + // 准备参数 + Long id = dbMailTemplate.getId(); + + // 调用 + MailTemplateDO mailTemplate = mailTemplateService.getMailTemplate(id); + // 断言 + assertPojoEquals(dbMailTemplate, mailTemplate); + } + + @Test + public void testGetMailTemplateByCodeFromCache() { + // mock 数据 + MailTemplateDO dbMailTemplate = randomPojo(MailTemplateDO.class); + mailTemplateMapper.insert(dbMailTemplate); + mailTemplateService.initLocalCache(); + // 准备参数 + String code = dbMailTemplate.getCode(); + + // 调用 + MailTemplateDO mailTemplate = mailTemplateService.getMailTemplateByCodeFromCache(code); + // 断言 + assertPojoEquals(dbMailTemplate, mailTemplate); + } + + @Test + public void testFormatMailTemplateContent() { + // 准备参数 + Map params = new HashMap<>(); + params.put("name", "小红"); + params.put("what", "饭"); + + // 调用,并断言 + assertEquals("小红,你好,饭吃了吗?", + mailTemplateService.formatMailTemplateContent("{name},你好,{what}吃了吗?", params)); + } + + @Test + public void testCountByAccountId() { + // mock 数据 + MailTemplateDO dbMailTemplate = randomPojo(MailTemplateDO.class); + mailTemplateMapper.insert(dbMailTemplate); + // 测试 accountId 不匹配 + mailTemplateMapper.insert(cloneIgnoreId(dbMailTemplate, o -> o.setAccountId(2L))); + // 准备参数 + Long accountId = dbMailTemplate.getAccountId(); + + // 调用 + long count = mailTemplateService.countByAccountId(accountId); + // 断言 + assertEquals(1, count); + } + } diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/notice/NoticeServiceImplTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/notice/NoticeServiceImplTest.java index a2af9545b..b4727096a 100644 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/notice/NoticeServiceImplTest.java +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/notice/NoticeServiceImplTest.java @@ -2,75 +2,67 @@ package cn.iocoder.yudao.module.system.service.notice; import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum; import cn.iocoder.yudao.framework.common.pojo.PageResult; +import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import cn.iocoder.yudao.module.system.controller.admin.notice.vo.NoticeCreateReqVO; import cn.iocoder.yudao.module.system.controller.admin.notice.vo.NoticePageReqVO; import cn.iocoder.yudao.module.system.controller.admin.notice.vo.NoticeUpdateReqVO; import cn.iocoder.yudao.module.system.dal.dataobject.notice.NoticeDO; import cn.iocoder.yudao.module.system.dal.mysql.notice.NoticeMapper; -import cn.iocoder.yudao.module.system.enums.notice.NoticeTypeEnum; -import cn.iocoder.yudao.framework.common.util.object.ObjectUtils; -import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import org.junit.jupiter.api.Test; import org.springframework.context.annotation.Import; import javax.annotation.Resource; -import java.util.function.Consumer; - -import static cn.hutool.core.util.RandomUtil.randomEle; -import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.NOTICE_NOT_FOUND; +import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomLongId; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo; +import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.NOTICE_NOT_FOUND; import static org.junit.jupiter.api.Assertions.*; @Import(NoticeServiceImpl.class) class NoticeServiceImplTest extends BaseDbUnitTest { @Resource - private NoticeServiceImpl sysNoticeService; + private NoticeServiceImpl noticeService; @Resource - private NoticeMapper sysNoticeMapper; + private NoticeMapper noticeMapper; @Test - public void testPageNotices_success() { + public void testGetNoticePage_success() { // 插入前置数据 NoticeDO dbNotice = randomPojo(NoticeDO.class, o -> { o.setTitle("尼古拉斯赵四来啦!"); o.setStatus(CommonStatusEnum.ENABLE.getStatus()); - o.setType(randomEle(NoticeTypeEnum.values()).getType()); }); - sysNoticeMapper.insert(dbNotice); - + noticeMapper.insert(dbNotice); // 测试 title 不匹配 - sysNoticeMapper.insert(ObjectUtils.cloneIgnoreId(dbNotice, o -> o.setTitle("尼古拉斯凯奇也来啦!"))); + noticeMapper.insert(cloneIgnoreId(dbNotice, o -> o.setTitle("尼古拉斯凯奇也来啦!"))); // 测试 status 不匹配 - sysNoticeMapper.insert(ObjectUtils.cloneIgnoreId(dbNotice, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus()))); - - - // 查询 + noticeMapper.insert(cloneIgnoreId(dbNotice, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus()))); + // 准备参数 NoticePageReqVO reqVO = new NoticePageReqVO(); reqVO.setTitle("尼古拉斯赵四来啦!"); reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus()); - PageResult pageResult = sysNoticeService.pageNotices(reqVO); + // 调用 + PageResult pageResult = noticeService.getNoticePage(reqVO); // 验证查询结果经过筛选 assertEquals(1, pageResult.getTotal()); assertEquals(1, pageResult.getList().size()); assertPojoEquals(dbNotice, pageResult.getList().get(0)); - } @Test public void testGetNotice_success() { // 插入前置数据 - NoticeDO dbNotice = randomNoticeDO(); - sysNoticeMapper.insert(dbNotice); + NoticeDO dbNotice = randomPojo(NoticeDO.class); + noticeMapper.insert(dbNotice); // 查询 - NoticeDO notice = sysNoticeService.getNotice(dbNotice.getId()); + NoticeDO notice = noticeService.getNotice(dbNotice.getId()); // 验证插入与读取对象是否一致 assertNotNull(notice); @@ -80,84 +72,59 @@ class NoticeServiceImplTest extends BaseDbUnitTest { @Test public void testCreateNotice_success() { // 准备参数 - NoticeCreateReqVO reqVO = randomNoticeCreateReqVO(); - - // 校验插入是否成功 - Long noticeId = sysNoticeService.createNotice(reqVO); - assertNotNull(noticeId); + NoticeCreateReqVO reqVO = randomPojo(NoticeCreateReqVO.class); + // 调用 + Long noticeId = noticeService.createNotice(reqVO); // 校验插入属性是否正确 - NoticeDO notice = sysNoticeMapper.selectById(noticeId); + assertNotNull(noticeId); + NoticeDO notice = noticeMapper.selectById(noticeId); assertPojoEquals(reqVO, notice); } @Test public void testUpdateNotice_success() { // 插入前置数据 - NoticeDO dbNoticeDO = randomNoticeDO(); - sysNoticeMapper.insert(dbNoticeDO); + NoticeDO dbNoticeDO = randomPojo(NoticeDO.class); + noticeMapper.insert(dbNoticeDO); // 准备更新参数 - NoticeUpdateReqVO reqVO = randomNoticeUpdateReqVO(o -> o.setId(dbNoticeDO.getId())); + NoticeUpdateReqVO reqVO = randomPojo(NoticeUpdateReqVO.class, o -> o.setId(dbNoticeDO.getId())); // 更新 - sysNoticeService.updateNotice(reqVO); - + noticeService.updateNotice(reqVO); // 检验是否更新成功 - NoticeDO notice = sysNoticeMapper.selectById(reqVO.getId()); + NoticeDO notice = noticeMapper.selectById(reqVO.getId()); assertPojoEquals(reqVO, notice); } @Test public void testDeleteNotice_success() { // 插入前置数据 - NoticeDO dbNotice = randomNoticeDO(); - sysNoticeMapper.insert(dbNotice); + NoticeDO dbNotice = randomPojo(NoticeDO.class); + noticeMapper.insert(dbNotice); // 删除 - sysNoticeService.deleteNotice(dbNotice.getId()); + noticeService.deleteNotice(dbNotice.getId()); // 检查是否删除成功 - assertNull(sysNoticeMapper.selectById(dbNotice.getId())); + assertNull(noticeMapper.selectById(dbNotice.getId())); } @Test - public void checkNoticeExists_success() { + public void testValidateNoticeExists_success() { // 插入前置数据 - NoticeDO dbNotice = randomNoticeDO(); - sysNoticeMapper.insert(dbNotice); + NoticeDO dbNotice = randomPojo(NoticeDO.class); + noticeMapper.insert(dbNotice); // 成功调用 - sysNoticeService.checkNoticeExists(dbNotice.getId()); + noticeService.validateNoticeExists(dbNotice.getId()); } @Test - public void checkNoticeExists_noExists() { - assertServiceException(() -> sysNoticeService.checkNoticeExists(randomLongId()), NOTICE_NOT_FOUND); + public void testValidateNoticeExists_noExists() { + assertServiceException(() -> + noticeService.validateNoticeExists(randomLongId()), NOTICE_NOT_FOUND); } - @SafeVarargs - private static NoticeDO randomNoticeDO(Consumer... consumers) { - NoticeDO notice = randomPojo(NoticeDO.class, consumers); - notice.setType(randomEle(NoticeTypeEnum.values()).getType()); - notice.setStatus(CommonStatusEnum.ENABLE.getStatus()); - return notice; - } - - @SafeVarargs - private static NoticeUpdateReqVO randomNoticeUpdateReqVO(Consumer... consumers) { - NoticeUpdateReqVO reqVO = randomPojo(NoticeUpdateReqVO.class, consumers); - reqVO.setType(randomEle(NoticeTypeEnum.values()).getType()); - reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus()); - return reqVO; - } - - private static NoticeCreateReqVO randomNoticeCreateReqVO() { - NoticeCreateReqVO reqVO = randomPojo(NoticeCreateReqVO.class); - reqVO.setType(randomEle(NoticeTypeEnum.values()).getType()); - reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus()); - return reqVO; - } - - } diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/notify/NotifyMessageServiceImplTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/notify/NotifyMessageServiceImplTest.java index 1087918cc..9e2158da1 100644 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/notify/NotifyMessageServiceImplTest.java +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/notify/NotifyMessageServiceImplTest.java @@ -108,6 +108,20 @@ public class NotifyMessageServiceImplTest extends BaseDbUnitTest { assertPojoEquals(dbNotifyMessage, pageResult.getList().get(0)); } + @Test + public void testGetNotifyMessage() { + // mock 数据 + NotifyMessageDO dbNotifyMessage = randomPojo(NotifyMessageDO.class, + o -> o.setTemplateParams(randomTemplateParams())); + notifyMessageMapper.insert(dbNotifyMessage); + // 准备参数 + Long id = dbNotifyMessage.getId(); + + // 调用 + NotifyMessageDO notifyMessage = notifyMessageService.getNotifyMessage(id); + assertPojoEquals(dbNotifyMessage, notifyMessage); + } + @Test public void testGetMyNotifyMessagePage() { // mock 数据 diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/notify/NotifySendServiceImplTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/notify/NotifySendServiceImplTest.java index e3ee32853..7c5078330 100644 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/notify/NotifySendServiceImplTest.java +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/notify/NotifySendServiceImplTest.java @@ -4,8 +4,6 @@ import cn.hutool.core.map.MapUtil; import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum; import cn.iocoder.yudao.framework.common.enums.UserTypeEnum; import cn.iocoder.yudao.framework.test.core.ut.BaseMockitoUnitTest; -import cn.iocoder.yudao.module.system.dal.dataobject.mail.MailAccountDO; -import cn.iocoder.yudao.module.system.dal.dataobject.mail.MailTemplateDO; import cn.iocoder.yudao.module.system.dal.dataobject.notify.NotifyTemplateDO; import org.assertj.core.util.Lists; import org.junit.jupiter.api.Test; @@ -18,7 +16,8 @@ import java.util.Map; import static cn.hutool.core.util.RandomUtil.randomEle; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; -import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*; +import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.NOTICE_NOT_FOUND; +import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.NOTIFY_SEND_TEMPLATE_PARAM_MISS; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.ArgumentMatchers.eq; @@ -34,6 +33,62 @@ class NotifySendServiceImplTest extends BaseMockitoUnitTest { @Mock private NotifyMessageService notifyMessageService; + @Test + public void testSendSingleNotifyToAdmin() { + // 准备参数 + Long userId = randomLongId(); + String templateCode = randomString(); + Map templateParams = MapUtil.builder().put("code", "1234") + .put("op", "login").build(); + // mock NotifyTemplateService 的方法 + NotifyTemplateDO template = randomPojo(NotifyTemplateDO.class, o -> { + o.setStatus(CommonStatusEnum.ENABLE.getStatus()); + o.setContent("验证码为{code}, 操作为{op}"); + o.setParams(Lists.newArrayList("code", "op")); + }); + when(notifyTemplateService.getNotifyTemplateByCodeFromCache(eq(templateCode))).thenReturn(template); + String content = randomString(); + when(notifyTemplateService.formatNotifyTemplateContent(eq(template.getContent()), eq(templateParams))) + .thenReturn(content); + // mock NotifyMessageService 的方法 + Long messageId = randomLongId(); + when(notifyMessageService.createNotifyMessage(eq(userId), eq(UserTypeEnum.ADMIN.getValue()), + eq(template), eq(content), eq(templateParams))).thenReturn(messageId); + + // 调用 + Long resultMessageId = notifySendService.sendSingleNotifyToAdmin(userId, templateCode, templateParams); + // 断言 + assertEquals(messageId, resultMessageId); + } + + @Test + public void testSendSingleNotifyToMember() { + // 准备参数 + Long userId = randomLongId(); + String templateCode = randomString(); + Map templateParams = MapUtil.builder().put("code", "1234") + .put("op", "login").build(); + // mock NotifyTemplateService 的方法 + NotifyTemplateDO template = randomPojo(NotifyTemplateDO.class, o -> { + o.setStatus(CommonStatusEnum.ENABLE.getStatus()); + o.setContent("验证码为{code}, 操作为{op}"); + o.setParams(Lists.newArrayList("code", "op")); + }); + when(notifyTemplateService.getNotifyTemplateByCodeFromCache(eq(templateCode))).thenReturn(template); + String content = randomString(); + when(notifyTemplateService.formatNotifyTemplateContent(eq(template.getContent()), eq(templateParams))) + .thenReturn(content); + // mock NotifyMessageService 的方法 + Long messageId = randomLongId(); + when(notifyMessageService.createNotifyMessage(eq(userId), eq(UserTypeEnum.MEMBER.getValue()), + eq(template), eq(content), eq(templateParams))).thenReturn(messageId); + + // 调用 + Long resultMessageId = notifySendService.sendSingleNotifyToMember(userId, templateCode, templateParams); + // 断言 + assertEquals(messageId, resultMessageId); + } + /** * 发送成功,当短信模板开启时 */ @@ -100,7 +155,7 @@ class NotifySendServiceImplTest extends BaseMockitoUnitTest { // mock 方法 // 调用,并断言异常 - assertServiceException(() -> notifySendService.checkNotifyTemplateValid(templateCode), + assertServiceException(() -> notifySendService.validateNotifyTemplate(templateCode), NOTICE_NOT_FOUND); } @@ -113,7 +168,7 @@ class NotifySendServiceImplTest extends BaseMockitoUnitTest { // mock 方法 // 调用,并断言异常 - assertServiceException(() -> notifySendService.checkTemplateParams(template, templateParams), + assertServiceException(() -> notifySendService.validateTemplateParams(template, templateParams), NOTIFY_SEND_TEMPLATE_PARAM_MISS, "code"); } diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/notify/NotifyTemplateServiceImplTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/notify/NotifyTemplateServiceImplTest.java index 5a6f5a508..28f6f9a38 100644 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/notify/NotifyTemplateServiceImplTest.java +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/notify/NotifyTemplateServiceImplTest.java @@ -14,6 +14,8 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import javax.annotation.Resource; +import java.util.HashMap; +import java.util.Map; import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildBetweenTime; import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildTime; @@ -143,4 +145,44 @@ public class NotifyTemplateServiceImplTest extends BaseDbUnitTest { assertPojoEquals(dbNotifyTemplate, pageResult.getList().get(0)); } + @Test + public void testGetNotifyTemplate() { + // mock 数据 + NotifyTemplateDO dbNotifyTemplate = randomPojo(NotifyTemplateDO.class); + notifyTemplateMapper.insert(dbNotifyTemplate); + // 准备参数 + Long id = dbNotifyTemplate.getId(); + + // 调用 + NotifyTemplateDO notifyTemplate = notifyTemplateService.getNotifyTemplate(id); + // 断言 + assertPojoEquals(dbNotifyTemplate, notifyTemplate); + } + + @Test + public void testGetNotifyTemplateByCodeFromCache() { + // mock 数据 + NotifyTemplateDO dbNotifyTemplate = randomPojo(NotifyTemplateDO.class); + notifyTemplateMapper.insert(dbNotifyTemplate); + notifyTemplateService.initLocalCache(); + // 准备参数 + String code = dbNotifyTemplate.getCode(); + + // 调用 + NotifyTemplateDO notifyTemplate = notifyTemplateService.getNotifyTemplateByCodeFromCache(code); + // 断言 + assertPojoEquals(dbNotifyTemplate, notifyTemplate); + } + + @Test + public void testFormatNotifyTemplateContent() { + // 准备参数 + Map params = new HashMap<>(); + params.put("name", "小红"); + params.put("what", "饭"); + + // 调用,并断言 + assertEquals("小红,你好,饭吃了吗?", + notifyTemplateService.formatNotifyTemplateContent("{name},你好,{what}吃了吗?", params)); + } } diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/oauth2/OAuth2ClientServiceImplTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/oauth2/OAuth2ClientServiceImplTest.java index 50401cf97..3a671b0b9 100755 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/oauth2/OAuth2ClientServiceImplTest.java +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/oauth2/OAuth2ClientServiceImplTest.java @@ -153,6 +153,19 @@ public class OAuth2ClientServiceImplTest extends BaseDbUnitTest { assertServiceException(() -> oauth2ClientService.validateClientIdExists(null, clientId), OAUTH2_CLIENT_EXISTS); } + @Test + public void testGetOAuth2Client() { + // mock 数据 + OAuth2ClientDO clientDO = randomPojo(OAuth2ClientDO.class); + oauth2ClientMapper.insert(clientDO); + // 准备参数 + Long id = clientDO.getId(); + + // 调用,并断言 + OAuth2ClientDO dbClientDO = oauth2ClientService.getOAuth2Client(id); + assertPojoEquals(clientDO, dbClientDO); + } + @Test public void testGetOAuth2ClientPage() { // mock 数据 @@ -203,10 +216,13 @@ public class OAuth2ClientServiceImplTest extends BaseDbUnitTest { null, null, Collections.singleton(randomString()), null), OAUTH2_CLIENT_SCOPE_OVER); assertServiceException(() -> oauth2ClientService.validOAuthClientFromCache("default", null, null, null, "test"), OAUTH2_CLIENT_REDIRECT_URI_NOT_MATCH, "test"); - // 成功调用 + // 成功调用(1:参数完整) OAuth2ClientDO result = oauth2ClientService.validOAuthClientFromCache(client.getClientId(), client.getSecret(), client.getAuthorizedGrantTypes().get(0), client.getScopes(), client.getRedirectUris().get(0)); assertPojoEquals(client, result); + // 成功调用(2:只有 clientId 参数) + result = oauth2ClientService.validOAuthClientFromCache(client.getClientId()); + assertPojoEquals(client, result); } } diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/oauth2/OAuth2GrantServiceImplTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/oauth2/OAuth2GrantServiceImplTest.java index 944086671..52c722831 100644 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/oauth2/OAuth2GrantServiceImplTest.java +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/oauth2/OAuth2GrantServiceImplTest.java @@ -16,6 +16,7 @@ import java.util.List; import static cn.hutool.core.util.RandomUtil.randomEle; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; +import static java.util.Collections.emptyList; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; @@ -134,6 +135,13 @@ public class OAuth2GrantServiceImplTest extends BaseMockitoUnitTest { refreshToken, clientId)); } + @Test + public void testGrantClientCredentials() { + assertThrows(UnsupportedOperationException.class, + () -> oauth2GrantService.grantClientCredentials(randomString(), emptyList()), + "暂时不支持 client_credentials 授权模式"); + } + @Test public void testRevokeToken_clientIdError() { // 准备参数 diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/permission/MenuServiceImplTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/permission/MenuServiceImplTest.java new file mode 100644 index 000000000..d643c5501 --- /dev/null +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/permission/MenuServiceImplTest.java @@ -0,0 +1,407 @@ +package cn.iocoder.yudao.module.system.service.permission; + +import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum; +import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; +import cn.iocoder.yudao.module.system.controller.admin.permission.vo.menu.MenuCreateReqVO; +import cn.iocoder.yudao.module.system.controller.admin.permission.vo.menu.MenuListReqVO; +import cn.iocoder.yudao.module.system.controller.admin.permission.vo.menu.MenuUpdateReqVO; +import cn.iocoder.yudao.module.system.dal.dataobject.permission.MenuDO; +import cn.iocoder.yudao.module.system.dal.mysql.permission.MenuMapper; +import cn.iocoder.yudao.module.system.enums.permission.MenuTypeEnum; +import cn.iocoder.yudao.module.system.mq.producer.permission.MenuProducer; +import cn.iocoder.yudao.module.system.service.tenant.TenantService; +import com.google.common.collect.LinkedListMultimap; +import com.google.common.collect.Multimap; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.context.annotation.Import; + +import javax.annotation.Resource; +import java.util.*; + +import static cn.iocoder.yudao.framework.common.util.collection.SetUtils.asSet; +import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId; +import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; +import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; +import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; +import static cn.iocoder.yudao.module.system.dal.dataobject.permission.MenuDO.ID_ROOT; +import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*; +import static java.util.Arrays.asList; +import static java.util.Collections.singletonList; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.verify; + +@Import(MenuServiceImpl.class) +public class MenuServiceImplTest extends BaseDbUnitTest { + + @Resource + private MenuServiceImpl menuService; + + @Resource + private MenuMapper menuMapper; + + @MockBean + private PermissionService permissionService; + @MockBean + private MenuProducer menuProducer; + @MockBean + private TenantService tenantService; + + @Test + public void testInitLocalCache_success() { + MenuDO menuDO1 = randomPojo(MenuDO.class); + menuMapper.insert(menuDO1); + MenuDO menuDO2 = randomPojo(MenuDO.class); + menuMapper.insert(menuDO2); + + // 调用 + menuService.initLocalCache(); + // 校验 menuCache 缓存 + Map menuCache = menuService.getMenuCache(); + assertEquals(2, menuCache.size()); + assertPojoEquals(menuDO1, menuCache.get(menuDO1.getId())); + assertPojoEquals(menuDO2, menuCache.get(menuDO2.getId())); + // 校验 permissionMenuCache 缓存 + Multimap permissionMenuCache = menuService.getPermissionMenuCache(); + assertEquals(2, permissionMenuCache.size()); + assertPojoEquals(menuDO1, permissionMenuCache.get(menuDO1.getPermission())); + assertPojoEquals(menuDO2, permissionMenuCache.get(menuDO2.getPermission())); + } + + @Test + public void testCreateMenu_success() { + // mock 数据(构造父菜单) + MenuDO menuDO = createMenuDO(MenuTypeEnum.MENU, + "parent", 0L); + menuMapper.insert(menuDO); + Long parentId = menuDO.getId(); + // 准备参数 + MenuCreateReqVO reqVO = randomPojo(MenuCreateReqVO.class, o -> { + o.setParentId(parentId); + o.setName("testSonName"); + o.setType(MenuTypeEnum.MENU.getType()); + }); + Long menuId = menuService.createMenu(reqVO); + + // 校验记录的属性是否正确 + MenuDO dbMenu = menuMapper.selectById(menuId); + assertPojoEquals(reqVO, dbMenu); + // 校验调用 + verify(menuProducer).sendMenuRefreshMessage(); + } + + @Test + public void testUpdateMenu_success() { + // mock 数据(构造父子菜单) + MenuDO sonMenuDO = initParentAndSonMenu(); + Long sonId = sonMenuDO.getId(); + // 准备参数 + MenuUpdateReqVO reqVO = randomPojo(MenuUpdateReqVO.class, o -> { + o.setId(sonId); + o.setName("testSonName"); // 修改名字 + o.setParentId(sonMenuDO.getParentId()); + o.setType(MenuTypeEnum.MENU.getType()); + }); + + // 调用 + menuService.updateMenu(reqVO); + // 校验记录的属性是否正确 + MenuDO dbMenu = menuMapper.selectById(sonId); + assertPojoEquals(reqVO, dbMenu); + // 校验调用 + verify(menuProducer).sendMenuRefreshMessage(); + } + + @Test + public void testUpdateMenu_sonIdNotExist() { + // 准备参数 + MenuUpdateReqVO reqVO = randomPojo(MenuUpdateReqVO.class); + // 调用,并断言异常 + assertServiceException(() -> menuService.updateMenu(reqVO), MENU_NOT_EXISTS); + } + + @Test + public void testDeleteMenu_success() { + // mock 数据 + MenuDO menuDO = randomPojo(MenuDO.class); + menuMapper.insert(menuDO); + // 准备参数 + Long id = menuDO.getId(); + + // 调用 + menuService.deleteMenu(id); + // 断言 + MenuDO dbMenuDO = menuMapper.selectById(id); + assertNull(dbMenuDO); + verify(permissionService).processMenuDeleted(id); + verify(menuProducer).sendMenuRefreshMessage(); + } + + @Test + public void testDeleteMenu_menuNotExist() { + assertServiceException(() -> menuService.deleteMenu(randomLongId()), + MENU_NOT_EXISTS); + } + + @Test + public void testDeleteMenu_existChildren() { + // mock 数据(构造父子菜单) + MenuDO sonMenu = initParentAndSonMenu(); + // 准备参数 + Long parentId = sonMenu.getParentId(); + + // 调用并断言异常 + assertServiceException(() -> menuService.deleteMenu(parentId), MENU_EXISTS_CHILDREN); + } + + @Test + public void testGetMenuList_all() { + // mock 数据 + MenuDO menu100 = randomPojo(MenuDO.class); + menuMapper.insert(menu100); + MenuDO menu101 = randomPojo(MenuDO.class); + menuMapper.insert(menu101); + // 准备参数 + + // 调用 + List list = menuService.getMenuList(); + // 断言 + assertEquals(2, list.size()); + assertPojoEquals(menu100, list.get(0)); + assertPojoEquals(menu101, list.get(1)); + } + + @Test + public void testGetMenuList() { + // mock 数据 + MenuDO menuDO = randomPojo(MenuDO.class, o -> o.setName("芋艿").setStatus(CommonStatusEnum.ENABLE.getStatus())); + menuMapper.insert(menuDO); + // 测试 status 不匹配 + menuMapper.insert(cloneIgnoreId(menuDO, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus()))); + // 测试 name 不匹配 + menuMapper.insert(cloneIgnoreId(menuDO, o -> o.setName("艿"))); + // 准备参数 + MenuListReqVO reqVO = new MenuListReqVO().setName("芋").setStatus(CommonStatusEnum.ENABLE.getStatus()); + + // 调用 + List result = menuService.getMenuList(reqVO); + // 断言 + assertEquals(1, result.size()); + assertPojoEquals(menuDO, result.get(0)); + } + + @Test + public void testGetMenuListByTenant() { + // mock 数据 + MenuDO menu100 = randomPojo(MenuDO.class, o -> o.setId(100L).setStatus(CommonStatusEnum.ENABLE.getStatus())); + menuMapper.insert(menu100); + MenuDO menu101 = randomPojo(MenuDO.class, o -> o.setId(101L).setStatus(CommonStatusEnum.DISABLE.getStatus())); + menuMapper.insert(menu101); + MenuDO menu102 = randomPojo(MenuDO.class, o -> o.setId(102L).setStatus(CommonStatusEnum.ENABLE.getStatus())); + menuMapper.insert(menu102); + // mock 过滤菜单 + Set menuIds = asSet(100L, 101L); + doNothing().when(tenantService).handleTenantMenu(argThat(handler -> { + handler.handle(menuIds); + return true; + })); + // 准备参数 + MenuListReqVO reqVO = new MenuListReqVO().setStatus(CommonStatusEnum.ENABLE.getStatus()); + + // 调用 + List result = menuService.getMenuListByTenant(reqVO); + // 断言 + assertEquals(1, result.size()); + assertPojoEquals(menu100, result.get(0)); + } + + @Test + public void testListMenusFromCache_withoutId() { + // mock 缓存 + Map menuCache = new HashMap<>(); + // 可被匹配 + MenuDO menuDO = randomPojo(MenuDO.class, o -> o.setId(1L) + .setType(MenuTypeEnum.MENU.getType()).setStatus(CommonStatusEnum.ENABLE.getStatus())); + menuCache.put(menuDO.getId(), menuDO); + // 测试 type 不匹配 + menuCache.put(3L, randomPojo(MenuDO.class, o -> o.setId(3L) + .setType(MenuTypeEnum.BUTTON.getType()).setStatus(CommonStatusEnum.ENABLE.getStatus()))); + // 测试 status 不匹配 + menuCache.put(4L, randomPojo(MenuDO.class, o -> o.setId(4L) + .setType(MenuTypeEnum.MENU.getType()).setStatus(CommonStatusEnum.DISABLE.getStatus()))); + menuService.setMenuCache(menuCache); + // 准备参数 + Collection menuTypes = singletonList(MenuTypeEnum.MENU.getType()); + Collection menusStatuses = singletonList(CommonStatusEnum.ENABLE.getStatus()); + + // 调用 + List list = menuService.getMenuListFromCache(menuTypes, menusStatuses); + // 断言 + assertEquals(1, list.size()); + assertPojoEquals(menuDO, list.get(0)); + } + + @Test + public void testListMenusFromCache_withId() { + // mock 缓存 + Map menuCache = new HashMap<>(); + // 可被匹配 + MenuDO menuDO = randomPojo(MenuDO.class, o -> o.setId(1L) + .setType(MenuTypeEnum.MENU.getType()).setStatus(CommonStatusEnum.ENABLE.getStatus())); + menuCache.put(menuDO.getId(), menuDO); + // 测试 id 不匹配 + menuCache.put(2L, randomPojo(MenuDO.class, o -> o.setId(2L) + .setType(MenuTypeEnum.MENU.getType()).setStatus(CommonStatusEnum.ENABLE.getStatus()))); + // 测试 type 不匹配 + menuCache.put(3L, randomPojo(MenuDO.class, o -> o.setId(3L) + .setType(MenuTypeEnum.BUTTON.getType()).setStatus(CommonStatusEnum.ENABLE.getStatus()))); + // 测试 status 不匹配 + menuCache.put(4L, randomPojo(MenuDO.class, o -> o.setId(4L) + .setType(MenuTypeEnum.MENU.getType()).setStatus(CommonStatusEnum.DISABLE.getStatus()))); + menuService.setMenuCache(menuCache); + // 准备参数 + Collection menuIds = asList(1L, 3L, 4L); + Collection menuTypes = singletonList(MenuTypeEnum.MENU.getType()); + Collection menusStatuses = singletonList(CommonStatusEnum.ENABLE.getStatus()); + + // 调用 + List list = menuService.getMenuListFromCache(menuIds, menuTypes, menusStatuses); + // 断言 + assertEquals(1, list.size()); + assertPojoEquals(menuDO, list.get(0)); + } + + @Test + public void testGetMenuListByPermissionFromCache() { + // mock 缓存 + Multimap permissionMenuCache = LinkedListMultimap.create(); + // 可被匹配 + MenuDO menuDO01 = randomPojo(MenuDO.class, o -> o.setId(1L).setPermission("123")); + permissionMenuCache.put(menuDO01.getPermission(), menuDO01); + MenuDO menuDO02 = randomPojo(MenuDO.class, o -> o.setId(2L).setPermission("123")); + permissionMenuCache.put(menuDO02.getPermission(), menuDO02); + // 不可匹配 + permissionMenuCache.put("456", randomPojo(MenuDO.class, o -> o.setId(3L).setPermission("456"))); + menuService.setPermissionMenuCache(permissionMenuCache); + // 准备参数 + String permission = "123"; + + // 调用 + List list = menuService.getMenuListByPermissionFromCache(permission); + // 断言 + assertEquals(2, list.size()); + assertPojoEquals(menuDO01, list.get(0)); + assertPojoEquals(menuDO02, list.get(1)); + } + + @Test + public void testGetMenu() { + // mock 数据 + MenuDO menu = randomPojo(MenuDO.class); + menuMapper.insert(menu); + // 准备参数 + Long id = menu.getId(); + + // 调用 + MenuDO dbMenu = menuService.getMenu(id); + // 断言 + assertPojoEquals(menu, dbMenu); + } + + @Test + public void testValidateParentMenu_success() { + // mock 数据 + MenuDO menuDO = createMenuDO(MenuTypeEnum.MENU, "parent", 0L); + menuMapper.insert(menuDO); + // 准备参数 + Long parentId = menuDO.getId(); + + // 调用,无需断言 + menuService.validateParentMenu(parentId, null); + } + + @Test + public void testValidateParentMenu_canNotSetSelfToBeParent() { + // 调用,并断言异常 + assertServiceException(() -> menuService.validateParentMenu(1L, 1L), + MENU_PARENT_ERROR); + } + + @Test + public void testValidateParentMenu_parentNotExist() { + // 调用,并断言异常 + assertServiceException(() -> menuService.validateParentMenu(randomLongId(), null), + MENU_PARENT_NOT_EXISTS); + } + + @Test + public void testValidateParentMenu_parentTypeError() { + // mock 数据 + MenuDO menuDO = createMenuDO(MenuTypeEnum.BUTTON, "parent", 0L); + menuMapper.insert(menuDO); + // 准备参数 + Long parentId = menuDO.getId(); + + // 调用,并断言异常 + assertServiceException(() -> menuService.validateParentMenu(parentId, null), + MENU_PARENT_NOT_DIR_OR_MENU); + } + + @Test + public void testValidateMenu_success() { + // mock 父子菜单 + MenuDO sonMenu = initParentAndSonMenu(); + // 准备参数 + Long parentId = sonMenu.getParentId(); + Long otherSonMenuId = randomLongId(); + String otherSonMenuName = randomString(); + + // 调用,无需断言 + menuService.validateMenu(parentId, otherSonMenuName, otherSonMenuId); + } + + @Test + public void testValidateMenu_sonMenuNameDuplicate() { + // mock 父子菜单 + MenuDO sonMenu = initParentAndSonMenu(); + // 准备参数 + Long parentId = sonMenu.getParentId(); + Long otherSonMenuId = randomLongId(); + String otherSonMenuName = sonMenu.getName(); //相同名称 + + // 调用,并断言异常 + assertServiceException(() -> menuService.validateMenu(parentId, otherSonMenuName, otherSonMenuId), + MENU_NAME_DUPLICATE); + } + + // ====================== 初始化方法 ====================== + + /** + * 构造父子菜单,返回子菜单 + * + * @return 子菜单 + */ + private MenuDO initParentAndSonMenu() { + // 构造父子菜单 + MenuDO parentMenuDO = createMenuDO(MenuTypeEnum.MENU, "parent", ID_ROOT); + menuMapper.insert(parentMenuDO); + // 构建子菜单 + MenuDO sonMenuDO = createMenuDO(MenuTypeEnum.MENU, "testSonName", + parentMenuDO.getParentId()); + menuMapper.insert(sonMenuDO); + return sonMenuDO; + } + + private MenuDO createMenuDO(MenuTypeEnum type, String name, Long parentId) { + return createMenuDO(type, name, parentId, randomCommonStatus()); + } + + private MenuDO createMenuDO(MenuTypeEnum type, String name, Long parentId, Integer status) { + return randomPojo(MenuDO.class, o -> o.setId(null).setName(name).setParentId(parentId) + .setType(type.getType()).setStatus(status)); + } + +} diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/permission/MenuServiceTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/permission/MenuServiceTest.java deleted file mode 100644 index eae4633b1..000000000 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/permission/MenuServiceTest.java +++ /dev/null @@ -1,384 +0,0 @@ -package cn.iocoder.yudao.module.system.service.permission; - -import cn.hutool.core.bean.BeanUtil; -import cn.hutool.core.lang.Assert; -import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum; -import cn.iocoder.yudao.framework.common.util.spring.SpringAopUtils; -import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; -import cn.iocoder.yudao.module.system.controller.admin.permission.vo.menu.MenuCreateReqVO; -import cn.iocoder.yudao.module.system.controller.admin.permission.vo.menu.MenuListReqVO; -import cn.iocoder.yudao.module.system.controller.admin.permission.vo.menu.MenuUpdateReqVO; -import cn.iocoder.yudao.module.system.dal.dataobject.permission.MenuDO; -import cn.iocoder.yudao.module.system.dal.mysql.permission.MenuMapper; -import cn.iocoder.yudao.module.system.enums.permission.MenuTypeEnum; -import cn.iocoder.yudao.module.system.mq.producer.permission.MenuProducer; -import cn.iocoder.yudao.module.system.service.tenant.TenantService; -import com.google.common.collect.Multimap; -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.context.annotation.Import; - -import javax.annotation.Resource; -import java.util.*; - -import static cn.iocoder.yudao.framework.common.util.collection.SetUtils.asSet; -import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; -import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; -import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; -import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.argThat; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.verify; - -// TODO @芋艿:单测的代码质量可以提升下 -@Import(MenuServiceImpl.class) -public class MenuServiceTest extends BaseDbUnitTest { - - @Resource - private MenuServiceImpl menuService; - - @Resource - private MenuMapper menuMapper; - - @MockBean - private PermissionService permissionService; - @MockBean - private MenuProducer menuProducer; - @MockBean - private TenantService tenantService; - - @Test - public void testInitLocalCache_success() { - MenuDO menuDO1 = randomPojo(MenuDO.class); - menuMapper.insert(menuDO1); - MenuDO menuDO2 = randomPojo(MenuDO.class); - menuMapper.insert(menuDO2); - - // 调用 - menuService.initLocalCache(); - // 校验 menuCache 缓存 - Map menuCache = menuService.getMenuCache(); - Assert.isTrue(menuCache.size() == 2); - assertPojoEquals(menuDO1, menuCache.get(menuDO1.getId())); - assertPojoEquals(menuDO2, menuCache.get(menuDO2.getId())); - // 校验 permissionMenuCache 缓存 - Multimap permissionMenuCache = menuService.getPermissionMenuCache(); - Assert.isTrue(permissionMenuCache.size() == 2); - assertPojoEquals(menuDO1, permissionMenuCache.get(menuDO1.getPermission())); - assertPojoEquals(menuDO2, permissionMenuCache.get(menuDO2.getPermission())); - } - - @Test - public void testCreateMenu_success() { - //构造父目录 - MenuDO menuDO = createMenuDO(MenuTypeEnum.MENU, "parent", 0L); - menuMapper.insert(menuDO); - Long parentId = menuDO.getId(); - - //调用 - MenuCreateReqVO vo = randomPojo(MenuCreateReqVO.class, o -> { - o.setParentId(parentId); - o.setName("testSonName"); - o.setType(MenuTypeEnum.MENU.getType()); - o.setStatus(randomCommonStatus()); - }); - Long menuId = menuService.createMenu(vo); - - //断言 - assertNotNull(menuId); - // 校验记录的属性是否正确 - MenuDO ret = menuMapper.selectById(menuId); - assertPojoEquals(vo, ret); - // 校验调用 - verify(menuProducer).sendMenuRefreshMessage(); - } - - @Test - public void testUpdateMenu_success() { - //构造父子目录 - MenuDO sonMenuDO = initParentAndSonMenuDO(); - Long sonId = sonMenuDO.getId(); - Long parentId = sonMenuDO.getParentId(); - - //调用 - MenuUpdateReqVO vo = randomPojo(MenuUpdateReqVO.class, o -> { - o.setId(sonId); - o.setParentId(parentId); - o.setType(MenuTypeEnum.MENU.getType()); - o.setStatus(randomCommonStatus()); - o.setName("pppppp"); //修改名字 - }); - menuService.updateMenu(vo); - - //断言 - // 校验记录的属性是否正确 - MenuDO ret = menuMapper.selectById(sonId); - assertPojoEquals(vo, ret); - // 校验调用 - verify(menuProducer).sendMenuRefreshMessage(); - } - - @Test - public void testUpdateMenu_sonIdNotExist() { - Long sonId = 99999L; - Long parentId = 10000L; - - //调用 - MenuUpdateReqVO vo = randomPojo(MenuUpdateReqVO.class, o -> { - o.setId(sonId); - o.setParentId(parentId); - o.setType(MenuTypeEnum.MENU.getType()); - o.setStatus(randomCommonStatus()); - }); - //断言 - assertServiceException(() -> menuService.updateMenu(vo), MENU_NOT_EXISTS); - } - - @Test - public void testDeleteMenu_success() { - MenuDO sonMenuDO = initParentAndSonMenuDO(); - Long sonId = sonMenuDO.getId(); - - // 调用 - menuService.deleteMenu(sonId); - - // 断言 - MenuDO menuDO = menuMapper.selectById(sonId); - assertNull(menuDO); - verify(permissionService).processMenuDeleted(sonId); - verify(menuProducer).sendMenuRefreshMessage(); - } - - @Test - public void testDeleteMenu_menuNotExist() { - Long sonId = 99999L; - - assertServiceException(() -> menuService.deleteMenu(sonId), MENU_NOT_EXISTS); - } - - @Test - public void testDeleteMenu_existChildren() { - MenuDO sonMenu = initParentAndSonMenuDO(); - Long parentId = sonMenu.getParentId(); - - assertServiceException(() -> menuService.deleteMenu(parentId), MENU_EXISTS_CHILDREN); - } - - @Test - public void testGetMenus() { - // mock 数据 - MenuDO menu100 = randomPojo(MenuDO.class, o -> o.setId(100L).setStatus(CommonStatusEnum.ENABLE.getStatus())); - menuMapper.insert(menu100); - MenuDO menu101 = randomPojo(MenuDO.class, o -> o.setId(101L).setStatus(CommonStatusEnum.DISABLE.getStatus())); - menuMapper.insert(menu101); - // 准备参数 - MenuListReqVO reqVO = new MenuListReqVO().setStatus(CommonStatusEnum.ENABLE.getStatus()); - - // 调用 - List result = menuService.getMenus(reqVO); - // 断言 - assertEquals(1, result.size()); - assertPojoEquals(menu100, result.get(0)); - } - - @Test - public void testTenantMenus() { - // mock 数据 - MenuDO menu100 = randomPojo(MenuDO.class, o -> o.setId(100L).setStatus(CommonStatusEnum.ENABLE.getStatus())); - menuMapper.insert(menu100); - MenuDO menu101 = randomPojo(MenuDO.class, o -> o.setId(101L).setStatus(CommonStatusEnum.DISABLE.getStatus())); - menuMapper.insert(menu101); - MenuDO menu102 = randomPojo(MenuDO.class, o -> o.setId(102L).setStatus(CommonStatusEnum.ENABLE.getStatus())); - menuMapper.insert(menu102); - // mock 过滤菜单 - // mock 账户额度充足 - Set menuIds = asSet(100L, 101L); - doNothing().when(tenantService).handleTenantMenu(argThat(handler -> { - handler.handle(menuIds); - return true; - })); - // 准备参数 - MenuListReqVO reqVO = new MenuListReqVO().setStatus(CommonStatusEnum.ENABLE.getStatus()); - - // 调用 - List result = menuService.getTenantMenus(reqVO); - // 断言 - assertEquals(1, result.size()); - assertPojoEquals(menu100, result.get(0)); - } - - @Test - public void testGetMenusReqVo_success() { - Map idMenuMap = new HashMap<>(); - // 用于验证可以模糊搜索名称包含"name",状态为1的menu - MenuDO menu = createMenuDO(MenuTypeEnum.MENU, "name2", 0L, 1); - menuMapper.insert(menu); - idMenuMap.put(menu.getId(), menu); - - menu = createMenuDO(MenuTypeEnum.MENU, "11name111", 0L, 1); - menuMapper.insert(menu); - idMenuMap.put(menu.getId(), menu); - - menu = createMenuDO(MenuTypeEnum.MENU, "name", 0L, 1); - menuMapper.insert(menu); - idMenuMap.put(menu.getId(), menu); - - // 以下是不符合搜索条件的的menu - menu = createMenuDO(MenuTypeEnum.MENU, "xxxxxx", 0L, 1); - menuMapper.insert(menu); - menu = createMenuDO(MenuTypeEnum.MENU, "name", 0L, 2); - menuMapper.insert(menu); - - // 调用 - MenuListReqVO reqVO = new MenuListReqVO(); - reqVO.setStatus(1); - reqVO.setName("name"); - List menuDOS = menuService.getMenus(reqVO); - - // 断言 - assertEquals(menuDOS.size(), idMenuMap.size()); - menuDOS.forEach(m -> assertPojoEquals(idMenuMap.get(m.getId()), m)); - } - - @Test - public void testListMenusFromCache_success() throws Exception { - Map mockCacheMap = new HashMap<>(); - // 获取代理对象 - MenuServiceImpl target = (MenuServiceImpl) SpringAopUtils.getTarget(menuService); - BeanUtil.setFieldValue(target, "menuCache", mockCacheMap); - - Map idMenuMap = new HashMap<>(); - // 用于验证搜索类型为MENU,状态为1的menu - MenuDO menuDO = createMenuDO(1L, MenuTypeEnum.MENU, "name", 0L, 1); - mockCacheMap.put(menuDO.getId(), menuDO); - idMenuMap.put(menuDO.getId(), menuDO); - - menuDO = createMenuDO(2L, MenuTypeEnum.MENU, "name", 0L, 1); - mockCacheMap.put(menuDO.getId(), menuDO); - idMenuMap.put(menuDO.getId(), menuDO); - - // 以下是不符合搜索条件的menu - menuDO = createMenuDO(3L, MenuTypeEnum.BUTTON, "name", 0L, 1); - mockCacheMap.put(menuDO.getId(), menuDO); - menuDO = createMenuDO(4L, MenuTypeEnum.MENU, "name", 0L, 2); - mockCacheMap.put(menuDO.getId(), menuDO); - - List menuDOS = menuService.getMenuListFromCache(Collections.singletonList(MenuTypeEnum.MENU.getType()), - Collections.singletonList(CommonStatusEnum.DISABLE.getStatus())); - assertEquals(menuDOS.size(), idMenuMap.size()); - menuDOS.forEach(m -> assertPojoEquals(idMenuMap.get(m.getId()), m)); - } - - @Test - public void testListMenusFromCache2_success() throws Exception { - Map mockCacheMap = new HashMap<>(); - // 获取代理对象 - MenuServiceImpl target = (MenuServiceImpl) SpringAopUtils.getTarget(menuService); - BeanUtil.setFieldValue(target, "menuCache", mockCacheMap); - - Map idMenuMap = new HashMap<>(); - // 验证搜索id为1, 类型为MENU, 状态为1 的menu - MenuDO menuDO = createMenuDO(1L, MenuTypeEnum.MENU, "name", 0L, 1); - mockCacheMap.put(menuDO.getId(), menuDO); - idMenuMap.put(menuDO.getId(), menuDO); - - // 以下是不符合搜索条件的menu - menuDO = createMenuDO(2L, MenuTypeEnum.MENU, "name", 0L, 1); - mockCacheMap.put(menuDO.getId(), menuDO); - menuDO = createMenuDO(3L, MenuTypeEnum.BUTTON, "name", 0L, 1); - mockCacheMap.put(menuDO.getId(), menuDO); - menuDO = createMenuDO(4L, MenuTypeEnum.MENU, "name", 0L, 2); - mockCacheMap.put(menuDO.getId(), menuDO); - - List menuDOS = menuService.getMenuListFromCache(Collections.singletonList(1L), - Collections.singletonList(MenuTypeEnum.MENU.getType()), Collections.singletonList(1)); - assertEquals(menuDOS.size(), idMenuMap.size()); - menuDOS.forEach(menu -> assertPojoEquals(idMenuMap.get(menu.getId()), menu)); - } - - @Test - public void testCheckParentResource_success() { - MenuDO menuDO = createMenuDO(MenuTypeEnum.MENU, "parent", 0L); - menuMapper.insert(menuDO); - Long parentId = menuDO.getId(); - - menuService.checkParentResource(parentId, null); - } - - @Test - public void testCheckParentResource_canNotSetSelfToBeParent() { - assertServiceException(() -> menuService.checkParentResource(1L, 1L), MENU_PARENT_ERROR); - } - - @Test - public void testCheckParentResource_parentNotExist() { - assertServiceException(() -> menuService.checkParentResource(randomLongId(), null), MENU_PARENT_NOT_EXISTS); - } - - @Test - public void testCheckParentResource_parentTypeError() { - MenuDO menuDO = createMenuDO(MenuTypeEnum.BUTTON, "parent", 0L); - menuMapper.insert(menuDO); - Long parentId = menuDO.getId(); - - assertServiceException(() -> menuService.checkParentResource(parentId, null), MENU_PARENT_NOT_DIR_OR_MENU); - } - - @Test - public void testCheckResource_success() { - MenuDO sonMenu = initParentAndSonMenuDO(); - Long parentId = sonMenu.getParentId(); - - Long otherSonMenuId = randomLongId(); - String otherSonMenuName = randomString(); - - menuService.checkResource(parentId, otherSonMenuName, otherSonMenuId); - } - - @Test - public void testCheckResource_sonMenuNameDuplicate(){ - MenuDO sonMenu=initParentAndSonMenuDO(); - Long parentId=sonMenu.getParentId(); - - Long otherSonMenuId=randomLongId(); - String otherSonMenuName=sonMenu.getName(); //相同名称 - - assertServiceException(() -> menuService.checkResource(parentId, otherSonMenuName, otherSonMenuId), MENU_NAME_DUPLICATE); - } - - /** - * 构造父子目录,返回子目录 - * - * @return - */ - private MenuDO initParentAndSonMenuDO() { - //构造父子目录 - MenuDO menuDO = createMenuDO(MenuTypeEnum.MENU, "parent", 0L); - menuMapper.insert(menuDO); - Long parentId = menuDO.getId(); - - MenuDO sonMenuDO = createMenuDO(MenuTypeEnum.MENU, "testSonName", parentId); - menuMapper.insert(sonMenuDO); - return sonMenuDO; - } - - private MenuDO createMenuDO(MenuTypeEnum typeEnum, String menuName, Long parentId) { - return createMenuDO(typeEnum, menuName, parentId, randomCommonStatus()); - } - - private MenuDO createMenuDO(MenuTypeEnum typeEnum, String menuName, Long parentId, Integer status) { - return createMenuDO(null, typeEnum, menuName, parentId, status); - } - - private MenuDO createMenuDO(Long id, MenuTypeEnum typeEnum, String menuName, Long parentId, Integer status) { - return randomPojo(MenuDO.class, o -> { - o.setId(id); - o.setParentId(parentId); - o.setType(typeEnum.getType()); - o.setStatus(status); - o.setName(menuName); - }); - } - -} diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/permission/PermissionServiceTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/permission/PermissionServiceTest.java index afc4c0ced..35b250208 100644 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/permission/PermissionServiceTest.java +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/permission/PermissionServiceTest.java @@ -106,7 +106,7 @@ public class PermissionServiceTest extends BaseDbUnitTest { Collection menusStatuses = asList(0, 1); // mock 方法 List roleList = singletonList(randomPojo(RoleDO.class, o -> o.setId(100L))); - when(roleService.getRolesFromCache(eq(roleIds))).thenReturn(roleList); + when(roleService.getRoleListFromCache(eq(roleIds))).thenReturn(roleList); when(roleService.hasAnySuperAdmin(same(roleList))).thenReturn(true); List menuList = randomPojoList(MenuDO.class); when(menuService.getMenuListFromCache(eq(menuTypes), eq(menusStatuses))).thenReturn(menuList); @@ -163,7 +163,7 @@ public class PermissionServiceTest extends BaseDbUnitTest { // mock 方法 when(roleService.hasAnySuperAdmin(eq(singleton(100L)))).thenReturn(true); List menuList = singletonList(randomPojo(MenuDO.class).setId(1L)); - when(menuService.getMenus()).thenReturn(menuList); + when(menuService.getMenuList()).thenReturn(menuList); // 调用 Set menuIds = permissionService.getRoleMenuIds(roleId); @@ -419,7 +419,7 @@ public class PermissionServiceTest extends BaseDbUnitTest { .setStatus(CommonStatusEnum.ENABLE.getStatus())); when(roleService.getRoleFromCache(eq(100L))).thenReturn(role); // mock 其它方法 - when(roleService.getRolesFromCache(eq(asSet(100L)))).thenReturn(singletonList(role)); + when(roleService.getRoleListFromCache(eq(asSet(100L)))).thenReturn(singletonList(role)); // 调用 boolean has = permissionService.hasAnyRoles(userId, roles); @@ -436,7 +436,7 @@ public class PermissionServiceTest extends BaseDbUnitTest { // mock 获得用户的角色 RoleDO roleDO = randomPojo(RoleDO.class, o -> o.setDataScope(DataScopeEnum.ALL.getScope()) .setStatus(CommonStatusEnum.ENABLE.getStatus())); - when(roleService.getRolesFromCache(eq(singleton(2L)))).thenReturn(singletonList(roleDO)); + when(roleService.getRoleListFromCache(eq(singleton(2L)))).thenReturn(singletonList(roleDO)); when(roleService.getRoleFromCache(eq(2L))).thenReturn(roleDO); // 调用 @@ -456,7 +456,7 @@ public class PermissionServiceTest extends BaseDbUnitTest { // mock 获得用户的角色 RoleDO roleDO = randomPojo(RoleDO.class, o -> o.setDataScope(DataScopeEnum.DEPT_CUSTOM.getScope()) .setStatus(CommonStatusEnum.ENABLE.getStatus())); - when(roleService.getRolesFromCache(eq(singleton(2L)))).thenReturn(singletonList(roleDO)); + when(roleService.getRoleListFromCache(eq(singleton(2L)))).thenReturn(singletonList(roleDO)); when(roleService.getRoleFromCache(eq(2L))).thenReturn(roleDO); // mock 部门的返回 when(userService.getUser(eq(1L))).thenReturn(new AdminUserDO().setDeptId(3L), null, null); // 最后返回 null 的目的,看看会不会重复调用 @@ -480,7 +480,7 @@ public class PermissionServiceTest extends BaseDbUnitTest { // mock 获得用户的角色 RoleDO roleDO = randomPojo(RoleDO.class, o -> o.setDataScope(DataScopeEnum.DEPT_ONLY.getScope()) .setStatus(CommonStatusEnum.ENABLE.getStatus())); - when(roleService.getRolesFromCache(eq(singleton(2L)))).thenReturn(singletonList(roleDO)); + when(roleService.getRoleListFromCache(eq(singleton(2L)))).thenReturn(singletonList(roleDO)); when(roleService.getRoleFromCache(eq(2L))).thenReturn(roleDO); // mock 部门的返回 when(userService.getUser(eq(1L))).thenReturn(new AdminUserDO().setDeptId(3L), null, null); // 最后返回 null 的目的,看看会不会重复调用 @@ -503,13 +503,13 @@ public class PermissionServiceTest extends BaseDbUnitTest { // mock 获得用户的角色 RoleDO roleDO = randomPojo(RoleDO.class, o -> o.setDataScope(DataScopeEnum.DEPT_AND_CHILD.getScope()) .setStatus(CommonStatusEnum.ENABLE.getStatus())); - when(roleService.getRolesFromCache(eq(singleton(2L)))).thenReturn(singletonList(roleDO)); + when(roleService.getRoleListFromCache(eq(singleton(2L)))).thenReturn(singletonList(roleDO)); when(roleService.getRoleFromCache(eq(2L))).thenReturn(roleDO); // mock 部门的返回 when(userService.getUser(eq(1L))).thenReturn(new AdminUserDO().setDeptId(3L), null, null); // 最后返回 null 的目的,看看会不会重复调用 // mock 方法(部门) DeptDO deptDO = randomPojo(DeptDO.class); - when(deptService.getDeptsByParentIdFromCache(eq(3L), eq(true))) + when(deptService.getDeptListByParentIdFromCache(eq(3L), eq(true))) .thenReturn(singletonList(deptDO)); // 调用 @@ -531,7 +531,7 @@ public class PermissionServiceTest extends BaseDbUnitTest { // mock 获得用户的角色 RoleDO roleDO = randomPojo(RoleDO.class, o -> o.setDataScope(DataScopeEnum.SELF.getScope()) .setStatus(CommonStatusEnum.ENABLE.getStatus())); - when(roleService.getRolesFromCache(eq(singleton(2L)))).thenReturn(singletonList(roleDO)); + when(roleService.getRoleListFromCache(eq(singleton(2L)))).thenReturn(singletonList(roleDO)); when(roleService.getRoleFromCache(eq(2L))).thenReturn(roleDO); // 调用 diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/permission/RoleServiceImplTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/permission/RoleServiceImplTest.java new file mode 100644 index 000000000..a114556c4 --- /dev/null +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/permission/RoleServiceImplTest.java @@ -0,0 +1,399 @@ +package cn.iocoder.yudao.module.system.service.permission; + +import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum; +import cn.iocoder.yudao.framework.common.pojo.PageResult; +import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; +import cn.iocoder.yudao.module.system.controller.admin.permission.vo.role.RoleCreateReqVO; +import cn.iocoder.yudao.module.system.controller.admin.permission.vo.role.RoleExportReqVO; +import cn.iocoder.yudao.module.system.controller.admin.permission.vo.role.RolePageReqVO; +import cn.iocoder.yudao.module.system.controller.admin.permission.vo.role.RoleUpdateReqVO; +import cn.iocoder.yudao.module.system.dal.dataobject.permission.RoleDO; +import cn.iocoder.yudao.module.system.dal.mysql.permission.RoleMapper; +import cn.iocoder.yudao.module.system.enums.permission.DataScopeEnum; +import cn.iocoder.yudao.module.system.enums.permission.RoleTypeEnum; +import cn.iocoder.yudao.module.system.mq.producer.permission.RoleProducer; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.context.annotation.Import; + +import javax.annotation.Resource; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static cn.hutool.core.util.RandomUtil.randomEle; +import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildBetweenTime; +import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildTime; +import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId; +import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; +import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; +import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; +import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*; +import static java.util.Collections.singleton; +import static java.util.Collections.singletonList; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.verify; + +@Import(RoleServiceImpl.class) +public class RoleServiceImplTest extends BaseDbUnitTest { + + @Resource + private RoleServiceImpl roleService; + + @Resource + private RoleMapper roleMapper; + + @MockBean + private PermissionService permissionService; + @MockBean + private RoleProducer roleProducer; + + @Test + public void testInitLocalCache() { + RoleDO roleDO1 = randomPojo(RoleDO.class); + roleMapper.insert(roleDO1); + RoleDO roleDO2 = randomPojo(RoleDO.class); + roleMapper.insert(roleDO2); + + // 调用 + roleService.initLocalCache(); + // 断言 roleCache 缓存 + Map roleCache = roleService.getRoleCache(); + assertPojoEquals(roleDO1, roleCache.get(roleDO1.getId())); + assertPojoEquals(roleDO2, roleCache.get(roleDO2.getId())); + } + + @Test + public void testCreateRole_success() { + // 准备参数 + RoleCreateReqVO reqVO = randomPojo(RoleCreateReqVO.class); + + // 调用 + Long roleId = roleService.createRole(reqVO, null); + // 断言 + RoleDO roleDO = roleMapper.selectById(roleId); + assertPojoEquals(reqVO, roleDO); + assertEquals(RoleTypeEnum.CUSTOM.getType(), roleDO.getType()); + assertEquals(CommonStatusEnum.ENABLE.getStatus(), roleDO.getStatus()); + assertEquals(DataScopeEnum.ALL.getScope(), roleDO.getDataScope()); + // verify 发送刷新消息 + verify(roleProducer).sendRoleRefreshMessage(); + } + + @Test + public void testUpdateRole_success() { + // mock 数据 + RoleDO roleDO = randomPojo(RoleDO.class, o -> o.setType(RoleTypeEnum.CUSTOM.getType())); + roleMapper.insert(roleDO); + // 准备参数 + Long id = roleDO.getId(); + RoleUpdateReqVO reqVO = randomPojo(RoleUpdateReqVO.class, o -> o.setId(id)); + + // 调用 + roleService.updateRole(reqVO); + // 断言 + RoleDO newRoleDO = roleMapper.selectById(id); + assertPojoEquals(reqVO, newRoleDO); + // verify 发送刷新消息 + verify(roleProducer).sendRoleRefreshMessage(); + } + + @Test + public void testUpdateRoleStatus_success() { + // mock 数据 + RoleDO roleDO = randomPojo(RoleDO.class, o -> o.setStatus(CommonStatusEnum.ENABLE.getStatus()) + .setType(RoleTypeEnum.CUSTOM.getType())); + roleMapper.insert(roleDO); + + // 准备参数 + Long roleId = roleDO.getId(); + + // 调用 + roleService.updateRoleStatus(roleId, CommonStatusEnum.DISABLE.getStatus()); + // 断言 + RoleDO dbRoleDO = roleMapper.selectById(roleId); + assertEquals(CommonStatusEnum.DISABLE.getStatus(), dbRoleDO.getStatus()); + // verify 发送刷新消息 + verify(roleProducer).sendRoleRefreshMessage(); + } + + @Test + public void testUpdateRoleDataScope_success() { + // mock 数据 + RoleDO roleDO = randomPojo(RoleDO.class, o -> o.setType(RoleTypeEnum.CUSTOM.getType())); + roleMapper.insert(roleDO); + // 准备参数 + Long id = roleDO.getId(); + Integer dataScope = randomEle(DataScopeEnum.values()).getScope(); + Set dataScopeRoleIds = randomSet(Long.class); + + // 调用 + roleService.updateRoleDataScope(id, dataScope, dataScopeRoleIds); + // 断言 + RoleDO dbRoleDO = roleMapper.selectById(id); + assertEquals(dataScope, dbRoleDO.getDataScope()); + assertEquals(dataScopeRoleIds, dbRoleDO.getDataScopeDeptIds()); + // verify 发送刷新消息 + verify(roleProducer).sendRoleRefreshMessage(); + } + + @Test + public void testDeleteRole_success() { + // mock 数据 + RoleDO roleDO = randomPojo(RoleDO.class, o -> o.setType(RoleTypeEnum.CUSTOM.getType())); + roleMapper.insert(roleDO); + // 参数准备 + Long id = roleDO.getId(); + + // 调用 + roleService.deleteRole(id); + // 断言 + assertNull(roleMapper.selectById(id)); + // verify 删除相关数据 + verify(permissionService).processRoleDeleted(id); + // verify 发送刷新消息 + verify(roleProducer).sendRoleRefreshMessage(); + } + + @Test + public void testGetRoleFromCache() { + // mock 数据(缓存) + RoleDO roleDO = randomPojo(RoleDO.class); + roleMapper.insert(roleDO); + roleService.initLocalCache(); + // 参数准备 + Long id = roleDO.getId(); + + // 调用 + RoleDO dbRoleDO = roleService.getRoleFromCache(id); + // 断言 + assertPojoEquals(roleDO, dbRoleDO); + } + + @Test + public void testGetRole() { + // mock 数据 + RoleDO roleDO = randomPojo(RoleDO.class); + roleMapper.insert(roleDO); + // 参数准备 + Long id = roleDO.getId(); + + // 调用 + RoleDO dbRoleDO = roleService.getRole(id); + // 断言 + assertPojoEquals(roleDO, dbRoleDO); + } + + @Test + public void testGetRoleListByStatus_statusNotEmpty() { + // mock 数据 + RoleDO dbRole = randomPojo(RoleDO.class, o -> o.setStatus(CommonStatusEnum.ENABLE.getStatus())); + roleMapper.insert(dbRole); + // 测试 status 不匹配 + roleMapper.insert(cloneIgnoreId(dbRole, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus()))); + + // 调用 + List list = roleService.getRoleListByStatus(singleton(CommonStatusEnum.ENABLE.getStatus())); + // 断言 + assertEquals(1, list.size()); + assertPojoEquals(dbRole, list.get(0)); + } + + @Test + public void testGetRoleListByStatus_statusEmpty() { + // mock 数据 + RoleDO dbRole01 = randomPojo(RoleDO.class, o -> o.setStatus(CommonStatusEnum.ENABLE.getStatus())); + roleMapper.insert(dbRole01); + RoleDO dbRole02 = randomPojo(RoleDO.class, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus())); + roleMapper.insert(dbRole02); + + // 调用 + List list = roleService.getRoleListByStatus(null); + // 断言 + assertEquals(2, list.size()); + assertPojoEquals(dbRole01, list.get(0)); + assertPojoEquals(dbRole02, list.get(1)); + } + + @Test + public void testGetRoleListFromCache() { + // mock 数据 + RoleDO dbRole = randomPojo(RoleDO.class, o -> o.setStatus(CommonStatusEnum.ENABLE.getStatus())); + roleMapper.insert(dbRole); + // 测试 id 不匹配 + roleMapper.insert(cloneIgnoreId(dbRole, o -> {})); + roleService.initLocalCache(); + // 准备参数 + Collection ids = singleton(dbRole.getId()); + + // 调用 + List list = roleService.getRoleListFromCache(ids); + // 断言 + assertEquals(1, list.size()); + assertPojoEquals(dbRole, list.get(0)); + } + + @Test + public void testGetRoleList() { + // mock 数据 + RoleDO dbRole = randomPojo(RoleDO.class, o -> { // 等会查询到 + o.setName("土豆"); + o.setCode("tudou"); + o.setStatus(CommonStatusEnum.ENABLE.getStatus()); + o.setCreateTime(buildTime(2022, 2, 8)); + }); + roleMapper.insert(dbRole); + // 测试 name 不匹配 + roleMapper.insert(cloneIgnoreId(dbRole, o -> o.setName("红薯"))); + // 测试 code 不匹配 + roleMapper.insert(cloneIgnoreId(dbRole, o -> o.setCode("hong"))); + // 测试 createTime 不匹配 + roleMapper.insert(cloneIgnoreId(dbRole, o -> o.setCreateTime(buildTime(2022, 2, 16)))); + // 准备参数 + RoleExportReqVO reqVO = new RoleExportReqVO(); + reqVO.setName("土豆"); + reqVO.setCode("tu"); + reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus()); + reqVO.setCreateTime(buildBetweenTime(2022, 2, 1, 2022, 2, 12)); + + // 调用 + List list = roleService.getRoleList(reqVO); + // 断言 + assertEquals(1, list.size()); + assertPojoEquals(dbRole, list.get(0)); + } + + @Test + public void testGetRolePage() { + // mock 数据 + RoleDO dbRole = randomPojo(RoleDO.class, o -> { // 等会查询到 + o.setName("土豆"); + o.setCode("tudou"); + o.setStatus(CommonStatusEnum.ENABLE.getStatus()); + o.setCreateTime(buildTime(2022, 2, 8)); + }); + roleMapper.insert(dbRole); + // 测试 name 不匹配 + roleMapper.insert(cloneIgnoreId(dbRole, o -> o.setName("红薯"))); + // 测试 code 不匹配 + roleMapper.insert(cloneIgnoreId(dbRole, o -> o.setCode("hong"))); + // 测试 createTime 不匹配 + roleMapper.insert(cloneIgnoreId(dbRole, o -> o.setCreateTime(buildTime(2022, 2, 16)))); + // 准备参数 + RolePageReqVO reqVO = new RolePageReqVO(); + reqVO.setName("土豆"); + reqVO.setCode("tu"); + reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus()); + reqVO.setCreateTime(buildBetweenTime(2022, 2, 1, 2022, 2, 12)); + + // 调用 + PageResult pageResult = roleService.getRolePage(reqVO); + // 断言 + assertEquals(1, pageResult.getTotal()); + assertEquals(1, pageResult.getList().size()); + assertPojoEquals(dbRole, pageResult.getList().get(0)); + } + + @Test + public void testHasAnySuperAdmin() { + // 是超级 + assertTrue(roleService.hasAnySuperAdmin(singletonList(randomPojo(RoleDO.class, + o -> o.setCode("super_admin"))))); + // 非超级 + assertFalse(roleService.hasAnySuperAdmin(singletonList(randomPojo(RoleDO.class, + o -> o.setCode("tenant_admin"))))); + } + + @Test + public void testValidateRoleDuplicate_success() { + // 调用,不会抛异常 + roleService.validateRoleDuplicate(randomString(), randomString(), null); + } + + @Test + public void testValidateRoleDuplicate_nameDuplicate() { + // mock 数据 + RoleDO roleDO = randomPojo(RoleDO.class, o -> o.setName("role_name")); + roleMapper.insert(roleDO); + // 准备参数 + String name = "role_name"; + + // 调用,并断言异常 + assertServiceException(() -> roleService.validateRoleDuplicate(name, randomString(), null), + ROLE_NAME_DUPLICATE, name); + } + + @Test + public void testValidateRoleDuplicate_codeDuplicate() { + // mock 数据 + RoleDO roleDO = randomPojo(RoleDO.class, o -> o.setCode("code")); + roleMapper.insert(roleDO); + // 准备参数 + String code = "code"; + + // 调用,并断言异常 + assertServiceException(() -> roleService.validateRoleDuplicate(randomString(), code, null), + ROLE_CODE_DUPLICATE, code); + } + + @Test + public void testValidateUpdateRole_success() { + RoleDO roleDO = randomPojo(RoleDO.class); + roleMapper.insert(roleDO); + // 准备参数 + Long id = roleDO.getId(); + + // 调用,无异常 + roleService.validateRoleForUpdate(id); + } + + @Test + public void testValidateUpdateRole_roleIdNotExist() { + assertServiceException(() -> roleService.validateRoleForUpdate(randomLongId()), ROLE_NOT_EXISTS); + } + + @Test + public void testValidateUpdateRole_systemRoleCanNotBeUpdate() { + RoleDO roleDO = randomPojo(RoleDO.class, o -> o.setType(RoleTypeEnum.SYSTEM.getType())); + roleMapper.insert(roleDO); + // 准备参数 + Long id = roleDO.getId(); + + assertServiceException(() -> roleService.validateRoleForUpdate(id), + ROLE_CAN_NOT_UPDATE_SYSTEM_TYPE_ROLE); + } + + @Test + public void testValidateRoleList_success() { + // mock 数据 + RoleDO roleDO = randomPojo(RoleDO.class, o -> o.setStatus(CommonStatusEnum.ENABLE.getStatus())); + roleMapper.insert(roleDO); + // 准备参数 + List ids = singletonList(roleDO.getId()); + + // 调用,无需断言 + roleService.validateRoleList(ids); + } + + @Test + public void testValidateRoleList_notFound() { + // 准备参数 + List ids = singletonList(randomLongId()); + + // 调用, 并断言异常 + assertServiceException(() -> roleService.validateRoleList(ids), ROLE_NOT_EXISTS); + } + + @Test + public void testValidateRoleList_notEnable() { + // mock 数据 + RoleDO RoleDO = randomPojo(RoleDO.class, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus())); + roleMapper.insert(RoleDO); + // 准备参数 + List ids = singletonList(RoleDO.getId()); + + // 调用, 并断言异常 + assertServiceException(() -> roleService.validateRoleList(ids), ROLE_IS_DISABLE, RoleDO.getName()); + } +} diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/permission/RoleServiceTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/permission/RoleServiceTest.java deleted file mode 100644 index a0d6c79a0..000000000 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/permission/RoleServiceTest.java +++ /dev/null @@ -1,301 +0,0 @@ -package cn.iocoder.yudao.module.system.service.permission; - -import cn.hutool.core.util.RandomUtil; -import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum; -import cn.iocoder.yudao.framework.common.pojo.PageResult; -import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; -import cn.iocoder.yudao.module.system.controller.admin.permission.vo.role.RoleCreateReqVO; -import cn.iocoder.yudao.module.system.controller.admin.permission.vo.role.RoleExportReqVO; -import cn.iocoder.yudao.module.system.controller.admin.permission.vo.role.RolePageReqVO; -import cn.iocoder.yudao.module.system.controller.admin.permission.vo.role.RoleUpdateReqVO; -import cn.iocoder.yudao.module.system.dal.dataobject.permission.RoleDO; -import cn.iocoder.yudao.module.system.dal.mysql.permission.RoleMapper; -import cn.iocoder.yudao.module.system.enums.permission.DataScopeEnum; -import cn.iocoder.yudao.module.system.enums.permission.RoleTypeEnum; -import cn.iocoder.yudao.module.system.mq.producer.permission.RoleProducer; -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.context.annotation.Import; - -import javax.annotation.Resource; -import java.time.LocalDateTime; -import java.util.*; - -import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildTime; -import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId; -import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; -import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; -import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; -import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.verify; - -// TODO @芋艿:单测的代码质量可以提升下 -@Import(RoleServiceImpl.class) -public class RoleServiceTest extends BaseDbUnitTest { - - @Resource - private RoleServiceImpl roleService; - - @Resource - private RoleMapper roleMapper; - - @MockBean - private PermissionService permissionService; - @MockBean - private RoleProducer roleProducer; - - @Test - public void testInitLocalCache() { - RoleDO roleDO1 = randomRole(); - roleMapper.insert(roleDO1); - RoleDO roleDO2 = randomRole(); - roleMapper.insert(roleDO2); - - // 调用 - roleService.initLocalCache(); - // 断言 roleCache 缓存 - Map roleCache = roleService.getRoleCache(); - assertPojoEquals(roleDO1, roleCache.get(roleDO1.getId())); - assertPojoEquals(roleDO2, roleCache.get(roleDO2.getId())); - } - - @Test - public void testCreateRole_success() { - // 准备参数 - RoleCreateReqVO reqVO = randomPojo(RoleCreateReqVO.class); - - // 调用 - Long roleId = roleService.createRole(reqVO, null); - // 断言 - assertNotNull(roleId); - RoleDO roleDO = roleMapper.selectById(roleId); - assertPojoEquals(reqVO, roleDO); - assertEquals(RoleTypeEnum.CUSTOM.getType(), roleDO.getType()); - assertEquals(CommonStatusEnum.ENABLE.getStatus(), roleDO.getStatus()); - assertEquals(DataScopeEnum.ALL.getScope(), roleDO.getDataScope()); - // verify 发送刷新消息 - verify(roleProducer).sendRoleRefreshMessage(); - } - - @Test - public void testUpdateRole_success() { - // mock 数据 - RoleDO roleDO = createRoleDO("role_name", RoleTypeEnum.CUSTOM, DataScopeEnum.ALL); - roleMapper.insert(roleDO); - Long roleId = roleDO.getId(); - - //调用 - RoleUpdateReqVO reqVO = randomPojo(RoleUpdateReqVO.class, o -> { - o.setId(roleId); - o.setCode("role_code"); - o.setName("update_name"); - o.setSort(999); - }); - roleService.updateRole(reqVO); - - //断言 - RoleDO newRoleDO = roleMapper.selectById(roleId); - assertPojoEquals(reqVO, newRoleDO); - - verify(roleProducer).sendRoleRefreshMessage(); - } - - @Test - public void testUpdateRoleStatus_success() { - RoleDO roleDO = createRoleDO("role_name", RoleTypeEnum.CUSTOM, DataScopeEnum.ALL, CommonStatusEnum.ENABLE.getStatus()); - roleMapper.insert(roleDO); - Long roleId = roleDO.getId(); - - //调用 - roleService.updateRoleStatus(roleId, CommonStatusEnum.DISABLE.getStatus()); - - //断言 - RoleDO newRoleDO = roleMapper.selectById(roleId); - assertEquals(CommonStatusEnum.DISABLE.getStatus(), newRoleDO.getStatus()); - - verify(roleProducer).sendRoleRefreshMessage(); - } - - @Test - public void testUpdateRoleDataScope_success() { - RoleDO roleDO = createRoleDO("role_name", RoleTypeEnum.CUSTOM, DataScopeEnum.ALL); - roleMapper.insert(roleDO); - Long roleId = roleDO.getId(); - - //调用 - Set deptIdSet = new HashSet<>(Arrays.asList(1L, 2L, 3L, 4L, 5L)); - roleService.updateRoleDataScope(roleId, DataScopeEnum.DEPT_CUSTOM.getScope(), deptIdSet); - - //断言 - RoleDO newRoleDO = roleMapper.selectById(roleId); - assertEquals(DataScopeEnum.DEPT_CUSTOM.getScope(), newRoleDO.getDataScope()); - - Set newDeptIdSet = newRoleDO.getDataScopeDeptIds(); - assertEquals(deptIdSet.size(), newDeptIdSet.size()); - deptIdSet.stream().forEach(d -> assertTrue(newDeptIdSet.contains(d))); - - verify(roleProducer).sendRoleRefreshMessage(); - } - - @Test - public void testDeleteRole_success() { - RoleDO roleDO = createRoleDO("role_name", RoleTypeEnum.CUSTOM, DataScopeEnum.ALL); - roleMapper.insert(roleDO); - Long roleId = roleDO.getId(); - - //调用 - roleService.deleteRole(roleId); - - //断言 - RoleDO newRoleDO = roleMapper.selectById(roleId); - assertNull(newRoleDO); - - verify(roleProducer).sendRoleRefreshMessage(); - } - - @Test - public void testGetRoles() { - // mock 数据 - RoleDO dbRole = randomPojo(RoleDO.class, o -> { // 等会查询到 - o.setName("土豆"); - o.setCode("tudou"); - o.setStatus(CommonStatusEnum.ENABLE.getStatus()); - o.setCreateTime(buildTime(2022, 2, 8)); - }); - roleMapper.insert(dbRole); - // 测试 name 不匹配 - roleMapper.insert(cloneIgnoreId(dbRole, o -> o.setName("红薯"))); - // 测试 code 不匹配 - roleMapper.insert(cloneIgnoreId(dbRole, o -> o.setCode("hong"))); - // 测试 createTime 不匹配 - roleMapper.insert(cloneIgnoreId(dbRole, o -> o.setCreateTime(buildTime(2022, 2, 16)))); - // 准备参数 - RoleExportReqVO reqVO = new RoleExportReqVO(); - reqVO.setName("土豆"); - reqVO.setCode("tu"); - reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus()); - reqVO.setCreateTime((new LocalDateTime[]{buildTime(2022, 2, 1),buildTime(2022, 2, 12)})); - - // 调用 - List list = roleService.getRoleList(reqVO); - // 断言 - assertEquals(1, list.size()); - assertPojoEquals(dbRole, list.get(0)); - } - - @Test - public void testGetRolePage() { - // mock 数据 - RoleDO dbRole = randomPojo(RoleDO.class, o -> { // 等会查询到 - o.setName("土豆"); - o.setCode("tudou"); - o.setStatus(CommonStatusEnum.ENABLE.getStatus()); - o.setCreateTime(buildTime(2022, 2, 8)); - }); - roleMapper.insert(dbRole); - // 测试 name 不匹配 - roleMapper.insert(cloneIgnoreId(dbRole, o -> o.setName("红薯"))); - // 测试 code 不匹配 - roleMapper.insert(cloneIgnoreId(dbRole, o -> o.setCode("hong"))); - // 测试 createTime 不匹配 - roleMapper.insert(cloneIgnoreId(dbRole, o -> o.setCreateTime(buildTime(2022, 2, 16)))); - // 准备参数 - RolePageReqVO reqVO = new RolePageReqVO(); - reqVO.setName("土豆"); - reqVO.setCode("tu"); - reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus()); - reqVO.setCreateTime((new LocalDateTime[]{buildTime(2022, 2, 1),buildTime(2022, 2, 12)})); - - // 调用 - PageResult pageResult = roleService.getRolePage(reqVO); - // 断言 - assertEquals(1, pageResult.getTotal()); - assertEquals(1, pageResult.getList().size()); - assertPojoEquals(dbRole, pageResult.getList().get(0)); - } - - @Test - public void testCheckDuplicateRole_success() { - roleService.checkDuplicateRole(randomString(), randomString(), null); - } - - @Test - public void testCheckDuplicateRole_nameDuplicate() { - RoleDO roleDO = createRoleDO("role_name", RoleTypeEnum.CUSTOM, DataScopeEnum.ALL); - roleMapper.insert(roleDO); - - String duplicateName = "role_name"; - - assertServiceException(() -> roleService.checkDuplicateRole(duplicateName, randomString(), null), ROLE_NAME_DUPLICATE, duplicateName); - } - - @Test - public void testCheckDuplicateRole_codeDuplicate() { - RoleDO roleDO = randomPojo(RoleDO.class, o -> { - o.setName("role_999"); - o.setCode("code"); - o.setType(RoleTypeEnum.CUSTOM.getType()); - o.setStatus(1); - o.setDataScope(DataScopeEnum.ALL.getScope()); - }); - roleMapper.insert(roleDO); - - String randomName = randomString(); - String duplicateCode = "code"; - - assertServiceException(() -> roleService.checkDuplicateRole(randomName, duplicateCode, null), ROLE_CODE_DUPLICATE, duplicateCode); - } - - @Test - public void testCheckUpdateRole_success() { - RoleDO roleDO = createRoleDO("role_name", RoleTypeEnum.CUSTOM, DataScopeEnum.ALL); - roleMapper.insert(roleDO); - Long roleId = roleDO.getId(); - - roleService.checkUpdateRole(roleId); - } - - @Test - public void testCheckUpdateRole_roleIdNotExist() { - assertServiceException(() -> roleService.checkUpdateRole(randomLongId()), ROLE_NOT_EXISTS); - } - - @Test - public void testCheckUpdateRole_systemRoleCanNotBeUpdate() { - RoleDO roleDO = createRoleDO("role_name", RoleTypeEnum.SYSTEM, DataScopeEnum.ALL); - roleMapper.insert(roleDO); - Long roleId = roleDO.getId(); - - assertServiceException(() -> roleService.checkUpdateRole(roleId), ROLE_CAN_NOT_UPDATE_SYSTEM_TYPE_ROLE); - } - - private RoleDO createRoleDO(String name, RoleTypeEnum typeEnum, DataScopeEnum scopeEnum, Integer status) { - return createRoleDO( name, typeEnum, scopeEnum, status, randomString()); - } - - private RoleDO createRoleDO(String name, RoleTypeEnum typeEnum, DataScopeEnum scopeEnum, Integer status, String code) { - return createRoleDO(null, name, typeEnum, scopeEnum, status, code); - } - - private RoleDO createRoleDO(String name, RoleTypeEnum typeEnum, DataScopeEnum scopeEnum) { - return createRoleDO(null, name, typeEnum, scopeEnum, randomCommonStatus(), randomString()); - } - - private RoleDO createRoleDO(Long id, String name, RoleTypeEnum typeEnum, DataScopeEnum scopeEnum, Integer status, String code) { - return randomPojo(RoleDO.class, o -> { - o.setId(id); - o.setName(name); - o.setType(typeEnum.getType()); - o.setStatus(status); - o.setDataScope(scopeEnum.getScope()); - o.setCode(code); - }); - } - - private RoleDO randomRole() { - return randomPojo(RoleDO.class, - o -> o.setDataScope(RandomUtil.randomEle(DataScopeEnum.values()).getScope())); - } - -} diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sensitiveword/SensitiveWordServiceImplTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sensitiveword/SensitiveWordServiceImplTest.java index 273e74b4a..141236987 100644 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sensitiveword/SensitiveWordServiceImplTest.java +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sensitiveword/SensitiveWordServiceImplTest.java @@ -16,13 +16,12 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import javax.annotation.Resource; -import java.time.LocalDateTime; import java.util.Arrays; import java.util.List; +import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildBetweenTime; import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildTime; import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId; -import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.max; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomLongId; @@ -61,7 +60,7 @@ public class SensitiveWordServiceImplTest extends BaseDbUnitTest { // 调用 sensitiveWordService.initLocalCache(); // 断言 sensitiveWordTagsCache 缓存 - assertEquals(SetUtils.asSet("论坛", "蔬菜"), sensitiveWordService.getSensitiveWordTags()); + assertEquals(SetUtils.asSet("论坛", "蔬菜"), sensitiveWordService.getSensitiveWordTagSet()); // 断言 tagSensitiveWordTries 缓存 assertNotNull(sensitiveWordService.getDefaultSensitiveWordTrie()); assertEquals(2, sensitiveWordService.getTagSensitiveWordTries().size()); @@ -135,6 +134,36 @@ public class SensitiveWordServiceImplTest extends BaseDbUnitTest { assertServiceException(() -> sensitiveWordService.deleteSensitiveWord(id), SENSITIVE_WORD_NOT_EXISTS); } + @Test + public void testGetSensitiveWord() { + // mock 数据 + SensitiveWordDO sensitiveWord = randomPojo(SensitiveWordDO.class); + sensitiveWordMapper.insert(sensitiveWord); + // 准备参数 + Long id = sensitiveWord.getId(); + + // 调用 + SensitiveWordDO dbSensitiveWord = sensitiveWordService.getSensitiveWord(id); + // 断言 + assertPojoEquals(sensitiveWord, dbSensitiveWord); + } + + @Test + public void testGetSensitiveWordList() { + // mock 数据 + SensitiveWordDO sensitiveWord01 = randomPojo(SensitiveWordDO.class); + sensitiveWordMapper.insert(sensitiveWord01); + SensitiveWordDO sensitiveWord02 = randomPojo(SensitiveWordDO.class); + sensitiveWordMapper.insert(sensitiveWord02); + + // 调用 + List list = sensitiveWordService.getSensitiveWordList(); + // 断言 + assertEquals(2, list.size()); + assertEquals(sensitiveWord01, list.get(0)); + assertEquals(sensitiveWord02, list.get(1)); + } + @Test public void testGetSensitiveWordPage() { // mock 数据 @@ -156,7 +185,7 @@ public class SensitiveWordServiceImplTest extends BaseDbUnitTest { reqVO.setName("笨"); reqVO.setTag("论坛"); reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus()); - reqVO.setCreateTime((new LocalDateTime[]{buildTime(2022, 2, 1),buildTime(2022, 2, 12)})); + reqVO.setCreateTime(buildBetweenTime(2022, 2, 1, 2022, 2, 12)); // 调用 PageResult pageResult = sensitiveWordService.getSensitiveWordPage(reqVO); @@ -167,7 +196,7 @@ public class SensitiveWordServiceImplTest extends BaseDbUnitTest { } @Test - public void testGetSensitiveWordList() { + public void testGetSensitiveWordList_export() { // mock 数据 SensitiveWordDO dbSensitiveWord = randomPojo(SensitiveWordDO.class, o -> { // 等会查询到 o.setName("笨蛋"); @@ -187,7 +216,7 @@ public class SensitiveWordServiceImplTest extends BaseDbUnitTest { reqVO.setName("笨"); reqVO.setTag("论坛"); reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus()); - reqVO.setCreateTime((new LocalDateTime[]{buildTime(2022, 2, 1),buildTime(2022, 2, 12)})); + reqVO.setCreateTime(buildBetweenTime(2022, 2, 1, 2022, 2, 12)); // 调用 List list = sensitiveWordService.getSensitiveWordList(reqVO); diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sms/SmsChannelServiceTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sms/SmsChannelServiceTest.java index 4fe433d90..dabb9aa75 100644 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sms/SmsChannelServiceTest.java +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sms/SmsChannelServiceTest.java @@ -2,8 +2,6 @@ package cn.iocoder.yudao.module.system.service.sms; import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum; import cn.iocoder.yudao.framework.common.pojo.PageResult; -import cn.iocoder.yudao.framework.common.util.collection.ArrayUtils; -import cn.iocoder.yudao.framework.common.util.object.ObjectUtils; import cn.iocoder.yudao.framework.sms.core.client.SmsClientFactory; import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import cn.iocoder.yudao.module.system.controller.admin.sms.vo.channel.SmsChannelCreateReqVO; @@ -17,11 +15,12 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import javax.annotation.Resource; -import java.time.LocalDateTime; -import java.util.function.Consumer; -import static cn.hutool.core.util.RandomUtil.randomEle; +import java.util.List; + +import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildBetweenTime; import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildTime; +import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.*; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.SMS_CHANNEL_HAS_CHILDREN; @@ -49,9 +48,9 @@ public class SmsChannelServiceTest extends BaseDbUnitTest { @Test public void testInitLocalCache_success() { // mock 数据 - SmsChannelDO smsChannelDO01 = randomSmsChannelDO(); + SmsChannelDO smsChannelDO01 = randomPojo(SmsChannelDO.class); smsChannelMapper.insert(smsChannelDO01); - SmsChannelDO smsChannelDO02 = randomSmsChannelDO(); + SmsChannelDO smsChannelDO02 = randomPojo(SmsChannelDO.class); smsChannelMapper.insert(smsChannelDO02); // 调用 @@ -82,7 +81,7 @@ public class SmsChannelServiceTest extends BaseDbUnitTest { @Test public void testUpdateSmsChannel_success() { // mock 数据 - SmsChannelDO dbSmsChannel = randomSmsChannelDO(); + SmsChannelDO dbSmsChannel = randomPojo(SmsChannelDO.class); smsChannelMapper.insert(dbSmsChannel);// @Sql: 先插入出一条存在的数据 // 准备参数 SmsChannelUpdateReqVO reqVO = randomPojo(SmsChannelUpdateReqVO.class, o -> { @@ -112,7 +111,7 @@ public class SmsChannelServiceTest extends BaseDbUnitTest { @Test public void testDeleteSmsChannel_success() { // mock 数据 - SmsChannelDO dbSmsChannel = randomSmsChannelDO(); + SmsChannelDO dbSmsChannel = randomPojo(SmsChannelDO.class); smsChannelMapper.insert(dbSmsChannel);// @Sql: 先插入出一条存在的数据 // 准备参数 Long id = dbSmsChannel.getId(); @@ -137,7 +136,7 @@ public class SmsChannelServiceTest extends BaseDbUnitTest { @Test public void testDeleteSmsChannel_hasChildren() { // mock 数据 - SmsChannelDO dbSmsChannel = randomSmsChannelDO(); + SmsChannelDO dbSmsChannel = randomPojo(SmsChannelDO.class); smsChannelMapper.insert(dbSmsChannel);// @Sql: 先插入出一条存在的数据 // 准备参数 Long id = dbSmsChannel.getId(); @@ -148,6 +147,35 @@ public class SmsChannelServiceTest extends BaseDbUnitTest { assertServiceException(() -> smsChannelService.deleteSmsChannel(id), SMS_CHANNEL_HAS_CHILDREN); } + @Test + public void testGetSmsChannel() { + // mock 数据 + SmsChannelDO dbSmsChannel = randomPojo(SmsChannelDO.class); + smsChannelMapper.insert(dbSmsChannel); // @Sql: 先插入出一条存在的数据 + // 准备参数 + Long id = dbSmsChannel.getId(); + + // 调用,并断言 + assertPojoEquals(dbSmsChannel, smsChannelService.getSmsChannel(id)); + } + + @Test + public void testGetSmsChannelList() { + // mock 数据 + SmsChannelDO dbSmsChannel01 = randomPojo(SmsChannelDO.class); + smsChannelMapper.insert(dbSmsChannel01); + SmsChannelDO dbSmsChannel02 = randomPojo(SmsChannelDO.class); + smsChannelMapper.insert(dbSmsChannel02); + // 准备参数 + + // 调用 + List list = smsChannelService.getSmsChannelList(); + // 断言 + assertEquals(2, list.size()); + assertPojoEquals(dbSmsChannel01, list.get(0)); + assertPojoEquals(dbSmsChannel02, list.get(1)); + } + @Test public void testGetSmsChannelPage() { // mock 数据 @@ -158,16 +186,16 @@ public class SmsChannelServiceTest extends BaseDbUnitTest { }); smsChannelMapper.insert(dbSmsChannel); // 测试 signature 不匹配 - smsChannelMapper.insert(ObjectUtils.cloneIgnoreId(dbSmsChannel, o -> o.setSignature("源码"))); + smsChannelMapper.insert(cloneIgnoreId(dbSmsChannel, o -> o.setSignature("源码"))); // 测试 status 不匹配 - smsChannelMapper.insert(ObjectUtils.cloneIgnoreId(dbSmsChannel, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus()))); + smsChannelMapper.insert(cloneIgnoreId(dbSmsChannel, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus()))); // 测试 createTime 不匹配 - smsChannelMapper.insert(ObjectUtils.cloneIgnoreId(dbSmsChannel, o -> o.setCreateTime(buildTime(2020, 11, 11)))); + smsChannelMapper.insert(cloneIgnoreId(dbSmsChannel, o -> o.setCreateTime(buildTime(2020, 11, 11)))); // 准备参数 SmsChannelPageReqVO reqVO = new SmsChannelPageReqVO(); reqVO.setSignature("芋道"); reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus()); - reqVO.setCreateTime((new LocalDateTime[]{buildTime(2020, 12, 1),buildTime(2020, 12, 24)})); + reqVO.setCreateTime(buildBetweenTime(2020, 12, 1, 2020, 12, 24)); // 调用 PageResult pageResult = smsChannelService.getSmsChannelPage(reqVO); @@ -177,14 +205,4 @@ public class SmsChannelServiceTest extends BaseDbUnitTest { assertPojoEquals(dbSmsChannel, pageResult.getList().get(0)); } - // ========== 随机对象 ========== - - @SafeVarargs - private static SmsChannelDO randomSmsChannelDO(Consumer... consumers) { - Consumer consumer = (o) -> { - o.setStatus(randomEle(CommonStatusEnum.values()).getStatus()); // 保证 status 的范围 - }; - return randomPojo(SmsChannelDO.class, ArrayUtils.append(consumer, consumers)); - } - } diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sms/SmsCodeServiceImplTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sms/SmsCodeServiceImplTest.java new file mode 100644 index 000000000..e50d025af --- /dev/null +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sms/SmsCodeServiceImplTest.java @@ -0,0 +1,209 @@ +package cn.iocoder.yudao.module.system.service.sms; + +import cn.hutool.core.map.MapUtil; +import cn.iocoder.yudao.framework.mybatis.core.enums.SqlConstants; +import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; +import cn.iocoder.yudao.module.system.api.sms.dto.code.SmsCodeSendReqDTO; +import cn.iocoder.yudao.module.system.api.sms.dto.code.SmsCodeUseReqDTO; +import cn.iocoder.yudao.module.system.api.sms.dto.code.SmsCodeValidateReqDTO; +import cn.iocoder.yudao.module.system.dal.dataobject.sms.SmsCodeDO; +import cn.iocoder.yudao.module.system.dal.mysql.sms.SmsCodeMapper; +import cn.iocoder.yudao.module.system.enums.sms.SmsSceneEnum; +import cn.iocoder.yudao.module.system.framework.sms.SmsCodeProperties; +import com.baomidou.mybatisplus.annotation.DbType; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.context.annotation.Import; + +import javax.annotation.Resource; +import java.time.Duration; +import java.time.LocalDateTime; + +import static cn.hutool.core.util.RandomUtil.randomEle; +import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; +import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; +import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo; +import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@Import(SmsCodeServiceImpl.class) +public class SmsCodeServiceImplTest extends BaseDbUnitTest { + + @Resource + private SmsCodeServiceImpl smsCodeService; + + @Resource + private SmsCodeMapper smsCodeMapper; + + @MockBean + private SmsCodeProperties smsCodeProperties; + @MockBean + private SmsSendService smsSendService; + + @BeforeEach + public void setUp() { + when(smsCodeProperties.getExpireTimes()).thenReturn(Duration.ofMinutes(5)); + when(smsCodeProperties.getSendFrequency()).thenReturn(Duration.ofMinutes(1)); + when(smsCodeProperties.getSendMaximumQuantityPerDay()).thenReturn(10); + when(smsCodeProperties.getBeginCode()).thenReturn(9999); + when(smsCodeProperties.getEndCode()).thenReturn(9999); + } + + @Test + public void sendSmsCode_success() { + // 准备参数 + SmsCodeSendReqDTO reqDTO = randomPojo(SmsCodeSendReqDTO.class, o -> { + o.setMobile("15601691300"); + o.setScene(SmsSceneEnum.MEMBER_LOGIN.getScene()); + }); + // mock 方法 + SqlConstants.init(DbType.MYSQL); + + // 调用 + smsCodeService.sendSmsCode(reqDTO); + // 断言 code 验证码 + SmsCodeDO smsCodeDO = smsCodeMapper.selectOne(null); + assertPojoEquals(reqDTO, smsCodeDO); + assertEquals("9999", smsCodeDO.getCode()); + assertEquals(1, smsCodeDO.getTodayIndex()); + assertFalse(smsCodeDO.getUsed()); + // 断言调用 + verify(smsSendService).sendSingleSms(eq(reqDTO.getMobile()), isNull(), isNull(), + eq("user-sms-login"), eq(MapUtil.of("code", "9999"))); + } + + @Test + public void sendSmsCode_tooFast() { + // mock 数据 + SmsCodeDO smsCodeDO = randomPojo(SmsCodeDO.class, + o -> o.setMobile("15601691300").setTodayIndex(1)); + smsCodeMapper.insert(smsCodeDO); + // 准备参数 + SmsCodeSendReqDTO reqDTO = randomPojo(SmsCodeSendReqDTO.class, o -> { + o.setMobile("15601691300"); + o.setScene(SmsSceneEnum.MEMBER_LOGIN.getScene()); + }); + // mock 方法 + SqlConstants.init(DbType.MYSQL); + + // 调用,并断言异常 + assertServiceException(() -> smsCodeService.sendSmsCode(reqDTO), + SMS_CODE_SEND_TOO_FAST); + } + + @Test + public void sendSmsCode_exceedDay() { + // mock 数据 + SmsCodeDO smsCodeDO = randomPojo(SmsCodeDO.class, + o -> o.setMobile("15601691300").setTodayIndex(10).setCreateTime(LocalDateTime.now())); + smsCodeMapper.insert(smsCodeDO); + // 准备参数 + SmsCodeSendReqDTO reqDTO = randomPojo(SmsCodeSendReqDTO.class, o -> { + o.setMobile("15601691300"); + o.setScene(SmsSceneEnum.MEMBER_LOGIN.getScene()); + }); + // mock 方法 + SqlConstants.init(DbType.MYSQL); + when(smsCodeProperties.getSendFrequency()).thenReturn(Duration.ofMillis(0)); + + // 调用,并断言异常 + assertServiceException(() -> smsCodeService.sendSmsCode(reqDTO), + SMS_CODE_EXCEED_SEND_MAXIMUM_QUANTITY_PER_DAY); + } + + @Test + public void testUseSmsCode_success() { + // 准备参数 + SmsCodeUseReqDTO reqDTO = randomPojo(SmsCodeUseReqDTO.class, o -> { + o.setMobile("15601691300"); + o.setScene(randomEle(SmsSceneEnum.values()).getScene()); + }); + // mock 数据 + SqlConstants.init(DbType.MYSQL); + smsCodeMapper.insert(randomPojo(SmsCodeDO.class, o -> { + o.setMobile(reqDTO.getMobile()).setScene(reqDTO.getScene()) + .setCode(reqDTO.getCode()).setUsed(false); + })); + + // 调用 + smsCodeService.useSmsCode(reqDTO); + // 断言 + SmsCodeDO smsCodeDO = smsCodeMapper.selectOne(null); + assertTrue(smsCodeDO.getUsed()); + assertNotNull(smsCodeDO.getUsedTime()); + assertEquals(reqDTO.getUsedIp(), smsCodeDO.getUsedIp()); + } + + @Test + public void validateSmsCode_success() { + // 准备参数 + SmsCodeValidateReqDTO reqDTO = randomPojo(SmsCodeValidateReqDTO.class, o -> { + o.setMobile("15601691300"); + o.setScene(randomEle(SmsSceneEnum.values()).getScene()); + }); + // mock 数据 + SqlConstants.init(DbType.MYSQL); + smsCodeMapper.insert(randomPojo(SmsCodeDO.class, o -> o.setMobile(reqDTO.getMobile()) + .setScene(reqDTO.getScene()).setCode(reqDTO.getCode()).setUsed(false))); + + // 调用 + smsCodeService.validateSmsCode(reqDTO); + } + + @Test + public void validateSmsCode_notFound() { + // 准备参数 + SmsCodeValidateReqDTO reqDTO = randomPojo(SmsCodeValidateReqDTO.class, o -> { + o.setMobile("15601691300"); + o.setScene(randomEle(SmsSceneEnum.values()).getScene()); + }); + // mock 数据 + SqlConstants.init(DbType.MYSQL); + + // 调用,并断言异常 + assertServiceException(() -> smsCodeService.validateSmsCode(reqDTO), + SMS_CODE_NOT_FOUND); + } + + @Test + public void validateSmsCode_expired() { + // 准备参数 + SmsCodeValidateReqDTO reqDTO = randomPojo(SmsCodeValidateReqDTO.class, o -> { + o.setMobile("15601691300"); + o.setScene(randomEle(SmsSceneEnum.values()).getScene()); + }); + // mock 数据 + SqlConstants.init(DbType.MYSQL); + smsCodeMapper.insert(randomPojo(SmsCodeDO.class, o -> o.setMobile(reqDTO.getMobile()) + .setScene(reqDTO.getScene()).setCode(reqDTO.getCode()).setUsed(false) + .setCreateTime(LocalDateTime.now().minusMinutes(6)))); + + // 调用,并断言异常 + assertServiceException(() -> smsCodeService.validateSmsCode(reqDTO), + SMS_CODE_EXPIRED); + } + + @Test + public void validateSmsCode_used() { + // 准备参数 + SmsCodeValidateReqDTO reqDTO = randomPojo(SmsCodeValidateReqDTO.class, o -> { + o.setMobile("15601691300"); + o.setScene(randomEle(SmsSceneEnum.values()).getScene()); + }); + // mock 数据 + SqlConstants.init(DbType.MYSQL); + smsCodeMapper.insert(randomPojo(SmsCodeDO.class, o -> o.setMobile(reqDTO.getMobile()) + .setScene(reqDTO.getScene()).setCode(reqDTO.getCode()).setUsed(true) + .setCreateTime(LocalDateTime.now()))); + + // 调用,并断言异常 + assertServiceException(() -> smsCodeService.validateSmsCode(reqDTO), + SMS_CODE_USED); + } + +} diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sms/SmsLogServiceTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sms/SmsLogServiceImplTest.java similarity index 81% rename from yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sms/SmsLogServiceTest.java rename to yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sms/SmsLogServiceImplTest.java index 5a31892f5..2380ca09e 100644 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sms/SmsLogServiceTest.java +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sms/SmsLogServiceImplTest.java @@ -1,7 +1,11 @@ package cn.iocoder.yudao.module.system.service.sms; import cn.hutool.core.map.MapUtil; +import cn.iocoder.yudao.framework.common.enums.UserTypeEnum; import cn.iocoder.yudao.framework.common.pojo.CommonResult; +import cn.iocoder.yudao.framework.common.pojo.PageResult; +import cn.iocoder.yudao.framework.common.util.collection.ArrayUtils; +import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import cn.iocoder.yudao.module.system.controller.admin.sms.vo.log.SmsLogExportReqVO; import cn.iocoder.yudao.module.system.controller.admin.sms.vo.log.SmsLogPageReqVO; import cn.iocoder.yudao.module.system.dal.dataobject.sms.SmsLogDO; @@ -10,11 +14,6 @@ import cn.iocoder.yudao.module.system.dal.mysql.sms.SmsLogMapper; import cn.iocoder.yudao.module.system.enums.sms.SmsReceiveStatusEnum; import cn.iocoder.yudao.module.system.enums.sms.SmsSendStatusEnum; import cn.iocoder.yudao.module.system.enums.sms.SmsTemplateTypeEnum; -import cn.iocoder.yudao.framework.common.enums.UserTypeEnum; -import cn.iocoder.yudao.framework.common.pojo.PageResult; -import cn.iocoder.yudao.framework.common.util.collection.ArrayUtils; -import cn.iocoder.yudao.framework.common.util.object.ObjectUtils; -import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import org.junit.jupiter.api.Test; import org.springframework.context.annotation.Import; @@ -26,14 +25,16 @@ import java.util.function.Consumer; import static cn.hutool.core.util.RandomUtil.randomBoolean; import static cn.hutool.core.util.RandomUtil.randomEle; +import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildBetweenTime; import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildTime; +import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; @Import(SmsLogServiceImpl.class) -public class SmsLogServiceTest extends BaseDbUnitTest { +public class SmsLogServiceImplTest extends BaseDbUnitTest { @Resource private SmsLogServiceImpl smsLogService; @@ -55,30 +56,28 @@ public class SmsLogServiceTest extends BaseDbUnitTest { }); smsLogMapper.insert(dbSmsLog); // 测试 channelId 不匹配 - smsLogMapper.insert(ObjectUtils.cloneIgnoreId(dbSmsLog, o -> o.setChannelId(2L))); + smsLogMapper.insert(cloneIgnoreId(dbSmsLog, o -> o.setChannelId(2L))); // 测试 templateId 不匹配 - smsLogMapper.insert(ObjectUtils.cloneIgnoreId(dbSmsLog, o -> o.setTemplateId(20L))); + smsLogMapper.insert(cloneIgnoreId(dbSmsLog, o -> o.setTemplateId(20L))); // 测试 mobile 不匹配 - smsLogMapper.insert(ObjectUtils.cloneIgnoreId(dbSmsLog, o -> o.setMobile("18818260999"))); + smsLogMapper.insert(cloneIgnoreId(dbSmsLog, o -> o.setMobile("18818260999"))); // 测试 sendStatus 不匹配 - smsLogMapper.insert(ObjectUtils.cloneIgnoreId(dbSmsLog, o -> o.setSendStatus(SmsSendStatusEnum.IGNORE.getStatus()))); + smsLogMapper.insert(cloneIgnoreId(dbSmsLog, o -> o.setSendStatus(SmsSendStatusEnum.IGNORE.getStatus()))); // 测试 sendTime 不匹配 - smsLogMapper.insert(ObjectUtils.cloneIgnoreId(dbSmsLog, o -> o.setSendTime(buildTime(2020, 12, 12)))); + smsLogMapper.insert(cloneIgnoreId(dbSmsLog, o -> o.setSendTime(buildTime(2020, 12, 12)))); // 测试 receiveStatus 不匹配 - smsLogMapper.insert(ObjectUtils.cloneIgnoreId(dbSmsLog, o -> o.setReceiveStatus(SmsReceiveStatusEnum.SUCCESS.getStatus()))); + smsLogMapper.insert(cloneIgnoreId(dbSmsLog, o -> o.setReceiveStatus(SmsReceiveStatusEnum.SUCCESS.getStatus()))); // 测试 receiveTime 不匹配 - smsLogMapper.insert(ObjectUtils.cloneIgnoreId(dbSmsLog, o -> o.setReceiveTime(buildTime(2021, 12, 12)))); + smsLogMapper.insert(cloneIgnoreId(dbSmsLog, o -> o.setReceiveTime(buildTime(2021, 12, 12)))); // 准备参数 SmsLogPageReqVO reqVO = new SmsLogPageReqVO(); reqVO.setChannelId(1L); reqVO.setTemplateId(10L); reqVO.setMobile("156"); reqVO.setSendStatus(SmsSendStatusEnum.INIT.getStatus()); - reqVO.setSendTime((new LocalDateTime[]{buildTime(2020, 11, 1), - buildTime(2020, 11, 30)})); + reqVO.setSendTime(buildBetweenTime(2020, 11, 1, 2020, 11, 30)); reqVO.setReceiveStatus(SmsReceiveStatusEnum.INIT.getStatus()); - reqVO.setReceiveTime((new LocalDateTime[]{buildTime(2021, 11, 1), - buildTime(2021, 11, 30)})); + reqVO.setReceiveTime(buildBetweenTime(2021, 11, 1, 2021, 11, 30)); // 调用 PageResult pageResult = smsLogService.getSmsLogPage(reqVO); @@ -102,30 +101,28 @@ public class SmsLogServiceTest extends BaseDbUnitTest { }); smsLogMapper.insert(dbSmsLog); // 测试 channelId 不匹配 - smsLogMapper.insert(ObjectUtils.cloneIgnoreId(dbSmsLog, o -> o.setChannelId(2L))); + smsLogMapper.insert(cloneIgnoreId(dbSmsLog, o -> o.setChannelId(2L))); // 测试 templateId 不匹配 - smsLogMapper.insert(ObjectUtils.cloneIgnoreId(dbSmsLog, o -> o.setTemplateId(20L))); + smsLogMapper.insert(cloneIgnoreId(dbSmsLog, o -> o.setTemplateId(20L))); // 测试 mobile 不匹配 - smsLogMapper.insert(ObjectUtils.cloneIgnoreId(dbSmsLog, o -> o.setMobile("18818260999"))); + smsLogMapper.insert(cloneIgnoreId(dbSmsLog, o -> o.setMobile("18818260999"))); // 测试 sendStatus 不匹配 - smsLogMapper.insert(ObjectUtils.cloneIgnoreId(dbSmsLog, o -> o.setSendStatus(SmsSendStatusEnum.IGNORE.getStatus()))); + smsLogMapper.insert(cloneIgnoreId(dbSmsLog, o -> o.setSendStatus(SmsSendStatusEnum.IGNORE.getStatus()))); // 测试 sendTime 不匹配 - smsLogMapper.insert(ObjectUtils.cloneIgnoreId(dbSmsLog, o -> o.setSendTime(buildTime(2020, 12, 12)))); + smsLogMapper.insert(cloneIgnoreId(dbSmsLog, o -> o.setSendTime(buildTime(2020, 12, 12)))); // 测试 receiveStatus 不匹配 - smsLogMapper.insert(ObjectUtils.cloneIgnoreId(dbSmsLog, o -> o.setReceiveStatus(SmsReceiveStatusEnum.SUCCESS.getStatus()))); + smsLogMapper.insert(cloneIgnoreId(dbSmsLog, o -> o.setReceiveStatus(SmsReceiveStatusEnum.SUCCESS.getStatus()))); // 测试 receiveTime 不匹配 - smsLogMapper.insert(ObjectUtils.cloneIgnoreId(dbSmsLog, o -> o.setReceiveTime(buildTime(2021, 12, 12)))); + smsLogMapper.insert(cloneIgnoreId(dbSmsLog, o -> o.setReceiveTime(buildTime(2021, 12, 12)))); // 准备参数 SmsLogExportReqVO reqVO = new SmsLogExportReqVO(); reqVO.setChannelId(1L); reqVO.setTemplateId(10L); reqVO.setMobile("156"); reqVO.setSendStatus(SmsSendStatusEnum.INIT.getStatus()); - reqVO.setSendTime((new LocalDateTime[]{buildTime(2020, 11, 1), - buildTime(2020, 11, 30)})); + reqVO.setSendTime(buildBetweenTime(2020, 11, 1, 2020, 11, 30)); reqVO.setReceiveStatus(SmsReceiveStatusEnum.INIT.getStatus()); - reqVO.setReceiveTime((new LocalDateTime[]{buildTime(2021, 11, 1), - buildTime(2021, 11, 30)})); + reqVO.setReceiveTime(buildBetweenTime(2021, 11, 1, 2021, 11, 30)); // 调用 List list = smsLogService.getSmsLogList(reqVO); diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sms/SmsSendServiceTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sms/SmsSendServiceImplTest.java similarity index 63% rename from yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sms/SmsSendServiceTest.java rename to yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sms/SmsSendServiceImplTest.java index 890924e14..0f7d0f9b7 100644 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sms/SmsSendServiceTest.java +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sms/SmsSendServiceImplTest.java @@ -1,10 +1,6 @@ package cn.iocoder.yudao.module.system.service.sms; import cn.hutool.core.map.MapUtil; -import cn.iocoder.yudao.module.system.dal.dataobject.sms.SmsChannelDO; -import cn.iocoder.yudao.module.system.dal.dataobject.sms.SmsTemplateDO; -import cn.iocoder.yudao.module.system.mq.message.sms.SmsSendMessage; -import cn.iocoder.yudao.module.system.mq.producer.sms.SmsProducer; import cn.iocoder.yudao.framework.common.core.KeyValue; import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum; import cn.iocoder.yudao.framework.common.enums.UserTypeEnum; @@ -14,6 +10,13 @@ import cn.iocoder.yudao.framework.sms.core.client.SmsCommonResult; import cn.iocoder.yudao.framework.sms.core.client.dto.SmsReceiveRespDTO; import cn.iocoder.yudao.framework.sms.core.client.dto.SmsSendRespDTO; import cn.iocoder.yudao.framework.test.core.ut.BaseMockitoUnitTest; +import cn.iocoder.yudao.module.system.dal.dataobject.sms.SmsChannelDO; +import cn.iocoder.yudao.module.system.dal.dataobject.sms.SmsTemplateDO; +import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO; +import cn.iocoder.yudao.module.system.mq.message.sms.SmsSendMessage; +import cn.iocoder.yudao.module.system.mq.producer.sms.SmsProducer; +import cn.iocoder.yudao.module.system.service.member.MemberService; +import cn.iocoder.yudao.module.system.service.user.AdminUserService; import org.assertj.core.util.Lists; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; @@ -31,11 +34,15 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.*; -public class SmsSendServiceTest extends BaseMockitoUnitTest { +public class SmsSendServiceImplTest extends BaseMockitoUnitTest { @InjectMocks private SmsSendServiceImpl smsService; + @Mock + private AdminUserService adminUserService; + @Mock + private MemberService memberService; @Mock private SmsChannelService smsChannelService; @Mock @@ -48,6 +55,84 @@ public class SmsSendServiceTest extends BaseMockitoUnitTest { @Mock private SmsClientFactory smsClientFactory; + @Test + public void testSendSingleSmsToAdmin() { + // 准备参数 + Long userId = randomLongId(); + String templateCode = randomString(); + Map templateParams = MapUtil.builder().put("code", "1234") + .put("op", "login").build(); + // mock adminUserService 的方法 + AdminUserDO user = randomPojo(AdminUserDO.class, o -> o.setMobile("15601691300")); + when(adminUserService.getUser(eq(userId))).thenReturn(user); + + // mock SmsTemplateService 的方法 + SmsTemplateDO template = randomPojo(SmsTemplateDO.class, o -> { + o.setStatus(CommonStatusEnum.ENABLE.getStatus()); + o.setContent("验证码为{code}, 操作为{op}"); + o.setParams(Lists.newArrayList("code", "op")); + }); + when(smsTemplateService.getSmsTemplateByCodeFromCache(eq(templateCode))).thenReturn(template); + String content = randomString(); + when(smsTemplateService.formatSmsTemplateContent(eq(template.getContent()), eq(templateParams))) + .thenReturn(content); + // mock SmsChannelService 的方法 + SmsChannelDO smsChannel = randomPojo(SmsChannelDO.class, o -> o.setStatus(CommonStatusEnum.ENABLE.getStatus())); + when(smsChannelService.getSmsChannel(eq(template.getChannelId()))).thenReturn(smsChannel); + // mock SmsLogService 的方法 + Long smsLogId = randomLongId(); + when(smsLogService.createSmsLog(eq(user.getMobile()), eq(userId), eq(UserTypeEnum.ADMIN.getValue()), eq(Boolean.TRUE), eq(template), + eq(content), eq(templateParams))).thenReturn(smsLogId); + + // 调用 + Long resultSmsLogId = smsService.sendSingleSmsToAdmin(null, userId, templateCode, templateParams); + // 断言 + assertEquals(smsLogId, resultSmsLogId); + // 断言调用 + verify(smsProducer).sendSmsSendMessage(eq(smsLogId), eq(user.getMobile()), + eq(template.getChannelId()), eq(template.getApiTemplateId()), + eq(Lists.newArrayList(new KeyValue<>("code", "1234"), new KeyValue<>("op", "login")))); + } + + @Test + public void testSendSingleSmsToUser() { + // 准备参数 + Long userId = randomLongId(); + String templateCode = randomString(); + Map templateParams = MapUtil.builder().put("code", "1234") + .put("op", "login").build(); + // mock memberService 的方法 + String mobile = "15601691300"; + when(memberService.getMemberUserMobile(eq(userId))).thenReturn(mobile); + + // mock SmsTemplateService 的方法 + SmsTemplateDO template = randomPojo(SmsTemplateDO.class, o -> { + o.setStatus(CommonStatusEnum.ENABLE.getStatus()); + o.setContent("验证码为{code}, 操作为{op}"); + o.setParams(Lists.newArrayList("code", "op")); + }); + when(smsTemplateService.getSmsTemplateByCodeFromCache(eq(templateCode))).thenReturn(template); + String content = randomString(); + when(smsTemplateService.formatSmsTemplateContent(eq(template.getContent()), eq(templateParams))) + .thenReturn(content); + // mock SmsChannelService 的方法 + SmsChannelDO smsChannel = randomPojo(SmsChannelDO.class, o -> o.setStatus(CommonStatusEnum.ENABLE.getStatus())); + when(smsChannelService.getSmsChannel(eq(template.getChannelId()))).thenReturn(smsChannel); + // mock SmsLogService 的方法 + Long smsLogId = randomLongId(); + when(smsLogService.createSmsLog(eq(mobile), eq(userId), eq(UserTypeEnum.MEMBER.getValue()), eq(Boolean.TRUE), eq(template), + eq(content), eq(templateParams))).thenReturn(smsLogId); + + // 调用 + Long resultSmsLogId = smsService.sendSingleSmsToMember(null, userId, templateCode, templateParams); + // 断言 + assertEquals(smsLogId, resultSmsLogId); + // 断言调用 + verify(smsProducer).sendSmsSendMessage(eq(smsLogId), eq(mobile), + eq(template.getChannelId()), eq(template.getApiTemplateId()), + eq(Lists.newArrayList(new KeyValue<>("code", "1234"), new KeyValue<>("op", "login")))); + } + /** * 发送成功,当短信模板开启时 */ @@ -83,7 +168,7 @@ public class SmsSendServiceTest extends BaseMockitoUnitTest { // 断言 assertEquals(smsLogId, resultSmsLogId); // 断言调用 - verify(smsProducer, times(1)).sendSmsSendMessage(eq(smsLogId), eq(mobile), + verify(smsProducer).sendSmsSendMessage(eq(smsLogId), eq(mobile), eq(template.getChannelId()), eq(template.getApiTemplateId()), eq(Lists.newArrayList(new KeyValue<>("code", "1234"), new KeyValue<>("op", "login")))); } @@ -134,7 +219,7 @@ public class SmsSendServiceTest extends BaseMockitoUnitTest { // mock 方法 // 调用,并断言异常 - assertServiceException(() -> smsService.checkSmsTemplateValid(templateCode), + assertServiceException(() -> smsService.validateSmsTemplate(templateCode), SMS_SEND_TEMPLATE_NOT_EXISTS); } @@ -157,7 +242,7 @@ public class SmsSendServiceTest extends BaseMockitoUnitTest { // mock 方法 // 调用,并断言异常 - assertServiceException(() -> smsService.checkMobile(null), + assertServiceException(() -> smsService.validateMobile(null), SMS_SEND_MOBILE_NOT_EXISTS); } @@ -177,7 +262,7 @@ public class SmsSendServiceTest extends BaseMockitoUnitTest { // 调用 smsService.doSendSms(message); // 断言 - verify(smsLogService, times(1)).updateSmsSendResult(eq(message.getLogId()), + verify(smsLogService).updateSmsSendResult(eq(message.getLogId()), eq(sendResult.getCode()), eq(sendResult.getMsg()), eq(sendResult.getApiCode()), eq(sendResult.getApiMsg()), eq(sendResult.getApiRequestId()), eq(sendResult.getData().getSerialNo())); } diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sms/SmsTemplateServiceTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sms/SmsTemplateServiceImplTest.java similarity index 92% rename from yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sms/SmsTemplateServiceTest.java rename to yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sms/SmsTemplateServiceImplTest.java index a89d1b2e1..3b9b577a2 100644 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sms/SmsTemplateServiceTest.java +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sms/SmsTemplateServiceImplTest.java @@ -1,14 +1,5 @@ package cn.iocoder.yudao.module.system.service.sms; -import cn.iocoder.yudao.module.system.controller.admin.sms.vo.template.SmsTemplateCreateReqVO; -import cn.iocoder.yudao.module.system.controller.admin.sms.vo.template.SmsTemplateExportReqVO; -import cn.iocoder.yudao.module.system.controller.admin.sms.vo.template.SmsTemplatePageReqVO; -import cn.iocoder.yudao.module.system.controller.admin.sms.vo.template.SmsTemplateUpdateReqVO; -import cn.iocoder.yudao.module.system.dal.dataobject.sms.SmsChannelDO; -import cn.iocoder.yudao.module.system.dal.dataobject.sms.SmsTemplateDO; -import cn.iocoder.yudao.module.system.dal.mysql.sms.SmsTemplateMapper; -import cn.iocoder.yudao.module.system.mq.producer.sms.SmsProducer; -import cn.iocoder.yudao.module.system.enums.sms.SmsTemplateTypeEnum; import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum; import cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants; import cn.iocoder.yudao.framework.common.pojo.PageResult; @@ -19,31 +10,38 @@ import cn.iocoder.yudao.framework.sms.core.client.SmsClientFactory; import cn.iocoder.yudao.framework.sms.core.client.SmsCommonResult; import cn.iocoder.yudao.framework.sms.core.client.dto.SmsTemplateRespDTO; import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; +import cn.iocoder.yudao.module.system.controller.admin.sms.vo.template.SmsTemplateCreateReqVO; +import cn.iocoder.yudao.module.system.controller.admin.sms.vo.template.SmsTemplateExportReqVO; +import cn.iocoder.yudao.module.system.controller.admin.sms.vo.template.SmsTemplatePageReqVO; +import cn.iocoder.yudao.module.system.controller.admin.sms.vo.template.SmsTemplateUpdateReqVO; +import cn.iocoder.yudao.module.system.dal.dataobject.sms.SmsChannelDO; +import cn.iocoder.yudao.module.system.dal.dataobject.sms.SmsTemplateDO; +import cn.iocoder.yudao.module.system.dal.mysql.sms.SmsTemplateMapper; +import cn.iocoder.yudao.module.system.enums.sms.SmsTemplateTypeEnum; +import cn.iocoder.yudao.module.system.mq.producer.sms.SmsProducer; import com.google.common.collect.Lists; import org.junit.jupiter.api.Test; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import javax.annotation.Resource; -import java.time.LocalDateTime; import java.util.List; import java.util.Map; import java.util.function.Consumer; -import static cn.hutool.core.bean.BeanUtil.getFieldValue; import static cn.hutool.core.util.RandomUtil.randomEle; -import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.max; -import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*; +import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildBetweenTime; import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildTime; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; +import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.*; @Import(SmsTemplateServiceImpl.class) -public class SmsTemplateServiceTest extends BaseDbUnitTest { +public class SmsTemplateServiceImplTest extends BaseDbUnitTest { @Resource private SmsTemplateServiceImpl smsTemplateService; @@ -226,7 +224,7 @@ public class SmsTemplateServiceTest extends BaseDbUnitTest { reqVO.setContent("芋道"); reqVO.setApiTemplateId("yu"); reqVO.setChannelId(1L); - reqVO.setCreateTime((new LocalDateTime[]{buildTime(2021, 11, 1),buildTime(2021, 12, 1)})); + reqVO.setCreateTime(buildBetweenTime(2021, 11, 1, 2021, 12, 1)); // 调用 PageResult pageResult = smsTemplateService.getSmsTemplatePage(reqVO); @@ -271,7 +269,7 @@ public class SmsTemplateServiceTest extends BaseDbUnitTest { reqVO.setContent("芋道"); reqVO.setApiTemplateId("yu"); reqVO.setChannelId(1L); - reqVO.setCreateTime((new LocalDateTime[]{buildTime(2021, 11, 1),buildTime(2021, 12, 1)})); + reqVO.setCreateTime(buildBetweenTime(2021, 11, 1, 2021, 12, 1)); // 调用 List list = smsTemplateService.getSmsTemplateList(reqVO); @@ -281,7 +279,7 @@ public class SmsTemplateServiceTest extends BaseDbUnitTest { } @Test - public void testCheckSmsChannel_success() { + public void testValidateSmsChannel_success() { // 准备参数 Long channelId = randomLongId(); // mock 方法 @@ -292,23 +290,23 @@ public class SmsTemplateServiceTest extends BaseDbUnitTest { when(smsChannelService.getSmsChannel(eq(channelId))).thenReturn(channelDO); // 调用 - SmsChannelDO returnChannelDO = smsTemplateService.checkSmsChannel(channelId); + SmsChannelDO returnChannelDO = smsTemplateService.validateSmsChannel(channelId); // 断言 assertPojoEquals(returnChannelDO, channelDO); } @Test - public void testCheckSmsChannel_notExists() { + public void testValidateSmsChannel_notExists() { // 准备参数 Long channelId = randomLongId(); // 调用,校验异常 - assertServiceException(() -> smsTemplateService.checkSmsChannel(channelId), + assertServiceException(() -> smsTemplateService.validateSmsChannel(channelId), SMS_CHANNEL_NOT_EXISTS); } @Test - public void testCheckSmsChannel_disable() { + public void testValidateSmsChannel_disable() { // 准备参数 Long channelId = randomLongId(); // mock 方法 @@ -319,30 +317,30 @@ public class SmsTemplateServiceTest extends BaseDbUnitTest { when(smsChannelService.getSmsChannel(eq(channelId))).thenReturn(channelDO); // 调用,校验异常 - assertServiceException(() -> smsTemplateService.checkSmsChannel(channelId), + assertServiceException(() -> smsTemplateService.validateSmsChannel(channelId), SMS_CHANNEL_DISABLE); } @Test - public void testCheckDictDataValueUnique_success() { + public void testValidateDictDataValueUnique_success() { // 调用,成功 - smsTemplateService.checkSmsTemplateCodeDuplicate(randomLongId(), randomString()); + smsTemplateService.validateSmsTemplateCodeDuplicate(randomLongId(), randomString()); } @Test - public void testCheckSmsTemplateCodeDuplicate_valueDuplicateForCreate() { + public void testValidateSmsTemplateCodeDuplicate_valueDuplicateForCreate() { // 准备参数 String code = randomString(); // mock 数据 smsTemplateMapper.insert(randomSmsTemplateDO(o -> o.setCode(code))); // 调用,校验异常 - assertServiceException(() -> smsTemplateService.checkSmsTemplateCodeDuplicate(null, code), + assertServiceException(() -> smsTemplateService.validateSmsTemplateCodeDuplicate(null, code), SMS_TEMPLATE_CODE_DUPLICATE, code); } @Test - public void testCheckDictDataValueUnique_valueDuplicateForUpdate() { + public void testValidateDictDataValueUnique_valueDuplicateForUpdate() { // 准备参数 Long id = randomLongId(); String code = randomString(); @@ -350,7 +348,7 @@ public class SmsTemplateServiceTest extends BaseDbUnitTest { smsTemplateMapper.insert(randomSmsTemplateDO(o -> o.setCode(code))); // 调用,校验异常 - assertServiceException(() -> smsTemplateService.checkSmsTemplateCodeDuplicate(id, code), + assertServiceException(() -> smsTemplateService.validateSmsTemplateCodeDuplicate(id, code), SMS_TEMPLATE_CODE_DUPLICATE, code); } diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/social/SocialUserServiceTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/social/SocialUserServiceImplTest.java similarity index 99% rename from yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/social/SocialUserServiceTest.java rename to yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/social/SocialUserServiceImplTest.java index 6a3e76bdf..48f914a1a 100644 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/social/SocialUserServiceTest.java +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/social/SocialUserServiceImplTest.java @@ -35,7 +35,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.*; @Import(SocialUserServiceImpl.class) -public class SocialUserServiceTest extends BaseDbAndRedisUnitTest { +public class SocialUserServiceImplTest extends BaseDbAndRedisUnitTest { @Resource private SocialUserServiceImpl socialUserService; diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/tenant/TenantPackageServiceImplTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/tenant/TenantPackageServiceImplTest.java index 8277cdea5..9f80a1014 100755 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/tenant/TenantPackageServiceImplTest.java +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/tenant/TenantPackageServiceImplTest.java @@ -2,21 +2,22 @@ package cn.iocoder.yudao.module.system.service.tenant; import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum; import cn.iocoder.yudao.framework.common.pojo.PageResult; +import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import cn.iocoder.yudao.module.system.controller.admin.tenant.vo.packages.TenantPackageCreateReqVO; import cn.iocoder.yudao.module.system.controller.admin.tenant.vo.packages.TenantPackagePageReqVO; import cn.iocoder.yudao.module.system.controller.admin.tenant.vo.packages.TenantPackageUpdateReqVO; import cn.iocoder.yudao.module.system.dal.dataobject.tenant.TenantDO; import cn.iocoder.yudao.module.system.dal.dataobject.tenant.TenantPackageDO; import cn.iocoder.yudao.module.system.dal.mysql.tenant.TenantPackageMapper; -import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import org.junit.jupiter.api.Test; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import javax.annotation.Resource; -import java.time.LocalDateTime; +import java.util.List; +import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildBetweenTime; import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildTime; import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; @@ -158,7 +159,7 @@ public class TenantPackageServiceImplTest extends BaseDbUnitTest { reqVO.setName("芋道"); reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus()); reqVO.setRemark("源码"); - reqVO.setCreateTime((new LocalDateTime[]{buildTime(2022, 10, 9),buildTime(2022, 10, 11)})); + reqVO.setCreateTime(buildBetweenTime(2022, 10, 9, 2022, 10, 11)); // 调用 PageResult pageResult = tenantPackageService.getTenantPackagePage(reqVO); @@ -201,4 +202,34 @@ public class TenantPackageServiceImplTest extends BaseDbUnitTest { assertServiceException(() -> tenantPackageService.validTenantPackage(dbTenantPackage.getId()), TENANT_PACKAGE_DISABLE, dbTenantPackage.getName()); } + + @Test + public void testGetTenantPackage() { + // mock 数据 + TenantPackageDO dbTenantPackage = randomPojo(TenantPackageDO.class); + tenantPackageMapper.insert(dbTenantPackage);// @Sql: 先插入出一条存在的数据 + + // 调用 + TenantPackageDO result = tenantPackageService.getTenantPackage(dbTenantPackage.getId()); + // 断言 + assertPojoEquals(result, dbTenantPackage); + } + + @Test + public void testGetTenantPackageListByStatus() { + // mock 数据 + TenantPackageDO dbTenantPackage = randomPojo(TenantPackageDO.class, + o -> o.setStatus(CommonStatusEnum.ENABLE.getStatus())); + tenantPackageMapper.insert(dbTenantPackage); + // 测试 status 不匹配 + tenantPackageMapper.insert(cloneIgnoreId(dbTenantPackage, + o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus()))); + + // 调用 + List list = tenantPackageService.getTenantPackageListByStatus( + CommonStatusEnum.ENABLE.getStatus()); + assertEquals(1, list.size()); + assertPojoEquals(dbTenantPackage, list.get(0)); + } + } diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/tenant/TenantServiceImplTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/tenant/TenantServiceImplTest.java index dfaebdbb7..38357b280 100644 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/tenant/TenantServiceImplTest.java +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/tenant/TenantServiceImplTest.java @@ -34,6 +34,7 @@ import java.util.Collections; import java.util.List; import static cn.iocoder.yudao.framework.common.util.collection.SetUtils.asSet; +import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildBetweenTime; import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildTime; import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; @@ -81,13 +82,13 @@ public class TenantServiceImplTest extends BaseDbUnitTest { } @Test - public void testGetTenantIds() { + public void testGetTenantIdList() { // mock 数据 TenantDO tenant = randomPojo(TenantDO.class, o -> o.setId(1L)); tenantMapper.insert(tenant); // 调用,并断言业务异常 - List result = tenantService.getTenantIds(); + List result = tenantService.getTenantIdList(); assertEquals(Collections.singletonList(1L), result); } @@ -196,7 +197,7 @@ public class TenantServiceImplTest extends BaseDbUnitTest { role100.setTenantId(dbTenant.getId()); RoleDO role101 = randomPojo(RoleDO.class, o -> o.setId(101L)); role101.setTenantId(dbTenant.getId()); - when(roleService.getRoles(isNull())).thenReturn(asList(role100, role101)); + when(roleService.getRoleListByStatus(isNull())).thenReturn(asList(role100, role101)); // mock 每个角色的权限 when(permissionService.getRoleMenuIds(eq(101L))).thenReturn(asSet(201L, 202L)); @@ -310,7 +311,7 @@ public class TenantServiceImplTest extends BaseDbUnitTest { reqVO.setContactName("艿"); reqVO.setContactMobile("1560"); reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus()); - reqVO.setCreateTime(new LocalDateTime[]{buildTime(2020, 12, 1),buildTime(2020, 12, 24)}); + reqVO.setCreateTime(buildBetweenTime(2020, 12, 1, 2020, 12, 24)); // 调用 PageResult pageResult = tenantService.getTenantPage(reqVO); @@ -347,7 +348,7 @@ public class TenantServiceImplTest extends BaseDbUnitTest { reqVO.setContactName("艿"); reqVO.setContactMobile("1560"); reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus()); - reqVO.setCreateTime(new LocalDateTime[]{buildTime(2020, 12, 1),buildTime(2020, 12, 24)}); + reqVO.setCreateTime(buildBetweenTime(2020, 12, 1, 2020, 12, 24)); // 调用 List list = tenantService.getTenantList(reqVO); @@ -356,7 +357,6 @@ public class TenantServiceImplTest extends BaseDbUnitTest { assertPojoEquals(dbTenant, list.get(0)); } - @Test public void testGetTenantByName() { // mock 数据 @@ -453,7 +453,7 @@ public class TenantServiceImplTest extends BaseDbUnitTest { tenantMapper.insert(dbTenant);// @Sql: 先插入出一条存在的数据 TenantContextHolder.setTenantId(dbTenant.getId()); // mock 菜单 - when(menuService.getMenus()).thenReturn(Arrays.asList(randomPojo(MenuDO.class, o -> o.setId(100L)), + when(menuService.getMenuList()).thenReturn(Arrays.asList(randomPojo(MenuDO.class, o -> o.setId(100L)), randomPojo(MenuDO.class, o -> o.setId(101L)))); // 调用 diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/user/AdminUserServiceImplTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/user/AdminUserServiceImplTest.java index 2822789e3..a5e0183a4 100644 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/user/AdminUserServiceImplTest.java +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/user/AdminUserServiceImplTest.java @@ -6,7 +6,6 @@ import cn.iocoder.yudao.framework.common.exception.ServiceException; import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.common.util.collection.ArrayUtils; import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils; -import cn.iocoder.yudao.framework.common.util.object.ObjectUtils; import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import cn.iocoder.yudao.module.infra.api.file.FileApi; import cn.iocoder.yudao.module.system.controller.admin.user.vo.profile.UserProfileUpdatePasswordReqVO; @@ -32,23 +31,25 @@ import org.springframework.security.crypto.password.PasswordEncoder; import javax.annotation.Resource; import java.io.ByteArrayInputStream; -import java.time.LocalDateTime; import java.util.Collection; import java.util.List; +import java.util.Map; import java.util.function.Consumer; import static cn.hutool.core.util.RandomUtil.randomBytes; import static cn.hutool.core.util.RandomUtil.randomEle; import static cn.iocoder.yudao.framework.common.util.collection.SetUtils.asSet; +import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildBetweenTime; import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildTime; +import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*; import static java.util.Collections.singleton; +import static java.util.Collections.singletonList; import static org.assertj.core.util.Lists.newArrayList; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; @@ -102,7 +103,7 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest { o.setId(postId); o.setStatus(CommonStatusEnum.ENABLE.getStatus()); })); - when(postService.getPosts(eq(reqVO.getPostIds()), isNull())).thenReturn(posts); + when(postService.getPostList(eq(reqVO.getPostIds()), isNull())).thenReturn(posts); // mock passwordEncoder 的方法 when(passwordEncoder.encode(eq(reqVO.getPassword()))).thenReturn("yudaoyuanma"); @@ -160,7 +161,7 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest { o.setId(postId); o.setStatus(CommonStatusEnum.ENABLE.getStatus()); })); - when(postService.getPosts(eq(reqVO.getPostIds()), isNull())).thenReturn(posts); + when(postService.getPostList(eq(reqVO.getPostIds()), isNull())).thenReturn(posts); // 调用 userService.updateUser(reqVO); @@ -173,6 +174,23 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest { assertEquals(3L, userPosts.get(1).getPostId()); } + @Test + public void testUpdateUserLogin() { + // mock 数据 + AdminUserDO user = randomAdminUserDO(o -> o.setLoginDate(null)); + userMapper.insert(user); + // 准备参数 + Long id = user.getId(); + String loginIp = randomString(); + + // 调用 + userService.updateUserLogin(id, loginIp); + // 断言 + AdminUserDO dbUser = userMapper.selectById(id); + assertEquals(loginIp, dbUser.getLoginIp()); + assertNotNull(dbUser.getLoginDate()); + } + @Test public void testUpdateUserProfile_success() { // mock 数据 @@ -286,6 +304,34 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest { verify(permissionService, times(1)).processUserDeleted(eq(userId)); } + @Test + public void testGetUserByUsername() { + // mock 数据 + AdminUserDO dbUser = randomAdminUserDO(); + userMapper.insert(dbUser); + // 准备参数 + String username = dbUser.getUsername(); + + // 调用 + AdminUserDO user = userService.getUserByUsername(username); + // 断言 + assertPojoEquals(dbUser, user); + } + + @Test + public void testGetUserByMobile() { + // mock 数据 + AdminUserDO dbUser = randomAdminUserDO(); + userMapper.insert(dbUser); + // 准备参数 + String mobile = dbUser.getMobile(); + + // 调用 + AdminUserDO user = userService.getUserByMobile(mobile); + // 断言 + assertPojoEquals(dbUser, user); + } + @Test public void testGetUserPage() { // mock 数据 @@ -295,11 +341,11 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest { reqVO.setUsername("tu"); reqVO.setMobile("1560"); reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus()); - reqVO.setCreateTime((new LocalDateTime[]{buildTime(2020, 12, 1),buildTime(2020, 12, 24)})); + reqVO.setCreateTime(buildBetweenTime(2020, 12, 1, 2020, 12, 24)); reqVO.setDeptId(1L); // 其中,1L 是 2L 的父部门 // mock 方法 List deptList = newArrayList(randomPojo(DeptDO.class, o -> o.setId(2L))); - when(deptService.getDeptsByParentIdFromCache(eq(reqVO.getDeptId()), eq(true))).thenReturn(deptList); + when(deptService.getDeptListByParentIdFromCache(eq(reqVO.getDeptId()), eq(true))).thenReturn(deptList); // 调用 PageResult pageResult = userService.getUserPage(reqVO); @@ -310,7 +356,7 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest { } @Test - public void testGetUsers() { + public void testGetUserList_export() { // mock 数据 AdminUserDO dbUser = initGetUserPageData(); // 准备参数 @@ -318,14 +364,14 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest { reqVO.setUsername("tu"); reqVO.setMobile("1560"); reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus()); - reqVO.setCreateTime((new LocalDateTime[]{buildTime(2020, 12, 1),buildTime(2020, 12, 24)})); + reqVO.setCreateTime(buildBetweenTime(2020, 12, 1, 2020, 12, 24)); reqVO.setDeptId(1L); // 其中,1L 是 2L 的父部门 // mock 方法 List deptList = newArrayList(randomPojo(DeptDO.class, o -> o.setId(2L))); - when(deptService.getDeptsByParentIdFromCache(eq(reqVO.getDeptId()), eq(true))).thenReturn(deptList); + when(deptService.getDeptListByParentIdFromCache(eq(reqVO.getDeptId()), eq(true))).thenReturn(deptList); // 调用 - List list = userService.getUsers(reqVO); + List list = userService.getUserList(reqVO); // 断言 assertEquals(1, list.size()); assertPojoEquals(dbUser, list.get(0)); @@ -345,31 +391,62 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest { }); userMapper.insert(dbUser); // 测试 username 不匹配 - userMapper.insert(ObjectUtils.cloneIgnoreId(dbUser, o -> o.setUsername("dou"))); + userMapper.insert(cloneIgnoreId(dbUser, o -> o.setUsername("dou"))); // 测试 mobile 不匹配 - userMapper.insert(ObjectUtils.cloneIgnoreId(dbUser, o -> o.setMobile("18818260888"))); + userMapper.insert(cloneIgnoreId(dbUser, o -> o.setMobile("18818260888"))); // 测试 status 不匹配 - userMapper.insert(ObjectUtils.cloneIgnoreId(dbUser, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus()))); + userMapper.insert(cloneIgnoreId(dbUser, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus()))); // 测试 createTime 不匹配 - userMapper.insert(ObjectUtils.cloneIgnoreId(dbUser, o -> o.setCreateTime(buildTime(2020, 11, 11)))); + userMapper.insert(cloneIgnoreId(dbUser, o -> o.setCreateTime(buildTime(2020, 11, 11)))); // 测试 dept 不匹配 - userMapper.insert(ObjectUtils.cloneIgnoreId(dbUser, o -> o.setDeptId(0L))); + userMapper.insert(cloneIgnoreId(dbUser, o -> o.setDeptId(0L))); return dbUser; } + @Test + public void testGetUser() { + // mock 数据 + AdminUserDO dbUser = randomAdminUserDO(); + userMapper.insert(dbUser); + // 准备参数 + Long userId = dbUser.getId(); + + // 调用 + AdminUserDO user = userService.getUser(userId); + // 断言 + assertPojoEquals(dbUser, user); + } + + @Test + public void testGetUserListByDeptIds() { + // mock 数据 + AdminUserDO dbUser = randomAdminUserDO(o -> o.setDeptId(1L)); + userMapper.insert(dbUser); + // 测试 deptId 不匹配 + userMapper.insert(cloneIgnoreId(dbUser, o -> o.setDeptId(2L))); + // 准备参数 + Collection deptIds = singleton(1L); + + // 调用 + List list = userService.getUserListByDeptIds(deptIds); + // 断言 + assertEquals(1, list.size()); + assertEquals(dbUser, list.get(0)); + } + /** * 情况一,校验不通过,导致插入失败 */ @Test - public void testImportUsers_01() { + public void testImportUserList_01() { // 准备参数 UserImportExcelVO importUser = randomPojo(UserImportExcelVO.class, o -> { }); // mock 方法,模拟失败 - doThrow(new ServiceException(DEPT_NOT_FOUND)).when(deptService).validDepts(any()); + doThrow(new ServiceException(DEPT_NOT_FOUND)).when(deptService).validateDeptList(any()); // 调用 - UserImportRespVO respVO = userService.importUsers(newArrayList(importUser), true); + UserImportRespVO respVO = userService.importUserList(newArrayList(importUser), true); // 断言 assertEquals(0, respVO.getCreateUsernames().size()); assertEquals(0, respVO.getUpdateUsernames().size()); @@ -381,7 +458,7 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest { * 情况二,不存在,进行插入 */ @Test - public void testImportUsers_02() { + public void testImportUserList_02() { // 准备参数 UserImportExcelVO importUser = randomPojo(UserImportExcelVO.class, o -> { o.setStatus(randomEle(CommonStatusEnum.values()).getStatus()); // 保证 status 的范围 @@ -397,7 +474,7 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest { when(passwordEncoder.encode(eq("yudaoyuanma"))).thenReturn("java"); // 调用 - UserImportRespVO respVO = userService.importUsers(newArrayList(importUser), true); + UserImportRespVO respVO = userService.importUserList(newArrayList(importUser), true); // 断言 assertEquals(1, respVO.getCreateUsernames().size()); AdminUserDO user = userMapper.selectByUsername(respVO.getCreateUsernames().get(0)); @@ -411,7 +488,7 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest { * 情况三,存在,但是不强制更新 */ @Test - public void testImportUsers_03() { + public void testImportUserList_03() { // mock 数据 AdminUserDO dbUser = randomAdminUserDO(); userMapper.insert(dbUser); @@ -429,7 +506,7 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest { when(deptService.getDept(eq(dept.getId()))).thenReturn(dept); // 调用 - UserImportRespVO respVO = userService.importUsers(newArrayList(importUser), false); + UserImportRespVO respVO = userService.importUserList(newArrayList(importUser), false); // 断言 assertEquals(0, respVO.getCreateUsernames().size()); assertEquals(0, respVO.getUpdateUsernames().size()); @@ -441,7 +518,7 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest { * 情况四,存在,强制更新 */ @Test - public void testImportUsers_04() { + public void testImportUserList_04() { // mock 数据 AdminUserDO dbUser = randomAdminUserDO(); userMapper.insert(dbUser); @@ -459,7 +536,7 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest { when(deptService.getDept(eq(dept.getId()))).thenReturn(dept); // 调用 - UserImportRespVO respVO = userService.importUsers(newArrayList(importUser), true); + UserImportRespVO respVO = userService.importUserList(newArrayList(importUser), true); // 断言 assertEquals(0, respVO.getCreateUsernames().size()); assertEquals(1, respVO.getUpdateUsernames().size()); @@ -469,24 +546,24 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest { } @Test - public void testCheckUserExists_notExists() { - assertServiceException(() -> userService.checkUserExists(randomLongId()), USER_NOT_EXISTS); + public void testValidateUserExists_notExists() { + assertServiceException(() -> userService.validateUserExists(randomLongId()), USER_NOT_EXISTS); } @Test - public void testCheckUsernameUnique_usernameExistsForCreate() { + public void testValidateUsernameUnique_usernameExistsForCreate() { // 准备参数 String username = randomString(); // mock 数据 userMapper.insert(randomAdminUserDO(o -> o.setUsername(username))); // 调用,校验异常 - assertServiceException(() -> userService.checkUsernameUnique(null, username), + assertServiceException(() -> userService.validateUsernameUnique(null, username), USER_USERNAME_EXISTS); } @Test - public void testCheckUsernameUnique_usernameExistsForUpdate() { + public void testValidateUsernameUnique_usernameExistsForUpdate() { // 准备参数 Long id = randomLongId(); String username = randomString(); @@ -494,24 +571,24 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest { userMapper.insert(randomAdminUserDO(o -> o.setUsername(username))); // 调用,校验异常 - assertServiceException(() -> userService.checkUsernameUnique(id, username), + assertServiceException(() -> userService.validateUsernameUnique(id, username), USER_USERNAME_EXISTS); } @Test - public void testCheckEmailUnique_emailExistsForCreate() { + public void testValidateEmailUnique_emailExistsForCreate() { // 准备参数 String email = randomString(); // mock 数据 userMapper.insert(randomAdminUserDO(o -> o.setEmail(email))); // 调用,校验异常 - assertServiceException(() -> userService.checkEmailUnique(null, email), + assertServiceException(() -> userService.validateEmailUnique(null, email), USER_EMAIL_EXISTS); } @Test - public void testCheckEmailUnique_emailExistsForUpdate() { + public void testValidateEmailUnique_emailExistsForUpdate() { // 准备参数 Long id = randomLongId(); String email = randomString(); @@ -519,24 +596,24 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest { userMapper.insert(randomAdminUserDO(o -> o.setEmail(email))); // 调用,校验异常 - assertServiceException(() -> userService.checkEmailUnique(id, email), + assertServiceException(() -> userService.validateEmailUnique(id, email), USER_EMAIL_EXISTS); } @Test - public void testCheckMobileUnique_mobileExistsForCreate() { + public void testValidateMobileUnique_mobileExistsForCreate() { // 准备参数 String mobile = randomString(); // mock 数据 userMapper.insert(randomAdminUserDO(o -> o.setMobile(mobile))); // 调用,校验异常 - assertServiceException(() -> userService.checkMobileUnique(null, mobile), + assertServiceException(() -> userService.validateMobileUnique(null, mobile), USER_MOBILE_EXISTS); } @Test - public void testCheckMobileUnique_mobileExistsForUpdate() { + public void testValidateMobileUnique_mobileExistsForUpdate() { // 准备参数 Long id = randomLongId(); String mobile = randomString(); @@ -544,18 +621,18 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest { userMapper.insert(randomAdminUserDO(o -> o.setMobile(mobile))); // 调用,校验异常 - assertServiceException(() -> userService.checkMobileUnique(id, mobile), + assertServiceException(() -> userService.validateMobileUnique(id, mobile), USER_MOBILE_EXISTS); } @Test - public void testCheckOldPassword_notExists() { - assertServiceException(() -> userService.checkOldPassword(randomLongId(), randomString()), + public void testValidateOldPassword_notExists() { + assertServiceException(() -> userService.validateOldPassword(randomLongId(), randomString()), USER_NOT_EXISTS); } @Test - public void testCheckOldPassword_passwordFailed() { + public void testValidateOldPassword_passwordFailed() { // mock 数据 AdminUserDO user = randomAdminUserDO(); userMapper.insert(user); @@ -564,14 +641,14 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest { String oldPassword = user.getPassword(); // 调用,校验异常 - assertServiceException(() -> userService.checkOldPassword(id, oldPassword), + assertServiceException(() -> userService.validateOldPassword(id, oldPassword), USER_PASSWORD_FAILED); // 校验调用 verify(passwordEncoder, times(1)).matches(eq(oldPassword), eq(user.getPassword())); } @Test - public void testUsersByPostIds() { + public void testUserListByPostIds() { // 准备参数 Collection postIds = asSet(10L, 20L); // mock user1 数据 @@ -585,12 +662,114 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest { userPostMapper.insert(new UserPostDO().setUserId(user2.getId()).setPostId(100L)); // 调用 - List result = userService.getUsersByPostIds(postIds); + List result = userService.getUserListByPostIds(postIds); // 断言 assertEquals(1, result.size()); assertEquals(user1, result.get(0)); } + @Test + public void testGetUserList() { + // mock 数据 + AdminUserDO user = randomAdminUserDO(); + userMapper.insert(user); + // 测试 id 不匹配 + userMapper.insert(randomAdminUserDO()); + // 准备参数 + Collection ids = singleton(user.getId()); + + // 调用 + List result = userService.getUserList(ids); + // 断言 + assertEquals(1, result.size()); + assertEquals(user, result.get(0)); + } + + @Test + public void testGetUserMap() { + // mock 数据 + AdminUserDO user = randomAdminUserDO(); + userMapper.insert(user); + // 测试 id 不匹配 + userMapper.insert(randomAdminUserDO()); + // 准备参数 + Collection ids = singleton(user.getId()); + + // 调用 + Map result = userService.getUserMap(ids); + // 断言 + assertEquals(1, result.size()); + assertEquals(user, result.get(user.getId())); + } + + @Test + public void testGetUserListByNickname() { + // mock 数据 + AdminUserDO user = randomAdminUserDO(o -> o.setNickname("芋头")); + userMapper.insert(user); + // 测试 nickname 不匹配 + userMapper.insert(randomAdminUserDO(o -> o.setNickname("源码"))); + // 准备参数 + String nickname = "芋"; + + // 调用 + List result = userService.getUserListByNickname(nickname); + // 断言 + assertEquals(1, result.size()); + assertEquals(user, result.get(0)); + } + + @Test + public void testGetUserListByStatus() { + // mock 数据 + AdminUserDO user = randomAdminUserDO(o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus())); + userMapper.insert(user); + // 测试 status 不匹配 + userMapper.insert(randomAdminUserDO(o -> o.setStatus(CommonStatusEnum.ENABLE.getStatus()))); + // 准备参数 + Integer status = CommonStatusEnum.DISABLE.getStatus(); + + // 调用 + List result = userService.getUserListByStatus(status); + // 断言 + assertEquals(1, result.size()); + assertEquals(user, result.get(0)); + } + + @Test + public void testValidateUserList_success() { + // mock 数据 + AdminUserDO userDO = randomAdminUserDO().setStatus(CommonStatusEnum.ENABLE.getStatus()); + userMapper.insert(userDO); + // 准备参数 + List ids = singletonList(userDO.getId()); + + // 调用,无需断言 + userService.validateUserList(ids); + } + + @Test + public void testValidateUserList_notFound() { + // 准备参数 + List ids = singletonList(randomLongId()); + + // 调用, 并断言异常 + assertServiceException(() -> userService.validateUserList(ids), USER_NOT_EXISTS); + } + + @Test + public void testValidateUserList_notEnable() { + // mock 数据 + AdminUserDO userDO = randomAdminUserDO().setStatus(CommonStatusEnum.DISABLE.getStatus()); + userMapper.insert(userDO); + // 准备参数 + List ids = singletonList(userDO.getId()); + + // 调用, 并断言异常 + assertServiceException(() -> userService.validateUserList(ids), USER_IS_DISABLE, + userDO.getNickname()); + } + // ========== 随机对象 ========== @SafeVarargs diff --git a/yudao-module-system/yudao-module-system-biz/src/test/resources/sql/clean.sql b/yudao-module-system/yudao-module-system-biz/src/test/resources/sql/clean.sql index 1be69f28b..785e5ea05 100644 --- a/yudao-module-system/yudao-module-system-biz/src/test/resources/sql/clean.sql +++ b/yudao-module-system/yudao-module-system-biz/src/test/resources/sql/clean.sql @@ -4,16 +4,18 @@ DELETE FROM "system_role"; DELETE FROM "system_role_menu"; DELETE FROM "system_menu"; DELETE FROM "system_user_role"; -DELETE FROM "system_user_post"; DELETE FROM "system_dict_type"; DELETE FROM "system_user_session"; DELETE FROM "system_post"; +DELETE FROM "system_user_post"; +DELETE FROM "system_notice"; DELETE FROM "system_login_log"; DELETE FROM "system_operate_log"; DELETE FROM "system_users"; DELETE FROM "system_sms_channel"; DELETE FROM "system_sms_template"; DELETE FROM "system_sms_log"; +DELETE FROM "system_sms_code"; DELETE FROM "system_error_code"; DELETE FROM "system_social_user"; DELETE FROM "system_social_user_bind"; diff --git a/yudao-module-system/yudao-module-system-biz/src/test/resources/sql/create_tables.sql b/yudao-module-system/yudao-module-system-biz/src/test/resources/sql/create_tables.sql index bf135f39e..e665f6a3b 100644 --- a/yudao-module-system/yudao-module-system-biz/src/test/resources/sql/create_tables.sql +++ b/yudao-module-system/yudao-module-system-biz/src/test/resources/sql/create_tables.sql @@ -162,7 +162,6 @@ CREATE TABLE IF NOT EXISTS `system_user_post`( PRIMARY KEY (`id`) ) COMMENT ='用户岗位表'; - CREATE TABLE IF NOT EXISTS "system_notice" ( "id" bigint NOT NULL GENERATED BY DEFAULT AS IDENTITY, "title" varchar(50) NOT NULL COMMENT '公告标题', @@ -250,63 +249,6 @@ CREATE TABLE IF NOT EXISTS "system_users" ( primary key ("id") ) comment '用户信息表'; -CREATE TABLE IF NOT EXISTS "inf_api_access_log" ( - "id" bigint not null GENERATED BY DEFAULT AS IDENTITY, - "trace_id" varchar(64) not null default '', - "user_id" bigint not null default '0', - "user_type" tinyint not null default '0', - "application_name" varchar(50) not null, - "request_method" varchar(16) not null default '', - "request_url" varchar(255) not null default '', - "request_params" varchar(8000) not null default '', - "user_ip" varchar(50) not null, - "user_agent" varchar(512) not null, - "begin_time" timestamp not null, - "end_time" timestamp not null, - "duration" integer not null, - "result_code" integer not null default '0', - "result_msg" varchar(512) default '', - "creator" varchar(64) default '', - "create_time" timestamp not null default current_timestamp, - "updater" varchar(64) default '', - "update_time" timestamp not null default current_timestamp, - "deleted" bit not null default false, - "tenant_id" bigint not null default '0', - primary key ("id") -) COMMENT 'API 访问日志表'; - -CREATE TABLE IF NOT EXISTS "inf_api_error_log" ( - "id" bigint not null GENERATED BY DEFAULT AS IDENTITY, - "trace_id" varchar(64) not null, - "user_id" bigint not null default '0', - "user_type" tinyint not null default '0', - "application_name" varchar(50) not null, - "request_method" varchar(16) not null, - "request_url" varchar(255) not null, - "request_params" varchar(8000) not null, - "user_ip" varchar(50) not null, - "user_agent" varchar(512) not null, - "exception_time" timestamp not null, - "exception_name" varchar(128) not null default '', - "exception_message" clob not null, - "exception_root_cause_message" clob not null, - "exception_stack_trace" clob not null, - "exception_class_name" varchar(512) not null, - "exception_file_name" varchar(512) not null, - "exception_method_name" varchar(512) not null, - "exception_line_number" integer not null, - "process_status" tinyint not null, - "process_time" timestamp default null, - "process_user_id" bigint default '0', - "creator" varchar(64) default '', - "create_time" timestamp not null default current_timestamp, - "updater" varchar(64) default '', - "update_time" timestamp not null default current_timestamp, - "deleted" bit not null default false, - "tenant_id" bigint not null default '0', - primary key ("id") -) COMMENT '系统异常日志'; - CREATE TABLE IF NOT EXISTS "system_sms_channel" ( "id" bigint NOT NULL GENERATED BY DEFAULT AS IDENTITY, "signature" varchar(10) NOT NULL, @@ -377,6 +319,24 @@ CREATE TABLE IF NOT EXISTS "system_sms_log" ( PRIMARY KEY ("id") ) COMMENT '短信日志'; +CREATE TABLE IF NOT EXISTS "system_sms_code" ( + "id" bigint NOT NULL GENERATED BY DEFAULT AS IDENTITY, + "mobile" varchar(11) NOT NULL, + "code" varchar(11) NOT NULL, + "scene" bigint NOT NULL, + "create_ip" varchar NOT NULL, + "today_index" int NOT NULL, + "used" bit NOT NULL DEFAULT FALSE, + "used_time" timestamp DEFAULT NULL, + "used_ip" varchar NULL, + "creator" varchar(64) DEFAULT '', + "create_time" timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updater" varchar(64) DEFAULT '', + "update_time" timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + "deleted" bit NOT NULL DEFAULT FALSE, + PRIMARY KEY ("id") +) COMMENT '短信日志'; + CREATE TABLE IF NOT EXISTS "system_error_code" ( "id" bigint NOT NULL GENERATED BY DEFAULT AS IDENTITY, "type" tinyint NOT NULL DEFAULT '0', diff --git a/yudao-server/pom.xml b/yudao-server/pom.xml index 0d4eceb29..546eff421 100644 --- a/yudao-server/pom.xml +++ b/yudao-server/pom.xml @@ -41,19 +41,19 @@ yudao-spring-boot-starter-biz-error-code - - - cn.iocoder.boot - yudao-module-visualization-biz - ${revision} - - + + + + + + + - + cn.iocoder.boot yudao-module-pay-biz @@ -112,7 +112,7 @@ org.springframework.boot spring-boot-maven-plugin - 2.7.7 + 2.7.8 true diff --git a/yudao-ui-admin/src/api/mp/user.js b/yudao-ui-admin/src/api/mp/mpuser.js similarity index 100% rename from yudao-ui-admin/src/api/mp/user.js rename to yudao-ui-admin/src/api/mp/mpuser.js diff --git a/yudao-ui-admin/src/components/bpmnProcessDesigner/package/penal/form/ElementForm.vue b/yudao-ui-admin/src/components/bpmnProcessDesigner/package/penal/form/ElementForm.vue index fc7dbb341..43668e71e 100644 --- a/yudao-ui-admin/src/components/bpmnProcessDesigner/package/penal/form/ElementForm.vue +++ b/yudao-ui-admin/src/components/bpmnProcessDesigner/package/penal/form/ElementForm.vue @@ -21,7 +21,7 @@ -