aaa0214dad606a8d650f5188d7d8b2a1a8857406
[institute/sw-backend.git] /
1 package com.supwisdom.institute.backend.base.domain.repo;
2
3 import java.util.ArrayList;
4 import java.util.List;
5 import java.util.Map;
6
7 import javax.persistence.criteria.CriteriaBuilder;
8 import javax.persistence.criteria.CriteriaQuery;
9 import javax.persistence.criteria.Predicate;
10 import javax.persistence.criteria.Root;
11 import javax.transaction.Transactional;
12
13 import org.springframework.data.domain.Example;
14 import org.springframework.data.domain.ExampleMatcher;
15 import org.springframework.data.domain.Page;
16 import org.springframework.data.domain.PageRequest;
17 import org.springframework.data.domain.Sort;
18 import org.springframework.data.jpa.domain.Specification;
19 import org.springframework.data.jpa.repository.Modifying;
20 import org.springframework.data.jpa.repository.Query;
21 import org.springframework.data.repository.query.Param;
22 import org.springframework.stereotype.Repository;
23 import org.springframework.util.StringUtils;
24
25 import com.supwisdom.institute.backend.base.domain.entity.Permission;
26 import com.supwisdom.institute.backend.common.framework.repo.BaseJpaRepository;
27 import com.supwisdom.institute.backend.common.util.MapBeanUtils;
28
29 @Repository
30 @Transactional
31 public interface PermissionRepository extends BaseJpaRepository<Permission> {
32   
33
34   @Override
35   public default Specification<Permission> convertToSpec(Map<String, Object> mapBean) {
36     
37     Specification<Permission> spec = new Specification<Permission>() {
38
39       /**
40        * 
41        */
42       private static final long serialVersionUID = 6195601104797641573L;
43
44       @Override
45       public Predicate toPredicate(Root<Permission> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
46         List<Predicate> predicates = new ArrayList<>();
47         
48         if (mapBean != null) {
49
50           if (MapBeanUtils.getBoolean(mapBean, "deleted") != null) {
51             predicates.add(criteriaBuilder.equal(root.get("deleted"), MapBeanUtils.getBoolean(mapBean, "deleted")));
52           }
53           
54           if (!StringUtils.isEmpty(MapBeanUtils.getString(mapBean, "code"))) {
55             predicates.add(criteriaBuilder.like(root.get("code"), "%" + MapBeanUtils.getString(mapBean, "code") + "%"));
56           }
57           if (!StringUtils.isEmpty(MapBeanUtils.getString(mapBean, "name"))) {
58             predicates.add(criteriaBuilder.like(root.get("name"), "%" + MapBeanUtils.getString(mapBean, "name") + "%"));
59           }
60           
61           if (!StringUtils.isEmpty(MapBeanUtils.getString(mapBean, "status"))) {
62             predicates.add(criteriaBuilder.equal(root.get("status"), MapBeanUtils.getString(mapBean, "status")));
63           }
64           
65           if (!StringUtils.isEmpty(MapBeanUtils.getString(mapBean, "type"))) {
66             predicates.add(criteriaBuilder.equal(root.get("type"), MapBeanUtils.getString(mapBean, "type")));
67           }
68           
69           if (!StringUtils.isEmpty(MapBeanUtils.getString(mapBean, "url"))) {
70             predicates.add(criteriaBuilder.like(root.get("url"), "%" + MapBeanUtils.getString(mapBean, "url") + "%"));
71           }
72
73           if (!StringUtils.isEmpty(MapBeanUtils.getString(mapBean, "applicationId"))) {
74             predicates.add(criteriaBuilder.equal(root.get("applicationId"), MapBeanUtils.getString(mapBean, "applicationId")));
75           }
76
77           if (!StringUtils.isEmpty(MapBeanUtils.getString(mapBean, "parentId"))) {
78             predicates.add(criteriaBuilder.equal(root.get("parentId"), MapBeanUtils.getString(mapBean, "parentId")));
79           }
80
81 //          if (!StringUtils.isEmpty(MapBeanUtils.getString(mapBean, "grantTimeBegin"))) {
82 //            String grantTimeBegin = MapBeanUtils.getString(mapBean, "grantTimeBegin");
83 //            Date d = DateUtil.parseDate(grantTimeBegin+" 00:00:00", "yyyy-MM-dd HH:mm:ss");
84 //            
85 //            if (d != null) {
86 //              predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("grantTime"), d));
87 //            }
88 //          }
89 //
90 //          if (!StringUtils.isEmpty(MapBeanUtils.getString(mapBean, "grantTimeEnd"))) {
91 //            String grantTimeEnd = MapBeanUtils.getString(mapBean, "grantTimeEnd");
92 //            Date d = DateUtil.parseDate(grantTimeEnd+" 23:59:59", "yyyy-MM-dd HH:mm:ss");
93 //            
94 //            if (d != null) {
95 //              predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("grantTime"), d));
96 //            }
97 //          }
98
99           List<Predicate> predicatesKeyword = new ArrayList<>();
100           if (!StringUtils.isEmpty(MapBeanUtils.getString(mapBean, "keyword"))) {
101             predicatesKeyword.add(criteriaBuilder.like(root.get("code"), "%" + MapBeanUtils.getString(mapBean, "keyword") + "%"));
102             predicatesKeyword.add(criteriaBuilder.like(root.get("name"), "%" + MapBeanUtils.getString(mapBean, "keyword") + "%"));
103             predicatesKeyword.add(criteriaBuilder.like(root.get("memo"), "%" + MapBeanUtils.getString(mapBean, "keyword") + "%"));
104             
105             predicates.add(criteriaBuilder.or(predicatesKeyword.toArray(new Predicate[predicatesKeyword.size()])));
106           }
107         }
108         
109         return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
110       }
111       
112     };
113     
114     return spec;
115   }
116   
117   @Override
118   public default Page<Permission> selectPageList(boolean loadAll, int pageIndex, int pageSize, Map<String, Object> mapBean, Map<String, String> orderBy) {
119     if (loadAll) {
120       pageIndex = 0;
121       pageSize = Integer.MAX_VALUE;
122     }
123     
124     Permission probe = new Permission();
125     if (mapBean != null) {
126       probe.setDeleted(MapBeanUtils.getBoolean(mapBean, "deleted"));
127       probe.setCode(MapBeanUtils.getString(mapBean, "code"));
128       probe.setName(MapBeanUtils.getString(mapBean, "name"));
129       probe.setMemo(MapBeanUtils.getString(mapBean, "memo"));
130       probe.setStatus(MapBeanUtils.getString(mapBean, "status"));
131       probe.setType(MapBeanUtils.getString(mapBean, "type"));
132     }
133     
134     ExampleMatcher matcher = ExampleMatcher.matching()
135         .withMatcher("deleted", ExampleMatcher.GenericPropertyMatchers.exact())
136         .withMatcher("code", ExampleMatcher.GenericPropertyMatchers.contains())
137         .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains())
138         .withMatcher("memo", ExampleMatcher.GenericPropertyMatchers.contains())
139         .withMatcher("status", ExampleMatcher.GenericPropertyMatchers.exact())
140         .withMatcher("type", ExampleMatcher.GenericPropertyMatchers.exact());
141     
142     PageRequest pageRequest = PageRequest.of(pageIndex, pageSize);
143     Example<Permission> example = Example.of(probe, matcher);
144     
145     Page<Permission> page = this.findAll(example, pageRequest);
146     
147     return page;
148   }
149   
150   
151   
152   @Query(value = "select max(p.rgt) from Permission p")
153   public int selectMaxRgt();
154   
155   @Query(value = "select p from Permission p where p.lft>:lft and p.rgt<:rgt order by p.lft")
156   public List<Permission> selectBetweenLftRgt(@Param("lft") int lft, @Param("rgt") int rgt);
157   
158   @Modifying
159   @Query(value = "update TB_BASE_PERMISSION "
160       + "set "
161       + "  LFT = (case when LFT >= :rgt then LFT + :offset else LFT end), "
162       + "  RGT = RGT + :offset "
163       + "where RGT >= :rgt", nativeQuery = true)
164   public int updateLftRgtWhenInsert(@Param("rgt") int rgt, @Param("offset") int offset);
165
166   @Modifying
167   @Query(value = "update TB_BASE_PERMISSION "
168       + "set "
169       + "  LFT = (case when LFT >= :rgt then LFT - :offset else LFT end), "
170       + "  RGT = RGT - :offset "
171       + "where RGT >= :rgt", nativeQuery = true)
172   public int updateLftRgtWhenDelete(@Param("rgt") int rgt, @Param("offset") int offset);
173   
174   
175   @Override
176   public default Permission insert(Permission entity) {
177
178     if (entity.getParentId() == null) {
179       entity.setParentId(Permission.ROOT_PARENT_ID);
180     }
181
182     if (entity.getParentId() == null || entity.getParentId().isEmpty() || Permission.ROOT_PARENT_ID.equals(entity.getParentId())) {
183       int maxRgt = selectMaxRgt();
184       entity.setLft((maxRgt+1));
185       entity.setRgt((maxRgt+1) + 1);
186       
187       entity.setLevel(1);
188     } else {
189       Permission parentEntity = this.selectById(entity.getParentId());
190       if (parentEntity == null) {
191         throw new RuntimeException(String.format("父级对象不存在!"));
192       } else {
193         // 将 lft或rgt 大于等于父级对象 rgt 的记录的 lft、rgt +offset
194         int rgt = parentEntity.getRgt();
195         int offset = 2;
196         updateLftRgtWhenInsert(rgt, offset);
197         
198         entity.setLft(rgt);
199         entity.setRgt(rgt + 1);
200         
201         entity.setLevel(parentEntity.getLevel() + 1);
202       }
203     }
204     
205     return BaseJpaRepository.super.insert(entity);
206   }
207   
208   @Override
209   public default Permission update(Permission entity) {
210
211     Permission originEntity = this.selectById(entity.getId());
212     if (originEntity == null) {
213       return null;
214     }
215     
216     //if (!this.checkFieldExists("code", entity.getCode(), entity.getId())) {
217     //  throw new RuntimeException(String.format("代码重复!"));
218     //}
219     
220     if (originEntity.getParentId() == null) {
221       originEntity.setParentId(Permission.ROOT_PARENT_ID);
222     }
223     
224     if (entity.getParentId() == null) {
225       entity.setParentId(Permission.ROOT_PARENT_ID);
226     }
227     
228     if (!originEntity.getParentId().equals(entity.getParentId()) ) {
229
230       int lft = originEntity.getLft();
231       int rgt = originEntity.getRgt();
232       int level = originEntity.getLevel();
233       int offset = rgt - lft +1;
234       
235       List<Permission> childEntities = this.selectBetweenLftRgt(lft, rgt);
236
237       if (entity.getParentId() == null || entity.getParentId().isEmpty() || Permission.ROOT_PARENT_ID.equals(entity.getParentId())) {
238         // 将 lft或rgt 大于等于该对象 rgt 的记录的 lft、rgt -offset
239         updateLftRgtWhenDelete(rgt, offset);
240   
241         int maxRgt = selectMaxRgt();
242         entity.setLft((maxRgt+1));
243         entity.setRgt((maxRgt+1) + 1 +offset-2);
244         
245         entity.setLevel(1);
246       } else {
247         // 将 lft或rgt 大于等于该对象 rgt 的记录的 lft、rgt -offset
248         updateLftRgtWhenDelete(rgt, offset);
249
250         Permission parentEntity = this.selectById(entity.getParentId());
251         if (parentEntity == null) {
252           throw new RuntimeException(String.format("父级对象不存在!"));
253         }
254         //System.out.println(String.format("pLft %s, pRgt %s", parentEntity.getLft(), parentEntity.getRgt()));
255         if (parentEntity.getLft() >= originEntity.getLft() && parentEntity.getRgt() <= originEntity.getRgt()) {
256           throw new RuntimeException(String.format("不能设置自身或自身的子节点作为父级!"));
257         }
258         
259         //parentEntity = this.selectById(entity.getParentId()); System.out.println(String.format("pLft %s, pRgt %s", parentEntity.getLft(), parentEntity.getRgt()));
260         // 将 lft或rgt 大于等于父级对象 rgt 的记录的 lft、rgt +offset
261         //int pLft = parentEntity.getLft();
262         int pRgt = parentEntity.getRgt();
263         updateLftRgtWhenInsert(pRgt, offset);
264         
265         entity.setLft(pRgt);
266         entity.setRgt(pRgt + 1 + offset-2);
267         
268         entity.setLevel(parentEntity.getLevel() + 1);
269       }
270       
271       int newLft = entity.getLft();
272       int newRgt = entity.getRgt();
273       int newLevel = entity.getLevel();
274       //System.out.println(String.format("newLft %s, newRgt %s, newLevel %s", newLft, newRgt, newLevel));
275       //System.out.println(String.format("lft %s, rgt %s, level %s", lft, rgt, level));
276       for (Permission childEntity : childEntities) {
277         //Permission pEntity = this.selectById(childEntity.getParentId());
278         
279         int cLft = childEntity.getLft();
280         int cRgt = childEntity.getRgt();
281         int cLevel = childEntity.getLevel();
282         
283         childEntity.setLft(cLft + (newLft - lft));
284         childEntity.setRgt(cRgt + (newRgt - rgt));
285         
286         childEntity.setLevel(cLevel + (newLevel - level));
287         
288         BaseJpaRepository.super.update(childEntity);
289       }
290
291     }
292     
293     return BaseJpaRepository.super.update(entity);
294   }
295
296   @Override
297   public default void delete(String id) {
298     
299     Permission originEntity = this.selectById(id);
300     if (originEntity == null) {
301       return;
302     }
303
304     int lft = originEntity.getLft();
305     int rgt = originEntity.getRgt();
306     int offset = rgt - lft +1;
307
308     // FIXME: 判断是否有子节点
309     //if (lft + 1 != rgt) {
310     //  return;
311     //}
312
313     List<Permission> childEntities = this.selectBetweenLftRgt(lft, rgt);
314     for (Permission childEntity : childEntities) {
315       BaseJpaRepository.super.delete(childEntity.getId());
316     }
317     
318     // 将 lft或rgt 大于等于该对象 rgt 的记录的 lft、rgt -offset
319     updateLftRgtWhenDelete(rgt, offset);
320     
321     BaseJpaRepository.super.delete(id);
322   }
323   
324   
325
326
327   public default List<Permission> selectList(boolean loadAll, int pageIndex, int pageSize, Map<String, Object> mapBean, Map<String, String> orderBy) {
328     
329     Specification<Permission> spec = convertToSpec(mapBean);
330     
331     if (loadAll) {
332       pageIndex = 0;
333       pageSize = Integer.MAX_VALUE;
334     }
335     
336     Sort sort = convertToSort(orderBy);
337
338     if (sort == null) {
339       return this.findAll(spec);
340     } else {
341       return this.findAll(spec, sort);
342     }
343   }
344
345   
346
347   @Query(value = "select p from Permission p "
348       + "inner join RolePermission rp on p.id=rp.permissionId "
349       + "inner join Role r on rp.roleId=r.id "
350       + "inner join AccountRole ar on r.id=ar.roleId "
351       + "inner join Account a on ar.accountId=a.id "
352       + "where a.username=:username "
353       + "and p.lft >= :lft and p.rgt <= :rgt "
354       + "and (:type is null or p.type=:type) "
355       + "and p.status='1' and r.status='1' and a.status='1' and a.enabled=1 ")
356   public List<Permission> selectAccountRolePermissionByUsername(@Param("username") String username, @Param("lft") int lft, @Param("rgt") int rgt, @Param("type") String type);
357   
358   @Query(value = "select p from Permission p "
359       + "inner join RolePermission rp on p.id=rp.permissionId "
360       + "inner join Role r on rp.roleId=r.id "
361       + "inner join GroupRole gr on r.id=gr.roleId "
362       + "inner join Group_ g on gr.groupId=g.id "
363       + "inner join AccountGroup ag on g.id=ag.groupId "
364       + "inner join Account a on ag.accountId=a.id "
365       + "where a.username=:username "
366       + "and p.lft >= :lft and p.rgt <= :rgt "
367       + "and (:type is null or p.type=:type) "
368       + "and p.status='1' and r.status='1' and g.status='1' and a.status='1' and a.enabled=1 ")
369   public List<Permission> selectAccountGroupRolePermissionByUsername(@Param("username") String username, @Param("lft") int lft, @Param("rgt") int rgt, @Param("type") String type);
370
371
372   @Query(value = "select p from Permission p "
373       + "inner join RolePermission rp on p.id=rp.permissionId "
374       + "inner join Role r on rp.roleId=r.id "
375       + "inner join AccountRole ar on r.id=ar.roleId "
376       + "inner join Account a on ar.accountId=a.id "
377       + "where a.username=:username "
378       + "and p.applicationId = :applicationId "
379       + "and (:type is null or p.type=:type) "
380       + "and p.status='1' and r.status='1' and a.status='1' and a.enabled=1 ")
381   public List<Permission> selectAccountRolePermissionByUsername(@Param("username") String username, @Param("applicationId") String applicationId, @Param("type") String type);
382   
383   @Query(value = "select p from Permission p "
384       + "inner join RolePermission rp on p.id=rp.permissionId "
385       + "inner join Role r on rp.roleId=r.id "
386       + "inner join GroupRole gr on r.id=gr.roleId "
387       + "inner join Group_ g on gr.groupId=g.id "
388       + "inner join AccountGroup ag on g.id=ag.groupId "
389       + "inner join Account a on ag.accountId=a.id "
390       + "where a.username=:username "
391       + "and p.applicationId = :applicationId "
392       + "and (:type is null or p.type=:type) "
393       + "and p.status='1' and r.status='1' and g.status='1' and a.status='1' and a.enabled=1 ")
394   public List<Permission> selectAccountGroupRolePermissionByUsername(@Param("username") String username, @Param("applicationId") String applicationId, @Param("type") String type);
395
396
397   @Query(value = "select p from Permission p "
398       + "inner join RolePermission rp on p.id=rp.permissionId "
399       + "inner join Role r on rp.roleId=r.id "
400       + "inner join AccountRole ar on r.id=ar.roleId "
401       + "inner join Account a on ar.accountId=a.id "
402       + "where a.username=:username "
403       + "and (:type is null or p.type=:type) "
404       + "and p.status='1' and r.status='1' and a.status='1' and a.enabled=1 ")
405   public List<Permission> selectAccountRolePermissionByUsername(@Param("username") String username, @Param("type") String type);
406   
407   @Query(value = "select p from Permission p "
408       + "inner join RolePermission rp on p.id=rp.permissionId "
409       + "inner join Role r on rp.roleId=r.id "
410       + "inner join GroupRole gr on r.id=gr.roleId "
411       + "inner join Group_ g on gr.groupId=g.id "
412       + "inner join AccountGroup ag on g.id=ag.groupId "
413       + "inner join Account a on ag.accountId=a.id "
414       + "where a.username=:username "
415       + "and (:type is null or p.type=:type) "
416       + "and p.status='1' and r.status='1' and g.status='1' and a.status='1' and a.enabled=1 ")
417   public List<Permission> selectAccountGroupRolePermissionByUsername(@Param("username") String username, @Param("type") String type);
418
419 }