From 3eef1ec0e43f26aa6f3a83b50855dcb55ebc7c54 Mon Sep 17 00:00:00 2001 From: John Cardinal Date: Mon, 23 Nov 2020 20:35:39 +0000 Subject: [PATCH] --- .../Controllers/CustomerNoteController.cs | 137 ++++++++++++ server/AyaNova/biz/CustomerNoteBiz.cs | 210 ++++++++++++++++++ server/AyaNova/models/AyContext.cs | 1 + server/AyaNova/models/CustomerNote.cs | 15 +- server/AyaNova/util/AySchema.cs | 5 +- 5 files changed, 360 insertions(+), 8 deletions(-) create mode 100644 server/AyaNova/Controllers/CustomerNoteController.cs create mode 100644 server/AyaNova/biz/CustomerNoteBiz.cs diff --git a/server/AyaNova/Controllers/CustomerNoteController.cs b/server/AyaNova/Controllers/CustomerNoteController.cs new file mode 100644 index 00000000..7d5e51c3 --- /dev/null +++ b/server/AyaNova/Controllers/CustomerNoteController.cs @@ -0,0 +1,137 @@ +using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Routing; +using Microsoft.AspNetCore.Authorization; +using Microsoft.Extensions.Logging; +using AyaNova.Models; +using AyaNova.Api.ControllerHelpers; +using AyaNova.Biz; + + +namespace AyaNova.Api.Controllers +{ + [ApiController] + [ApiVersion("8.0")] + [Route("api/v{version:apiVersion}/customer-note")] + [Produces("application/json")] + [Authorize] + public class CustomerNoteController : controllerbase + { + private readonly AyContext ct; + private readonly ILogger log; + private readonly ApiServerState serverState; + + /// + /// ctor + /// + /// + /// + /// + public CustomerNoteController(AyContext dbcontext, ILogger logger, ApiServerState apiServerState) + { + ct = dbcontext; + log = logger; + serverState = apiServerState; + } + + /// + /// Create CustomerNote + /// + /// + /// From route path + /// + [HttpPost] + public async Task PostCustomerNote([FromBody] CustomerNote newObject, ApiVersion apiVersion) + { + if (!serverState.IsOpen) + return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason)); + CustomerNoteBiz biz = CustomerNoteBiz.GetBiz(ct, HttpContext); + if (!Authorized.HasCreateRole(HttpContext.Items, biz.BizType)) + return StatusCode(403, new ApiNotAuthorizedResponse()); + if (!ModelState.IsValid) + return BadRequest(new ApiErrorResponse(ModelState)); + CustomerNote o = await biz.CreateAsync(newObject); + if (o == null) + return BadRequest(new ApiErrorResponse(biz.Errors)); + else + return CreatedAtAction(nameof(CustomerNoteController.GetCustomerNote), new { id = o.Id, version = apiVersion.ToString() }, new ApiCreatedResponse(o)); + } + + + + /// + /// Get CustomerNote + /// + /// + /// CustomerNote + [HttpGet("{id}")] + public async Task GetCustomerNote([FromRoute] long id) + { + if (!serverState.IsOpen) + return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason)); + CustomerNoteBiz biz = CustomerNoteBiz.GetBiz(ct, HttpContext); + if (!Authorized.HasReadFullRole(HttpContext.Items, biz.BizType)) + return StatusCode(403, new ApiNotAuthorizedResponse()); + if (!ModelState.IsValid) + return BadRequest(new ApiErrorResponse(ModelState)); + var o = await biz.GetAsync(id); + if (o == null) return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND)); + return Ok(ApiOkResponse.Response(o)); + } + + /// + /// Put (update) CustomerNote + /// + /// + /// + [HttpPut] + public async Task PutCustomerNote([FromBody] CustomerNote updatedObject) + { + if (!serverState.IsOpen) + return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason)); + if (!ModelState.IsValid) + return BadRequest(new ApiErrorResponse(ModelState)); + CustomerNoteBiz biz = CustomerNoteBiz.GetBiz(ct, HttpContext); + if (!Authorized.HasModifyRole(HttpContext.Items, biz.BizType)) + return StatusCode(403, new ApiNotAuthorizedResponse()); + var o = await biz.PutAsync(updatedObject);//In future may need to return entire object, for now just concurrency token + if (o == null) + { + if (biz.Errors.Exists(z => z.Code == ApiErrorCode.CONCURRENCY_CONFLICT)) + return StatusCode(409, new ApiErrorResponse(biz.Errors)); + else + return BadRequest(new ApiErrorResponse(biz.Errors)); + } + return Ok(ApiOkResponse.Response(new { Concurrency = o.Concurrency }));; + } + + /// + /// Delete CustomerNote + /// + /// + /// NoContent + [HttpDelete("{id}")] + public async Task DeleteCustomerNote([FromRoute] long id) + { + if (!serverState.IsOpen) + return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason)); + if (!ModelState.IsValid) + return BadRequest(new ApiErrorResponse(ModelState)); + CustomerNoteBiz biz = CustomerNoteBiz.GetBiz(ct, HttpContext); + if (!Authorized.HasDeleteRole(HttpContext.Items, biz.BizType)) + return StatusCode(403, new ApiNotAuthorizedResponse()); + if (!await biz.DeleteAsync(id)) + return BadRequest(new ApiErrorResponse(biz.Errors)); + return NoContent(); + } + + + + + + //------------ + + + }//eoc +}//eons \ No newline at end of file diff --git a/server/AyaNova/biz/CustomerNoteBiz.cs b/server/AyaNova/biz/CustomerNoteBiz.cs new file mode 100644 index 00000000..2625bd7f --- /dev/null +++ b/server/AyaNova/biz/CustomerNoteBiz.cs @@ -0,0 +1,210 @@ +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using AyaNova.Util; +using AyaNova.Api.ControllerHelpers; +using AyaNova.Models; + +namespace AyaNova.Biz +{ + internal class CustomerNoteBiz : BizObject, ISearchAbleObject + { + internal CustomerNoteBiz(AyContext dbcontext, long currentUserId, long userTranslationId, AuthorizationRoles UserRoles) + { + ct = dbcontext; + UserId = currentUserId; + UserTranslationId = userTranslationId; + CurrentUserRoles = UserRoles; + BizType = AyaType.CustomerNote; + } + + internal static CustomerNoteBiz GetBiz(AyContext ct, Microsoft.AspNetCore.Http.HttpContext httpContext = null) + { + if (httpContext != null) + return new CustomerNoteBiz(ct, UserIdFromContext.Id(httpContext.Items), UserTranslationIdFromContext.Id(httpContext.Items), UserRolesFromContext.Roles(httpContext.Items)); + else + return new CustomerNoteBiz(ct, 1, ServerBootConfig.AYANOVA_DEFAULT_TRANSLATION_ID, AuthorizationRoles.BizAdminFull); + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + //EXISTS + internal async Task ExistsAsync(long id) + { + return await ct.CustomerNote.AnyAsync(z => z.Id == id); + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + //CREATE + // + internal async Task CreateAsync(CustomerNote newObject) + { + //await ValidateAsync(newObject, null); + if (HasErrors) + return null; + else + { + newObject.Tags = TagBiz.NormalizeTags(newObject.Tags); + await ct.CustomerNote.AddAsync(newObject); + await ct.SaveChangesAsync(); + await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserId, newObject.Id, BizType, AyaEvent.Created), ct); + await SearchIndexAsync(newObject, true); + await TagBiz.ProcessUpdateTagsInRepositoryAsync(ct, newObject.Tags, null); + + return newObject; + } + } + + + //////////////////////////////////////////////////////////////////////////////////////////////// + //GET + // + internal async Task GetAsync(long id, bool logTheGetEvent = true) + { + var ret = await ct.CustomerNote.SingleOrDefaultAsync(m => m.Id == id); + if (logTheGetEvent && ret != null) + await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserId, id, BizType, AyaEvent.Retrieved), ct); + return ret; + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + //UPDATE + // + internal async Task PutAsync(CustomerNote putObject) + { + CustomerNote dbObject = await ct.CustomerNote.SingleOrDefaultAsync(m => m.Id == putObject.Id); + if (dbObject == null) + { + AddError(ApiErrorCode.NOT_FOUND, "id"); + return null; + } + CustomerNote SnapshotOfOriginalDBObj = new CustomerNote(); + CopyObject.Copy(dbObject, SnapshotOfOriginalDBObj); + CopyObject.Copy(putObject, dbObject, "Id"); + dbObject.Tags = TagBiz.NormalizeTags(dbObject.Tags); + + ct.Entry(dbObject).OriginalValues["Concurrency"] = putObject.Concurrency; + //await ValidateAsync(dbObject, SnapshotOfOriginalDBObj); + if (HasErrors) return null; + try + { + await ct.SaveChangesAsync(); + } + catch (DbUpdateConcurrencyException) + { + if (!await ExistsAsync(putObject.Id)) + AddError(ApiErrorCode.NOT_FOUND); + else + AddError(ApiErrorCode.CONCURRENCY_CONFLICT); + return null; + } + await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserId, dbObject.Id, BizType, AyaEvent.Modified), ct); + await SearchIndexAsync(dbObject, false); + await TagBiz.ProcessUpdateTagsInRepositoryAsync(ct, dbObject.Tags, SnapshotOfOriginalDBObj.Tags); + return dbObject; + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + //DELETE + // + internal async Task DeleteAsync(long id) + { + using (var transaction = await ct.Database.BeginTransactionAsync()) + { + try + { + CustomerNote dbObject = await ct.CustomerNote.SingleOrDefaultAsync(m => m.Id == id); + // ValidateCanDelete(dbObject); + if (HasErrors) + return false; + if (HasErrors) + return false; + ct.CustomerNote.Remove(dbObject); + await ct.SaveChangesAsync(); + + + await EventLogProcessor.DeleteObjectLogAsync(UserId, BizType, dbObject.Id, "CustomerNote", ct); + await Search.ProcessDeletedObjectKeywordsAsync(dbObject.Id, BizType, ct); + await TagBiz.ProcessDeleteTagsInRepositoryAsync(ct, dbObject.Tags); + await FileUtil.DeleteAttachmentsForObjectAsync(BizType, dbObject.Id, ct); + await transaction.CommitAsync(); + // await NotifyEventProcessor.HandlePotentialNotificationEvent(AyaEvent.Deleted, dbObject); + } + catch + { + //Just re-throw for now, let exception handler deal, but in future may want to deal with this more here + throw; + } + return true; + } + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + //SEARCH + // + private async Task SearchIndexAsync(CustomerNote obj, bool isNew) + { + var SearchParams = new Search.SearchIndexProcessObjectParameters(UserTranslationId, obj.Id, BizType); + SearchParams.AddText(obj.Notes).AddText(obj.Tags); + if (isNew) + await Search.ProcessNewObjectKeywordsAsync(SearchParams); + else + await Search.ProcessUpdatedObjectKeywordsAsync(SearchParams); + } + + public async Task GetSearchResultSummary(long id) + { + var obj = await ct.CustomerNote.SingleOrDefaultAsync(m => m.Id == id); + var SearchParams = new Search.SearchIndexProcessObjectParameters(); + if (obj != null) + SearchParams.AddText(obj.Notes).AddText(obj.Tags); + return SearchParams; + } + + + //////////////////////////////////////////////////////////////////////////////////////////////// + //VALIDATION + // + + // private async Task ValidateAsync(CustomerNote proposedObj, CustomerNote currentObj) + // { + + // // bool isNew = currentObj == null; + + + + + // // //Any form customizations to validate? + // // var FormCustomization = await ct.FormCustom.AsNoTracking().SingleOrDefaultAsync(x => x.FormKey == AyaType.CustomerNote.ToString()); + // // if (FormCustomization != null) + // // { + // // //Yeppers, do the validation, there are two, the custom fields and the regular fields that might be set to required + + // // //validate users choices for required non custom fields + // // RequiredFieldsValidator.Validate(this, FormCustomization, proposedObj); + + // // //validate custom fields + // // CustomFieldsValidator.Validate(this, FormCustomization, proposedObj.CustomFields); + // // } + + // } + + // private void ValidateCanDelete(CustomerNote inObj) + // { + // //whatever needs to be check to delete this object + // } + + + //////////////////////////////////////////////////////////////////////////////////////////////// + //JOB / OPERATIONS + // + + + //Other job handlers here... + + + ///////////////////////////////////////////////////////////////////// + + }//eoc + + +}//eons + diff --git a/server/AyaNova/models/AyContext.cs b/server/AyaNova/models/AyContext.cs index 3db4fd9c..ec7a71d2 100644 --- a/server/AyaNova/models/AyContext.cs +++ b/server/AyaNova/models/AyContext.cs @@ -28,6 +28,7 @@ namespace AyaNova.Models public virtual DbSet PickListTemplate { get; set; } public virtual DbSet License { get; set; } public virtual DbSet Customer { get; set; } + public virtual DbSet CustomerNote { get; set; } public virtual DbSet Contract { get; set; } public virtual DbSet HeadOffice { get; set; } public virtual DbSet LoanUnit { get; set; } diff --git a/server/AyaNova/models/CustomerNote.cs b/server/AyaNova/models/CustomerNote.cs index 446b6b1a..179afaf2 100644 --- a/server/AyaNova/models/CustomerNote.cs +++ b/server/AyaNova/models/CustomerNote.cs @@ -7,17 +7,17 @@ using Newtonsoft.Json; namespace AyaNova.Models { - - - public class CustomerNote + public class CustomerNote { public long Id { get; set; } - public uint Concurrency { get; set; } + public uint Concurrency { get; set; } + [Required] + public long CustomerId { get; set; } [Required] public long UserId { get; set; } [Required] public DateTime NoteDate { get; set; } - public string Notes { get; set; } + public string Notes { get; set; } public List Tags { get; set; } @@ -30,7 +30,10 @@ namespace AyaNova.Models [NotMapped, JsonIgnore] public AyaType AyaType { get => AyaType.CustomerNote; } - [JsonIgnore]//hide from being returned (as null anyway) with User object in routes + [JsonIgnore] + public Customer Customer { get; set; } + + [JsonIgnore] public User User { get; set; } }//eoc diff --git a/server/AyaNova/util/AySchema.cs b/server/AyaNova/util/AySchema.cs index 0438a7c8..2a522a4c 100644 --- a/server/AyaNova/util/AySchema.cs +++ b/server/AyaNova/util/AySchema.cs @@ -22,7 +22,7 @@ namespace AyaNova.Util //!!!!WARNING: BE SURE TO UPDATE THE DbUtil::EmptyBizDataFromDatabaseForSeedingOrImporting WHEN NEW TABLES ADDED!!!! private const int DESIRED_SCHEMA_LEVEL = 15; - internal const long EXPECTED_COLUMN_COUNT = 455; + internal const long EXPECTED_COLUMN_COUNT = 456; internal const long EXPECTED_INDEX_COUNT = 145; //!!!!WARNING: BE SURE TO UPDATE THE DbUtil::EmptyBizDataFromDatabaseForSeedingOrImporting WHEN NEW TABLES ADDED!!!! @@ -494,7 +494,8 @@ $BODY$; //CUSTOMER NOTES await ExecQueryAsync("CREATE TABLE acustomernotes (id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, " + - "userid bigint not null REFERENCES auser(id), startdate timestamp not null, notes text, tags varchar(255) ARRAY )"); + "customerid bigint not null REFERENCES acustomer(id), userid bigint not null REFERENCES auser(id), " + + "startdate timestamp not null, notes text, tags varchar(255) ARRAY )"); //CONTRACT await ExecQueryAsync("CREATE TABLE acontract (id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name text not null unique, active bool, " +