Require approval for student profile changes
This commit is contained in:
1 parent
a0d56561c5
commit
6c2cefd348
15 files changed
+13599
-25
No files matched your search
@@ -0,0 +1,106 @@
|
||||
using System.Text.Json;
|
||||
using Jiaowu.Api.Domain.Academic;
|
||||
using Jiaowu.Api.Domain.Identity;
|
||||
using Jiaowu.Api.Infrastructure.Auth;
|
||||
using Jiaowu.Api.Infrastructure.Caching;
|
||||
using Jiaowu.Api.Infrastructure.Persistence;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Jiaowu.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
[Route("api/student-identity-changes")]
|
||||
public sealed class StudentIdentityChangesController(AppDbContext db, ICurrentUserDataScope scope, IAppCache cache) : ControllerBase
|
||||
{
|
||||
private const string Managers = SystemRoles.SuperAdmin + "," + SystemRoles.AcademicAdmin + "," + SystemRoles.CollegeAdmin;
|
||||
|
||||
[HttpGet("mine")]
|
||||
[Authorize(Roles = SystemRoles.Student)]
|
||||
public async Task<IActionResult> Mine(CancellationToken ct)
|
||||
{
|
||||
var items = await db.StudentIdentityChanges.AsNoTracking()
|
||||
.Where(x => x.Student!.UserId == scope.Current.UserId)
|
||||
.OrderByDescending(x => x.CreatedAt).Take(50).ToListAsync(ct);
|
||||
return Ok(items.Select(Format));
|
||||
}
|
||||
|
||||
[HttpGet("pending")]
|
||||
[Authorize(Roles = Managers)]
|
||||
public async Task<IActionResult> Pending(CancellationToken ct)
|
||||
{
|
||||
var current = scope.Current;
|
||||
var query = db.StudentIdentityChanges.AsNoTracking().Include(x => x.Student)!
|
||||
.ThenInclude(x => x!.AdministrativeClass)!.ThenInclude(x => x!.Major)
|
||||
.Where(x => x.Status == ApprovalStatus.Submitted);
|
||||
if (current.Scope != DataScope.All)
|
||||
{
|
||||
if (current.Scope != DataScope.College || current.RestrictedCollegeId is null) return Forbid();
|
||||
query = query.Where(x => x.Student!.AdministrativeClass!.Major!.CollegeId == current.RestrictedCollegeId);
|
||||
}
|
||||
var items = await query.OrderBy(x => x.CreatedAt).Take(200).ToListAsync(ct);
|
||||
return Ok(items.Select(x => new { x.Id, x.CreatedAt, studentName = x.Student!.Name,
|
||||
studentNumber = x.Student.StudentNumber, className = x.Student.AdministrativeClass!.Name,
|
||||
changes = Parse(x.ChangesJson) }));
|
||||
}
|
||||
|
||||
[HttpPost("{id:guid}/review")]
|
||||
[Authorize(Roles = Managers)]
|
||||
public async Task<IActionResult> Review(Guid id, IdentityReviewRequest request, CancellationToken ct)
|
||||
{
|
||||
if (!request.Approved && string.IsNullOrWhiteSpace(request.Comment))
|
||||
return BadRequest(new { message = "驳回时请填写审核意见。" });
|
||||
var item = await db.StudentIdentityChanges.Include(x => x.Student)!
|
||||
.ThenInclude(x => x!.AdministrativeClass)!.ThenInclude(x => x!.Major)
|
||||
.SingleOrDefaultAsync(x => x.Id == id, ct);
|
||||
if (item is null) return NotFound();
|
||||
if (!scope.Current.CanAccessCollege(item.Student!.AdministrativeClass!.Major!.CollegeId)) return Forbid();
|
||||
if (item.Status != ApprovalStatus.Submitted) return Conflict(new { message = "申请已处理。" });
|
||||
var student = item.Student;
|
||||
if (request.Approved)
|
||||
{
|
||||
if (student.IsArchived) return Conflict(new { message = "学生档案已归档,无法通过申请。" });
|
||||
var changes = Parse(item.ChangesJson);
|
||||
var current = IdentitySnapshot.FromStudent(student);
|
||||
var values = new Dictionary<string, string?> {
|
||||
["Gender"] = current.Gender.ToString(), ["DateOfBirth"] = current.DateOfBirth?.ToString("yyyy-MM-dd"),
|
||||
["IdCardNumber"] = current.IdCardNumber, ["Nationality"] = current.Nationality,
|
||||
["Ethnicity"] = current.Ethnicity, ["PoliticalStatus"] = current.PoliticalStatus, ["NativePlace"] = current.NativePlace,
|
||||
["SpecialTags"] = current.SpecialTags, ["SpecialNeeds"] = current.SpecialNeeds
|
||||
};
|
||||
if (changes.Any(x => !values.TryGetValue(x.Field, out var value) || value != x.OldValue))
|
||||
return Conflict(new { message = "档案中的相关信息已发生变化,请驳回后由学生重新提交。" });
|
||||
foreach (var change in changes)
|
||||
switch (change.Field)
|
||||
{
|
||||
case "Gender": student.Gender = Enum.Parse<Gender>(change.NewValue!); break;
|
||||
case "DateOfBirth": student.DateOfBirth = change.NewValue is null ? null : DateOnly.ParseExact(change.NewValue, "yyyy-MM-dd"); break;
|
||||
case "IdCardNumber": student.IdCardNumber = change.NewValue; break;
|
||||
case "Nationality": student.Nationality = change.NewValue; break;
|
||||
case "Ethnicity": student.Ethnicity = change.NewValue; break;
|
||||
case "PoliticalStatus": student.PoliticalStatus = change.NewValue; break;
|
||||
case "NativePlace": student.NativePlace = change.NewValue; break;
|
||||
case "SpecialTags": student.SpecialTags = change.NewValue; break;
|
||||
case "SpecialNeeds": student.SpecialNeeds = change.NewValue; break;
|
||||
default: return Conflict(new { message = "申请包含未知字段,无法审核。" });
|
||||
}
|
||||
}
|
||||
item.Status = request.Approved ? ApprovalStatus.Approved : ApprovalStatus.Rejected;
|
||||
item.PendingSlot = null;
|
||||
item.ReviewComment = request.Comment?.Trim();
|
||||
item.ReviewedAt = DateTime.UtcNow;
|
||||
item.ReviewedByUserId = scope.Current.UserId;
|
||||
try { await db.SaveChangesAsync(ct); }
|
||||
catch (DbUpdateConcurrencyException) { return Conflict(new { message = "申请或档案已发生变化,请刷新后重试。" }); }
|
||||
if (request.Approved) await cache.RemoveByTagAsync(AppCacheTags.Analytics, ct);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
private static List<IdentityValueChange> Parse(string json) => JsonSerializer.Deserialize<List<IdentityValueChange>>(json) ?? [];
|
||||
private static object Format(StudentIdentityChange item) => new { item.Id, item.CreatedAt, item.Status,
|
||||
item.ReviewComment, item.ReviewedAt, changes = Parse(item.ChangesJson) };
|
||||
}
|
||||
|
||||
public sealed record IdentityReviewRequest(bool Approved, [property: System.ComponentModel.DataAnnotations.MaxLength(1000)] string? Comment);
|
||||
@@ -1,4 +1,5 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Text.Json;
|
||||
using Jiaowu.Api.Domain.Academic;
|
||||
using Jiaowu.Api.Domain.Identity;
|
||||
using Jiaowu.Api.Infrastructure.Auth;
|
||||
@@ -83,6 +84,7 @@ public sealed class StudentProfileController(
|
||||
x => x.UserId == userId,
|
||||
cancellationToken);
|
||||
if (student is null) return NotFound();
|
||||
if (!Enum.IsDefined(request.Gender)) return BadRequest(new { message = "性别无效。" });
|
||||
if (student.IsArchived)
|
||||
return Conflict(new ProblemDetails
|
||||
{
|
||||
@@ -91,14 +93,22 @@ public sealed class StudentProfileController(
|
||||
Status = StatusCodes.Status409Conflict
|
||||
});
|
||||
|
||||
student.Gender = request.Gender;
|
||||
student.DateOfBirth = request.DateOfBirth;
|
||||
var before = IdentitySnapshot.FromStudent(student);
|
||||
var after = new IdentitySnapshot(request.Gender, request.DateOfBirth,
|
||||
Normalize(request.IdCardNumber), Normalize(request.Nationality), Normalize(request.Ethnicity),
|
||||
Normalize(request.PoliticalStatus), Normalize(request.NativePlace), NormalizeTags(request.SpecialTags, student.SpecialTags), Normalize(request.SpecialNeeds));
|
||||
var changes = IdentityChangeSet.Create(before, after);
|
||||
if (changes.Count > 0)
|
||||
{
|
||||
if (await db.StudentIdentityChanges.AnyAsync(x => x.StudentId == student.Id && x.PendingSlot == "pending", cancellationToken))
|
||||
return Conflict(new { message = "已有个人信息修改申请正在审核,请等待处理。" });
|
||||
db.StudentIdentityChanges.Add(new StudentIdentityChange
|
||||
{
|
||||
StudentId = student.Id,
|
||||
ChangesJson = JsonSerializer.Serialize(changes)
|
||||
});
|
||||
}
|
||||
student.EnglishName = Normalize(request.EnglishName);
|
||||
student.IdCardNumber = Normalize(request.IdCardNumber);
|
||||
student.Nationality = Normalize(request.Nationality);
|
||||
student.Ethnicity = Normalize(request.Ethnicity);
|
||||
student.PoliticalStatus = Normalize(request.PoliticalStatus);
|
||||
student.NativePlace = Normalize(request.NativePlace);
|
||||
student.HouseholdAddress = Normalize(request.HouseholdAddress);
|
||||
student.CurrentAddress = Normalize(request.CurrentAddress);
|
||||
student.PostalCode = Normalize(request.PostalCode);
|
||||
@@ -110,17 +120,55 @@ public sealed class StudentProfileController(
|
||||
student.EmergencyContactRelationship = Normalize(
|
||||
request.EmergencyContactRelationship);
|
||||
student.EmergencyContactPhone = Normalize(request.EmergencyContactPhone);
|
||||
student.SpecialTags = Normalize(request.SpecialTags);
|
||||
student.SpecialNeeds = Normalize(request.SpecialNeeds);
|
||||
student.Biography = Normalize(request.Biography);
|
||||
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
try { await db.SaveChangesAsync(cancellationToken); }
|
||||
catch (DbUpdateConcurrencyException) { return Conflict(new { message = "档案已变更,请刷新后重试。" }); }
|
||||
catch (DbUpdateException) when (changes.Count > 0)
|
||||
{
|
||||
if (await db.StudentIdentityChanges.AsNoTracking().AnyAsync(x => x.StudentId == student.Id && x.PendingSlot == "pending", cancellationToken))
|
||||
return Conflict(new { message = "已有个人信息修改申请正在审核,请等待处理。" });
|
||||
throw;
|
||||
}
|
||||
await cache.RemoveByTagAsync(AppCacheTags.Analytics, cancellationToken);
|
||||
return NoContent();
|
||||
return Ok(new { approvalSubmitted = changes.Count > 0 });
|
||||
}
|
||||
|
||||
private static string? Normalize(string? value) =>
|
||||
string.IsNullOrWhiteSpace(value) ? null : value.Trim();
|
||||
|
||||
private static string? NormalizeTags(string? requested, string? existing)
|
||||
{
|
||||
static string[] Split(string? value) => (value ?? "").Split([',', ',', ';', ';', '、'], StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);
|
||||
return Split(requested).SequenceEqual(Split(existing)) ? existing : Normalize(requested);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record IdentityValueChange(string Field, string? OldValue, string? NewValue);
|
||||
public sealed record IdentitySnapshot(Gender Gender, DateOnly? DateOfBirth, string? IdCardNumber,
|
||||
string? Nationality, string? Ethnicity, string? PoliticalStatus, string? NativePlace, string? SpecialTags, string? SpecialNeeds)
|
||||
{
|
||||
public static IdentitySnapshot FromStudent(Student s) => new(s.Gender, s.DateOfBirth, s.IdCardNumber,
|
||||
s.Nationality, s.Ethnicity, s.PoliticalStatus, s.NativePlace, s.SpecialTags, s.SpecialNeeds);
|
||||
}
|
||||
public static class IdentityChangeSet
|
||||
{
|
||||
public static List<IdentityValueChange> Create(IdentitySnapshot before, IdentitySnapshot after)
|
||||
{
|
||||
var result = new List<IdentityValueChange>();
|
||||
void Add(string field, string? oldValue, string? newValue)
|
||||
{ if (oldValue != newValue) result.Add(new(field, oldValue, newValue)); }
|
||||
Add("Gender", before.Gender.ToString(), after.Gender.ToString());
|
||||
Add("DateOfBirth", before.DateOfBirth?.ToString("yyyy-MM-dd"), after.DateOfBirth?.ToString("yyyy-MM-dd"));
|
||||
Add("IdCardNumber", before.IdCardNumber, after.IdCardNumber);
|
||||
Add("Nationality", before.Nationality, after.Nationality);
|
||||
Add("Ethnicity", before.Ethnicity, after.Ethnicity);
|
||||
Add("PoliticalStatus", before.PoliticalStatus, after.PoliticalStatus);
|
||||
Add("NativePlace", before.NativePlace, after.NativePlace);
|
||||
Add("SpecialTags", before.SpecialTags, after.SpecialTags);
|
||||
Add("SpecialNeeds", before.SpecialNeeds, after.SpecialNeeds);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record StudentProfileDto(
|
||||
|
||||
@@ -2,6 +2,18 @@ using Jiaowu.Api.Domain.Common;
|
||||
|
||||
namespace Jiaowu.Api.Domain.Academic;
|
||||
|
||||
public sealed class StudentIdentityChange : EntityBase
|
||||
{
|
||||
public Guid StudentId { get; set; }
|
||||
public Student? Student { get; set; }
|
||||
public required string ChangesJson { get; set; }
|
||||
public ApprovalStatus Status { get; set; } = ApprovalStatus.Submitted;
|
||||
public string? PendingSlot { get; set; } = "pending";
|
||||
public string? ReviewComment { get; set; }
|
||||
public Guid? ReviewedByUserId { get; set; }
|
||||
public DateTime? ReviewedAt { get; set; }
|
||||
}
|
||||
|
||||
public sealed class StudentLeave : EntityBase
|
||||
{
|
||||
public Guid StudentId { get; set; }
|
||||
|
||||
Loaded 3 of 15 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user