VppAuditHelper.java 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package com.usky.vpp.util;
  2. import com.usky.common.security.utils.SecurityUtils;
  3. import org.springframework.util.StringUtils;
  4. import java.lang.reflect.Method;
  5. import java.time.LocalDateTime;
  6. import java.util.UUID;
  7. /**
  8. * VPP 审计与编号工具
  9. */
  10. public final class VppAuditHelper {
  11. public static final int NOT_DELETED = 0;
  12. public static final int DELETED = 1;
  13. private VppAuditHelper() {
  14. }
  15. public static void fillCreate(Object entity) {
  16. LocalDateTime now = LocalDateTime.now();
  17. invokeSetter(entity, "setCreateTime", now);
  18. invokeSetter(entity, "setUpdateTime", now);
  19. invokeSetter(entity, "setDeleteFlag", NOT_DELETED);
  20. String auditUser = currentUsername();
  21. if (StringUtils.hasText(auditUser)) {
  22. invokeSetter(entity, "setCreatedBy", auditUser);
  23. invokeSetter(entity, "setUpdatedBy", auditUser);
  24. }
  25. Integer tenantId = currentTenantId();
  26. if (tenantId != null) {
  27. invokeSetter(entity, "setTenantId", tenantId);
  28. }
  29. }
  30. public static void fillUpdate(Object entity) {
  31. invokeSetter(entity, "setUpdateTime", LocalDateTime.now());
  32. String auditUser = currentUsername();
  33. if (StringUtils.hasText(auditUser)) {
  34. invokeSetter(entity, "setUpdatedBy", auditUser);
  35. }
  36. }
  37. public static void fillSoftDelete(Object entity) {
  38. invokeSetter(entity, "setDeleteFlag", DELETED);
  39. invokeSetter(entity, "setDeletedAt", LocalDateTime.now());
  40. fillUpdate(entity);
  41. }
  42. public static boolean isDeleted(Integer deleteFlag) {
  43. return deleteFlag != null && deleteFlag == DELETED;
  44. }
  45. public static String nextApplyNo() {
  46. return "ACC" + System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 4).toUpperCase();
  47. }
  48. private static String currentUsername() {
  49. try {
  50. return SecurityUtils.getUsername();
  51. } catch (Exception ex) {
  52. return null;
  53. }
  54. }
  55. private static Integer currentTenantId() {
  56. try {
  57. return SecurityUtils.getTenantId();
  58. } catch (Exception ex) {
  59. return null;
  60. }
  61. }
  62. private static void invokeSetter(Object entity, String method, Object value) {
  63. try {
  64. Method m = entity.getClass().getMethod(method, value.getClass());
  65. m.invoke(entity, value);
  66. } catch (Exception ignored) {
  67. // 部分实体无审计字段时忽略
  68. }
  69. }
  70. }