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