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