สร้าง api อัพเอกสาร

This commit is contained in:
Kittapath 2023-03-31 15:01:40 +07:00
parent 3ff5a4fa46
commit 15e4d21a6f
13 changed files with 3037 additions and 5 deletions

View file

@ -1,4 +1,5 @@
using BMA.EHR.Core;
// using BMA.EHR.Core;
using BMA.EHR.Recurit.Exam.Service.Core;
using BMA.EHR.Recurit.Exam.Service.Request;
using BMA.EHR.Recurit.Exam.Service.Response;
using BMA.EHR.Recurit.Exam.Service.Services;
@ -13,20 +14,23 @@ namespace BMA.EHR.Recurit.Exam.Service.Controllers
[ApiController]
[Produces("application/json")]
[Authorize]
[SwaggerTag("จัดการข้อมูลศาสนา เพื่อนำไปใช้งานในระบบ")]
[SwaggerTag("จัดการข้อมูลสมัครสอบ เพื่อนำไปใช้งานในระบบ")]
public class CandidateController : BaseController
{
#region " Fields "
private readonly CandidateService _candidateService;
private readonly MinIOService _minioService;
#endregion
#region " Constructor and Destructor "
public CandidateController(CandidateService candidateService)
public CandidateController(CandidateService candidateService,
MinIOService minioService)
{
_candidateService = candidateService;
_minioService = minioService;
}
#endregion
@ -713,6 +717,95 @@ namespace BMA.EHR.Recurit.Exam.Service.Controllers
}
}
/// <summary>
/// อัปเอกสารหลักฐาน
/// </summary>
/// <param name="examId">รหัสรอบสมัคร</param>
/// <returns></returns>
/// <response code="200">เมื่ออัปเอกสารหลักฐานสำเร็จ</response>
/// <response code="401">ไม่ได้ Login เข้าระบบ</response>
/// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
[HttpPut("upload/{examId:length(36)}"), DisableRequestSizeLimit]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<ActionResult<ResponseObject>> CreateFileCandidateService(string examId)
{
try
{
if (Request.Form.Files == null || Request.Form.Files.Count == 0)
{
return Error(GlobalMessages.NoFileToUpload);
}
var file = Request.Form.Files[0];
await _candidateService.UpdateAsyncDocument(examId, file);
return Success();
}
catch (Exception ex)
{
return Error(ex);
}
}
/// <summary>
/// ลบเอกสารหลักฐาน
/// </summary>
/// <param name="documentId">รหัสไฟล์เอกสาร</param>
/// <returns></returns>
/// <response code="200">เมื่อลบเอกสารหลักฐานสำเร็จ</response>
/// <response code="401">ไม่ได้ Login เข้าระบบ</response>
/// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
[HttpDelete("upload/{examId:length(36)}"), DisableRequestSizeLimit]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<ActionResult<ResponseObject>> DeleteFileCandidateService(string documentId)
{
try
{
await _candidateService.DeleteAsyncDocument(documentId);
return Success();
}
catch (Exception ex)
{
return Error(ex);
}
}
/// <summary>
/// โหลดไฟล์
/// </summary>
/// <param name="examId">รหัสรอบสมัคร</param>
/// <returns></returns>
/// <response code="200">เมื่อโหลดไฟล์สำเร็จ</response>
/// <response code="401">ไม่ได้ Login เข้าระบบ</response>
/// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
[HttpGet("download/{id:length(36)}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<ActionResult<ResponseObject>> DownloadFile(Guid id)
{
try
{
var file_data = await _minioService.DownloadFileAsync(id);
Response.Headers["Content-Disposition"] = $"inline; filename={file_data.FileName}";
var ret = new FileContentResult(file_data.FileContent, file_data.FileType)
{
FileDownloadName = file_data.FileName
};
return ret;
}
catch (Exception ex)
{
return Error(ex);
}
}
#endregion
}
}

View file

@ -12,7 +12,7 @@ namespace BMA.EHR.Recurit.Exam.Service.Controllers
[ApiController]
[Produces("application/json")]
[Authorize]
[SwaggerTag("จัดการข้อมูลคำนำหน้า เพื่อนำไปใช้งานในระบบ")]
[SwaggerTag("จัดการข้อมูลรอบการสอบ เพื่อนำไปใช้งานในระบบ")]
public class PeriodExamController : BaseController
{
#region " Fields "

View file

@ -2,6 +2,7 @@
{
public class GlobalMessages
{
public const string Success = "Success";
public const string FileNotFoundOnServer = "ไม่พบไฟล์ในระบบ!!";
public const string CannotInsertToDatabase = "ไม่สามารถบันทึกลงฐานข้อมูลได้!!";
public const string InvalidRequestParam = "Request parameter ไม่ถูกต้อง!!";

View file

@ -38,6 +38,7 @@ namespace BMA.EHR.Recurit.Exam.Service.Data
public DbSet<Education> Educations { get; set; }
public DbSet<Document> Documents { get; set; }
public DbSet<CandidateDocument> CandidateDocuments { get; set; }
}
}

View file

@ -235,6 +235,9 @@ namespace BMA.EHR.Recurit.Exam.Service.Data.Migrations
.HasColumnType("longtext")
.HasComment("ประเภทอาชีพที่ทำงานมาก่อน");
b.Property<Guid?>("PaymentImgId")
.HasColumnType("char(36)");
b.Property<Guid>("PeriodExamId")
.HasColumnType("char(36)");
@ -312,6 +315,8 @@ namespace BMA.EHR.Recurit.Exam.Service.Data.Migrations
b.HasIndex("MotherPrefixId");
b.HasIndex("PaymentImgId");
b.HasIndex("PeriodExamId");
b.HasIndex("PrefixId");
@ -329,6 +334,68 @@ namespace BMA.EHR.Recurit.Exam.Service.Data.Migrations
b.ToTable("Candidates");
});
modelBuilder.Entity("BMA.EHR.Recurit.Exam.Service.Models.CandidateDocument", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)")
.HasColumnOrder(0)
.HasComment("PrimaryKey")
.HasAnnotation("Relational:JsonPropertyName", "id");
b.Property<Guid>("CandidateId")
.HasColumnType("char(36)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)")
.HasColumnOrder(100)
.HasComment("สร้างข้อมูลเมื่อ");
b.Property<string>("CreatedFullName")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("varchar(200)")
.HasColumnOrder(104)
.HasComment("ชื่อ User ที่สร้างข้อมูล");
b.Property<string>("CreatedUserId")
.IsRequired()
.HasMaxLength(40)
.HasColumnType("varchar(40)")
.HasColumnOrder(101)
.HasComment("User Id ที่สร้างข้อมูล");
b.Property<Guid>("DocumentId")
.HasColumnType("char(36)");
b.Property<string>("LastUpdateFullName")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("varchar(200)")
.HasColumnOrder(105)
.HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด");
b.Property<string>("LastUpdateUserId")
.IsRequired()
.HasMaxLength(40)
.HasColumnType("varchar(40)")
.HasColumnOrder(103)
.HasComment("User Id ที่แก้ไขข้อมูลล่าสุด");
b.Property<DateTime?>("LastUpdatedAt")
.HasColumnType("datetime(6)")
.HasColumnOrder(102)
.HasComment("แก้ไขข้อมูลล่าสุดเมื่อ");
b.HasKey("Id");
b.HasIndex("CandidateId");
b.HasIndex("DocumentId");
b.ToTable("CandidateDocuments");
});
modelBuilder.Entity("BMA.EHR.Recurit.Exam.Service.Models.Career", b =>
{
b.Property<Guid>("Id")
@ -1138,6 +1205,10 @@ namespace BMA.EHR.Recurit.Exam.Service.Data.Migrations
.WithMany()
.HasForeignKey("MotherPrefixId");
b.HasOne("BMA.EHR.Recurit.Exam.Service.Models.Documents.Document", "PaymentImg")
.WithMany()
.HasForeignKey("PaymentImgId");
b.HasOne("BMA.EHR.Recurit.Exam.Service.Models.PeriodExam", "PeriodExam")
.WithMany()
.HasForeignKey("PeriodExamId")
@ -1184,6 +1255,8 @@ namespace BMA.EHR.Recurit.Exam.Service.Data.Migrations
b.Navigation("MotherPrefix");
b.Navigation("PaymentImg");
b.Navigation("PeriodExam");
b.Navigation("Prefix");
@ -1199,6 +1272,25 @@ namespace BMA.EHR.Recurit.Exam.Service.Data.Migrations
b.Navigation("Relationship");
});
modelBuilder.Entity("BMA.EHR.Recurit.Exam.Service.Models.CandidateDocument", b =>
{
b.HasOne("BMA.EHR.Recurit.Exam.Service.Models.Candidate", "Candidate")
.WithMany()
.HasForeignKey("CandidateId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("BMA.EHR.Recurit.Exam.Service.Models.Documents.Document", "Document")
.WithMany()
.HasForeignKey("DocumentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Candidate");
b.Navigation("Document");
});
modelBuilder.Entity("BMA.EHR.Recurit.Exam.Service.Models.Career", b =>
{
b.HasOne("BMA.EHR.Recurit.Exam.Service.Models.Candidate", "Candidate")

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,50 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace BMA.EHR.Recurit.Exam.Service.Migrations
{
/// <inheritdoc />
public partial class addtablecandidateDoc : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<Guid>(
name: "PaymentImgId",
table: "Candidates",
type: "char(36)",
nullable: true,
collation: "ascii_general_ci");
migrationBuilder.CreateIndex(
name: "IX_Candidates_PaymentImgId",
table: "Candidates",
column: "PaymentImgId");
migrationBuilder.AddForeignKey(
name: "FK_Candidates_Documents_PaymentImgId",
table: "Candidates",
column: "PaymentImgId",
principalTable: "Documents",
principalColumn: "Id");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Candidates_Documents_PaymentImgId",
table: "Candidates");
migrationBuilder.DropIndex(
name: "IX_Candidates_PaymentImgId",
table: "Candidates");
migrationBuilder.DropColumn(
name: "PaymentImgId",
table: "Candidates");
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,68 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace BMA.EHR.Recurit.Exam.Service.Migrations
{
/// <inheritdoc />
public partial class addtablecandidateDoc2 : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "CandidateDocuments",
columns: table => new
{
Id = table.Column<Guid>(type: "char(36)", nullable: false, comment: "PrimaryKey", collation: "ascii_general_ci"),
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false, comment: "สร้างข้อมูลเมื่อ"),
CreatedUserId = table.Column<string>(type: "varchar(40)", maxLength: 40, nullable: false, comment: "User Id ที่สร้างข้อมูล")
.Annotation("MySql:CharSet", "utf8mb4"),
LastUpdatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: true, comment: "แก้ไขข้อมูลล่าสุดเมื่อ"),
LastUpdateUserId = table.Column<string>(type: "varchar(40)", maxLength: 40, nullable: false, comment: "User Id ที่แก้ไขข้อมูลล่าสุด")
.Annotation("MySql:CharSet", "utf8mb4"),
CreatedFullName = table.Column<string>(type: "varchar(200)", maxLength: 200, nullable: false, comment: "ชื่อ User ที่สร้างข้อมูล")
.Annotation("MySql:CharSet", "utf8mb4"),
LastUpdateFullName = table.Column<string>(type: "varchar(200)", maxLength: 200, nullable: false, comment: "ชื่อ User ที่แก้ไขข้อมูลล่าสุด")
.Annotation("MySql:CharSet", "utf8mb4"),
CandidateId = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci"),
DocumentId = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci")
},
constraints: table =>
{
table.PrimaryKey("PK_CandidateDocuments", x => x.Id);
table.ForeignKey(
name: "FK_CandidateDocuments_Candidates_CandidateId",
column: x => x.CandidateId,
principalTable: "Candidates",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_CandidateDocuments_Documents_DocumentId",
column: x => x.DocumentId,
principalTable: "Documents",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
})
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateIndex(
name: "IX_CandidateDocuments_CandidateId",
table: "CandidateDocuments",
column: "CandidateId");
migrationBuilder.CreateIndex(
name: "IX_CandidateDocuments_DocumentId",
table: "CandidateDocuments",
column: "DocumentId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "CandidateDocuments");
}
}
}

View file

@ -22,6 +22,9 @@ namespace BMA.EHR.Recurit.Exam.Service.Models
[Comment("Id รูปโปรไฟล์")]
public virtual Document? ProfileImg { get; set; }
[Comment("Id หลักฐานชำระเงิน")]
public virtual Document? PaymentImg { get; set; }
[Comment("คำนำหน้าชื่อ")]

View file

@ -0,0 +1,15 @@
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using BMA.EHR.Recurit.Exam.Service.Models.Documents;
namespace BMA.EHR.Recurit.Exam.Service.Models
{
public class CandidateDocument : EntityBase
{
[Required, Comment("Id ผู้สมัครสอบ")]
public virtual Candidate? Candidate { get; set; }
[Required, Comment("Id ไฟล์เอกสาร")]
public virtual Document? Document { get; set; }
}
}

View file

@ -0,0 +1,11 @@
namespace BMA.EHR.Recurit.Exam.Service.Responses.Document
{
public class FileListResponse
{
public string FileName { get; set; } = string.Empty;
public string FileType { get; set; } = string.Empty;
public int FileSize { get; set; }
}
}

View file

@ -4,6 +4,8 @@ using BMA.EHR.Recurit.Exam.Service.Data;
using BMA.EHR.Recurit.Exam.Service.Models;
using BMA.EHR.Recurit.Exam.Service.Request;
using BMA.EHR.Recurit.Exam.Service.Response;
using BMA.EHR.Recurit.Exam.Service.Responses.Document;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace BMA.EHR.Recurit.Exam.Service.Services
@ -14,16 +16,19 @@ namespace BMA.EHR.Recurit.Exam.Service.Services
private readonly ApplicationDbContext _context;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly MinIOService _minioService;
#endregion
#region " Constructor and Destructor "
public CandidateService(ApplicationDbContext context,
IHttpContextAccessor httpContextAccessor)
IHttpContextAccessor httpContextAccessor,
MinIOService minioService)
{
_context = context;
_httpContextAccessor = httpContextAccessor;
_minioService = minioService;
}
#endregion
@ -221,6 +226,28 @@ namespace BMA.EHR.Recurit.Exam.Service.Services
.ToListAsync();
}
public async Task<IEnumerable<FileListResponse?>> GetsAsyncFileUpload(string examId)
{
var exam = await _context.PeriodExams.AsQueryable()
.FirstOrDefaultAsync(x => x.Id == Guid.Parse(examId));
if (exam == null)
throw new Exception(GlobalMessages.ExamNotFound);
var candidate = await _context.Candidates.AsQueryable()
.FirstOrDefaultAsync(x => x.PeriodExam == exam && x.UserId == UserId);
return await _context.CandidateDocuments.AsQueryable()
.Where(x => x.Candidate == candidate)
.Select(x => new FileListResponse
{
FileName = x.Document == null ? "" : x.Document.FileName,
FileType = x.Document == null ? "" : x.Document.FileType,
FileSize = x.Document == null ? 0 : x.Document.FileSize,
})
.ToListAsync(); ;
}
public async Task<bool> GetsAsyncRegisterExam(string examId)
{
var exam = await _context.PeriodExams.AsQueryable()
@ -679,6 +706,44 @@ namespace BMA.EHR.Recurit.Exam.Service.Services
await _context.SaveChangesAsync();
}
public async Task UpdateAsyncDocument(string examId, IFormFile file)
{
var candidateId = await CreateAsyncCandidate(examId);
var candidate = await _context.Candidates.AsQueryable()
.FirstOrDefaultAsync(x => x.Id == Guid.Parse(candidateId));
if (candidate == null)
throw new Exception(GlobalMessages.ExamNotFound);
var doc = await _minioService.UploadFileAsync(file);
var document = await _context.Documents.AsQueryable()
.FirstOrDefaultAsync(x => x.Id == doc.Id);
var candidateDocument = new CandidateDocument
{
Candidate = candidate,
Document = document,
};
await _context.CandidateDocuments.AddAsync(candidateDocument);
await _context.SaveChangesAsync();
}
public async Task DeleteAsyncDocument(string documentId)
{
var document = await _context.Documents.AsQueryable()
.FirstOrDefaultAsync(x => x.Id == Guid.Parse(documentId));
if (document == null)
throw new Exception(GlobalMessages.FileNotFoundOnServer);
_context.Documents.Remove(document);
await _context.SaveChangesAsync();
}
public async Task CreateAsyncCareer(string examId, CandidateCareerResponseItem updated)
{
var candidateId = await CreateAsyncCandidate(examId);