This commit is contained in:
2020-05-07 21:40:55 +00:00
parent a40cda4043
commit a12065e8f3
7 changed files with 156 additions and 56 deletions

View File

@@ -15,6 +15,7 @@ todo: check attachment NOTES property is actually supported
todo: search tables in schema, I think there is a missing index here, need to look at the search query section again as it was changed several times from the original schema creation todo: search tables in schema, I think there is a missing index here, need to look at the search query section again as it was changed several times from the original schema creation
API REFACTORING (note: workordercontroller / biz should be following all these rules so it's the template if need reference) API REFACTORING (note: workordercontroller / biz should be following all these rules so it's the template if need reference)
todo: all api route parameters, post object sb "newObject", put="updatedObject" todo: all api route parameters, post object sb "newObject", put="updatedObject"
IN BIZ TOO IN BIZ TOO
@@ -29,6 +30,8 @@ todo: Routes should check rights *BEFORE* they fetch the object, not after, all
This is out of order as it triggers a db call even if they have no rights to do it This is out of order as it triggers a db call even if they have no rights to do it
todo: all biz objects "ExistsAsync" is this required / necessary? todo: all biz objects "ExistsAsync" is this required / necessary?
todo: log failed todo: log failed
- Download attempts with wrong key - Download attempts with wrong key
- Add delay for failed download - Add delay for failed download

View File

@@ -164,6 +164,7 @@ namespace AyaNova.Api.Controllers
[HttpPut("{id}")] [HttpPut("{id}")]
public async Task<IActionResult> PutWorkOrder([FromRoute] long id, [FromBody] WorkOrder updatedObject) public async Task<IActionResult> PutWorkOrder([FromRoute] long id, [FromBody] WorkOrder updatedObject)
{ {
return StatusCode(501);
if (!serverState.IsOpen) if (!serverState.IsOpen)
return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason)); return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));
@@ -173,26 +174,25 @@ namespace AyaNova.Api.Controllers
//Instantiate the business object handler //Instantiate the business object handler
WorkOrderBiz biz = WorkOrderBiz.GetBiz(ct, HttpContext); WorkOrderBiz biz = WorkOrderBiz.GetBiz(ct, HttpContext);
var o = await biz.GetAsync(id, false);
if (o == null)
return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND));
if (!Authorized.HasModifyRole(HttpContext.Items, biz.BizType)) if (!Authorized.HasModifyRole(HttpContext.Items, biz.BizType))
return StatusCode(403, new ApiNotAuthorizedResponse()); return StatusCode(403, new ApiNotAuthorizedResponse());
try //todo: handle concurrency in biz object, what to do?
{
if (!await biz.PutAsync(o, updatedObject)) // var o = await biz.PutAsync(id, updatedObject);
return BadRequest(new ApiErrorResponse(biz.Errors)); // try
} // {
catch (DbUpdateConcurrencyException) // if (o == null)
{ // return BadRequest(new ApiErrorResponse(biz.Errors));
if (!await biz.ExistsAsync(id)) // }
return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND)); // catch (DbUpdateConcurrencyException)
else // {
return StatusCode(409, new ApiErrorResponse(ApiErrorCode.CONCURRENCY_CONFLICT)); // if (!await biz.ExistsAsync(id))
} // return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND));
return Ok(ApiOkResponse.Response(new { ConcurrencyToken = o.ConcurrencyToken }, true)); // else
// return StatusCode(409, new ApiErrorResponse(ApiErrorCode.CONCURRENCY_CONFLICT));
// }
// return Ok(ApiOkResponse.Response(new { ConcurrencyToken = o.ConcurrencyToken }, true));
} }
@@ -277,13 +277,13 @@ namespace AyaNova.Api.Controllers
if (!ModelState.IsValid) if (!ModelState.IsValid)
return BadRequest(new ApiErrorResponse(ModelState)); return BadRequest(new ApiErrorResponse(ModelState));
// //Create and validate //Create and validate
// WorkOrderItem o = await biz.CreateAsync(newObject); WorkOrderItem o = await biz.CreateItemAsync(newObject);
// if (o == null) if (o == null)
// return BadRequest(new ApiErrorResponse(biz.Errors)); return BadRequest(new ApiErrorResponse(biz.Errors));
// else else
// return CreatedAtAction(nameof(WorkOrderController.GetWorkOrder), new { id = o.Id, version = apiVersion.ToString() }, new ApiCreatedResponse(o)); return CreatedAtAction(nameof(WorkOrderController.GetWorkOrderItem), new { id = o.Id, version = apiVersion.ToString() }, new ApiCreatedResponse(o));
return StatusCode(501);
} }

View File

@@ -31,11 +31,11 @@ namespace AyaNova.Biz
return new WorkOrderBiz(ct, 1, ServerBootConfig.AYANOVA_DEFAULT_TRANSLATION_ID, AuthorizationRoles.BizAdminFull); return new WorkOrderBiz(ct, 1, ServerBootConfig.AYANOVA_DEFAULT_TRANSLATION_ID, AuthorizationRoles.BizAdminFull);
} }
#region Workorder level
//////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////
//EXISTS //EXISTS
internal async Task<bool> ExistsAsync(long id) internal async Task<bool> WorkOrderExistsAsync(long id)
{ {
return await ct.WorkOrder.AnyAsync(e => e.Id == id); return await ct.WorkOrder.AnyAsync(e => e.Id == id);
} }
@@ -68,7 +68,7 @@ namespace AyaNova.Biz
// //
internal async Task<WorkOrder> DuplicateAsync(long id) internal async Task<WorkOrder> DuplicateAsync(long id)
{ {
WorkOrder dbObject = await ct.WorkOrder.FirstOrDefaultAsync(m => m.Id == id); WorkOrder dbObject = await GetAsync(id, false);
if (dbObject == null) if (dbObject == null)
{ {
AddError(ApiErrorCode.NOT_FOUND, "id"); AddError(ApiErrorCode.NOT_FOUND, "id");
@@ -113,42 +113,65 @@ namespace AyaNova.Biz
//////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////
//UPDATE //UPDATE
// //
internal async Task<WorkOrder> PutAsync(long id, WorkOrder putObj)
//put
internal async Task<bool> PutAsync(WorkOrder dbObj, WorkOrder putObj)
{ {
//TODO: THIS IS ALL WRONG, NEEDS TO HANDLE DESCENDENTS WITH TAGS AND SUCH
//IDEALLY IT SHOULD CALL THE OTHER METHODS TO HANDLE THEM INDIVIDUALLY
//OR...SHOULD IT ONLY EVER HANDLE THE TOP LEVEL....hmmm....
//I guess it would work if it traversed the input workorder and did each bit individually
WorkOrder dbObject = await GetAsync(id, false);
if (dbObject == null)
{
AddError(ApiErrorCode.NOT_FOUND, "id");
return null;
}
// make a snapshot of the original for validation but update the original to preserve workflow // make a snapshot of the original for validation but update the original to preserve workflow
WorkOrder SnapshotOfOriginalDBObj = new WorkOrder(); WorkOrder SnapshotOfOriginalDBObj = new WorkOrder();
CopyObject.Copy(dbObj, SnapshotOfOriginalDBObj); CopyObject.Copy(dbObject, SnapshotOfOriginalDBObj);
//Replace the db object with the PUT object //Replace the db object with the PUT object
CopyObject.Copy(putObj, dbObj, "Id,Serial"); CopyObject.Copy(putObj, dbObject, "Id,Serial");
//if user has rights then change it, otherwise just ignore it and do the rest //if user has rights then change it, otherwise just ignore it and do the rest
if (SnapshotOfOriginalDBObj.Serial != putObj.Serial && Authorized.HasAnyRole(CurrentUserRoles, RolesAllowedToChangeSerial)) if (SnapshotOfOriginalDBObj.Serial != putObj.Serial && Authorized.HasAnyRole(CurrentUserRoles, RolesAllowedToChangeSerial))
{ {
dbObj.Serial = putObj.Serial; dbObject.Serial = putObj.Serial;
} }
dbObj.Tags = TagUtil.NormalizeTags(dbObj.Tags); dbObject.Tags = TagUtil.NormalizeTags(dbObject.Tags);
dbObj.CustomFields = JsonUtil.CompactJson(dbObj.CustomFields); dbObject.CustomFields = JsonUtil.CompactJson(dbObject.CustomFields);
//Set "original" value of concurrency token to input token //Set "original" value of concurrency token to input token
//this will allow EF to check it out //this will allow EF to check it out
ct.Entry(dbObj).OriginalValues["ConcurrencyToken"] = putObj.ConcurrencyToken; ct.Entry(dbObject).OriginalValues["ConcurrencyToken"] = putObj.ConcurrencyToken;
await ValidateAsync(dbObj, SnapshotOfOriginalDBObj); await ValidateAsync(dbObject, SnapshotOfOriginalDBObj);
if (HasErrors) if (HasErrors)
return false; return null;
// try
// {
// if (o==null)
// return BadRequest(new ApiErrorResponse(biz.Errors));
// }
// catch (DbUpdateConcurrencyException)
// {
// if (!await biz.ExistsAsync(id))
// return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND));
// else
// return StatusCode(409, new ApiErrorResponse(ApiErrorCode.CONCURRENCY_CONFLICT));
// }
//Log event and save context //Log event and save context
await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserId, dbObj.Id, BizType, AyaEvent.Modified), ct); await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserId, dbObject.Id, BizType, AyaEvent.Modified), ct);
await SearchIndexAsync(dbObj, false); await SearchIndexAsync(dbObject, false);
await TagUtil.ProcessUpdateTagsInRepositoryAsync(ct, dbObj.Tags, SnapshotOfOriginalDBObj.Tags); await TagUtil.ProcessUpdateTagsInRepositoryAsync(ct, dbObject.Tags, SnapshotOfOriginalDBObj.Tags);
return true; return dbObject;
} }
@@ -196,7 +219,6 @@ namespace AyaNova.Biz
} }
//////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////
//VALIDATION //VALIDATION
// //
@@ -248,6 +270,88 @@ namespace AyaNova.Biz
// { // {
// //whatever needs to be check to delete this object // //whatever needs to be check to delete this object
// } // }
#endregion workorder level
#region WorkOrderItem level
////////////////////////////////////////////////////////////////////////////////////////////////
//CREATE
//
internal async Task<WorkOrder> CreateItemAsync(WorkOrderItem newObject)
{
await ValidateAsync(newObject, null);
if (HasErrors)
return null;
else
{
newObject.Serial = ServerBootConfig.WORKORDER_SERIAL.GetNext();
newObject.Tags = TagUtil.NormalizeTags(newObject.Tags);
newObject.CustomFields = JsonUtil.CompactJson(newObject.CustomFields);
await ct.WorkOrder.AddAsync(newObject);
await ct.SaveChangesAsync();
await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserId, newObject.Id, BizType, AyaEvent.Created), ct);
await SearchIndexAsync(newObject, true);
await TagUtil.ProcessUpdateTagsInRepositoryAsync(ct, newObject.Tags, null);
return newObject;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////
//VALIDATION
//
//Can save or update?
private async Task ValidateItemAsync(WorkOrderItem proposedObj, WorkOrderItem currentObj)
{
//run validation and biz rules
bool isNew = currentObj == null;
// //Name required
// if (string.IsNullOrWhiteSpace(proposedObj.Name))
// AddError(ApiErrorCode.VALIDATION_REQUIRED, "Name");
// //Name must be less than 255 characters
// if (proposedObj.Name.Length > 255)
// AddError(ApiErrorCode.VALIDATION_LENGTH_EXCEEDED, "Name", "255 max");
// //If name is otherwise OK, check that name is unique
// if (!PropertyHasErrors("Name"))
// {
// //Use Any command is efficient way to check existance, it doesn't return the record, just a true or false
// if (await ct.WorkOrder.AnyAsync(m => m.Name == proposedObj.Name && m.Id != proposedObj.Id))
// {
// AddError(ApiErrorCode.VALIDATION_NOT_UNIQUE, "Name");
// }
// }
//Any form customizations to validate?
var FormCustomization = await ct.FormCustom.AsNoTracking().SingleOrDefaultAsync(x => x.FormKey == AyaType.WorkOrder.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);
}
}
//Can delete?
// private void ValidateCanDelete(WorkOrder inObj)
// {
// //whatever needs to be check to delete this object
// }
#endregion work order item level

View File

@@ -13,9 +13,6 @@ namespace AyaNova.Models
public long Id { get; set; } public long Id { get; set; }
public uint ConcurrencyToken { get; set; } public uint ConcurrencyToken { get; set; }
[Required]
public string Name { get; set; }
public bool Active { get; set; }
public string Notes { get; set; } public string Notes { get; set; }
public string Wiki { get; set; } public string Wiki { get; set; }
public string CustomFields { get; set; } public string CustomFields { get; set; }

View File

@@ -13,9 +13,7 @@ namespace AyaNova.Models
public long Id { get; set; } public long Id { get; set; }
public uint ConcurrencyToken { get; set; } public uint ConcurrencyToken { get; set; }
[Required]
public string Name { get; set; }
public bool Active { get; set; }
public string Notes { get; set; } public string Notes { get; set; }
public string Wiki { get; set; } public string Wiki { get; set; }
public string CustomFields { get; set; } public string CustomFields { get; set; }

View File

@@ -13,9 +13,7 @@ namespace AyaNova.Models
public long Id { get; set; } public long Id { get; set; }
public uint ConcurrencyToken { get; set; } public uint ConcurrencyToken { get; set; }
[Required]
public string Name { get; set; }
public bool Active { get; set; }
public string Notes { get; set; } public string Notes { get; set; }
public string Wiki { get; set; } public string Wiki { get; set; }
public string CustomFields { get; set; } public string CustomFields { get; set; }

View File

@@ -390,19 +390,19 @@ namespace AyaNova.Util
await ExecQueryAsync("CREATE INDEX aworkorder_tags ON aworkorder using GIN(tags)"); await ExecQueryAsync("CREATE INDEX aworkorder_tags ON aworkorder using GIN(tags)");
//WORKORDERITEM //WORKORDERITEM
await ExecQueryAsync("CREATE TABLE aworkorderitem (id BIGSERIAL PRIMARY KEY, workorderid bigint not null REFERENCES aworkorder (id), name varchar(255) not null unique, active bool, " + await ExecQueryAsync("CREATE TABLE aworkorderitem (id BIGSERIAL PRIMARY KEY, workorderid bigint not null REFERENCES aworkorder (id), " +
"notes text NULL, wiki text null, customfields text NULL, tags varchar(255) ARRAY NULL)"); "notes text NULL, wiki text null, customfields text NULL, tags varchar(255) ARRAY NULL)");
await ExecQueryAsync("CREATE UNIQUE INDEX aworkorderitem_name_id_idx ON aworkorderitem (id, name);"); await ExecQueryAsync("CREATE UNIQUE INDEX aworkorderitem_name_id_idx ON aworkorderitem (id, name);");
await ExecQueryAsync("CREATE INDEX aworkorderitem_tags ON aworkorderitem using GIN(tags)"); await ExecQueryAsync("CREATE INDEX aworkorderitem_tags ON aworkorderitem using GIN(tags)");
//WORKORDERITEMPART //WORKORDERITEMPART
await ExecQueryAsync("CREATE TABLE aworkorderitempart (id BIGSERIAL PRIMARY KEY, workorderitemid bigint not null REFERENCES aworkorderitem (id), name varchar(255) not null unique, active bool, " + await ExecQueryAsync("CREATE TABLE aworkorderitempart (id BIGSERIAL PRIMARY KEY, workorderitemid bigint not null REFERENCES aworkorderitem (id), " +
"notes text NULL, wiki text null, customfields text NULL, tags varchar(255) ARRAY NULL)"); "notes text NULL, wiki text null, customfields text NULL, tags varchar(255) ARRAY NULL)");
await ExecQueryAsync("CREATE UNIQUE INDEX aworkorderitempart_name_id_idx ON aworkorderitempart (id, name);"); await ExecQueryAsync("CREATE UNIQUE INDEX aworkorderitempart_name_id_idx ON aworkorderitempart (id, name);");
await ExecQueryAsync("CREATE INDEX aworkorderitempart_tags ON aworkorderitempart using GIN(tags)"); await ExecQueryAsync("CREATE INDEX aworkorderitempart_tags ON aworkorderitempart using GIN(tags)");
//WORKORDERITEMLABOR //WORKORDERITEMLABOR
await ExecQueryAsync("CREATE TABLE aworkorderitemlabor (id BIGSERIAL PRIMARY KEY, workorderitemid bigint not null REFERENCES aworkorderitem (id), name varchar(255) not null unique, active bool, " + await ExecQueryAsync("CREATE TABLE aworkorderitemlabor (id BIGSERIAL PRIMARY KEY, workorderitemid bigint not null REFERENCES aworkorderitem (id), " +
"notes text NULL, wiki text null, customfields text NULL, tags varchar(255) ARRAY NULL)"); "notes text NULL, wiki text null, customfields text NULL, tags varchar(255) ARRAY NULL)");
await ExecQueryAsync("CREATE UNIQUE INDEX aworkorderitemlabor_name_id_idx ON aworkorderitemlabor (id, name);"); await ExecQueryAsync("CREATE UNIQUE INDEX aworkorderitemlabor_name_id_idx ON aworkorderitemlabor (id, name);");
await ExecQueryAsync("CREATE INDEX aworkorderitemlabor_tags ON aworkorderitemlabor using GIN(tags)"); await ExecQueryAsync("CREATE INDEX aworkorderitemlabor_tags ON aworkorderitemlabor using GIN(tags)");