383 lines
14 KiB
C#
383 lines
14 KiB
C#
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.AspNetCore.JsonPatch;
|
|
using EnumsNET;
|
|
using AyaNova.Util;
|
|
using AyaNova.Api.ControllerHelpers;
|
|
using AyaNova.Biz;
|
|
using AyaNova.Models;
|
|
using Newtonsoft.Json.Linq;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
|
|
namespace AyaNova.Biz
|
|
{
|
|
|
|
|
|
internal class UserBiz : BizObject, IJobObject, IImportAyaNova7Object
|
|
{
|
|
private readonly AyContext ct;
|
|
public readonly long userId;
|
|
private readonly AuthorizationRoles userRoles;
|
|
public bool V7ValidationImportMode { get; set; }
|
|
|
|
internal UserBiz(AyContext dbcontext, long currentUserId, AuthorizationRoles UserRoles)
|
|
{
|
|
ct = dbcontext;
|
|
userId = currentUserId;
|
|
userRoles = UserRoles;
|
|
V7ValidationImportMode = false;//default
|
|
}
|
|
|
|
|
|
////////////////////////////////////////////////////////////////////////////////////////////////
|
|
//CREATE
|
|
internal async Task<User> CreateAsync(User inObj)
|
|
{
|
|
Validate(inObj, true);
|
|
if (HasErrors)
|
|
return null;
|
|
else
|
|
{
|
|
//do stuff with User
|
|
User outObj = inObj;
|
|
outObj.OwnerId = userId;
|
|
//SearchHelper(break down text fields, save to db)
|
|
//TagHelper(collection of tags??)
|
|
await ct.User.AddAsync(outObj);
|
|
return outObj;
|
|
|
|
}
|
|
}
|
|
|
|
////////////////////////////////////////////////////////////////////////////////////////////////
|
|
/// GET
|
|
|
|
//Get one
|
|
internal async Task<User> GetAsync(long fetchId)
|
|
{
|
|
//This is simple so nothing more here, but often will be copying to a different output object or some other ops
|
|
return await ct.User.SingleOrDefaultAsync(m => m.Id == fetchId);
|
|
}
|
|
|
|
//get many (paged)
|
|
internal async Task<ApiPagedResponse<User>> GetManyAsync(IUrlHelper Url, string routeName, PagingOptions pagingOptions)
|
|
{
|
|
|
|
pagingOptions.Offset = pagingOptions.Offset ?? PagingOptions.DefaultOffset;
|
|
pagingOptions.Limit = pagingOptions.Limit ?? PagingOptions.DefaultLimit;
|
|
|
|
var items = await ct.User
|
|
.OrderBy(m => m.Id)
|
|
.Skip(pagingOptions.Offset.Value)
|
|
.Take(pagingOptions.Limit.Value)
|
|
.ToArrayAsync();
|
|
|
|
var totalRecordCount = await ct.User.CountAsync();
|
|
var pageLinks = new PaginationLinkBuilder(Url, routeName, null, pagingOptions, totalRecordCount).PagingLinksObject();
|
|
|
|
ApiPagedResponse<User> pr = new ApiPagedResponse<User>(items, pageLinks);
|
|
return pr;
|
|
}
|
|
|
|
|
|
//get picklist (paged)
|
|
internal async Task<ApiPagedResponse<NameIdItem>> GetPickListAsync(IUrlHelper Url, string routeName, PagingOptions pagingOptions, string q)
|
|
{
|
|
pagingOptions.Offset = pagingOptions.Offset ?? PagingOptions.DefaultOffset;
|
|
pagingOptions.Limit = pagingOptions.Limit ?? PagingOptions.DefaultLimit;
|
|
|
|
NameIdItem[] items;
|
|
int totalRecordCount = 0;
|
|
|
|
if (!string.IsNullOrWhiteSpace(q))
|
|
{
|
|
items = await ct.User
|
|
.Where(m => EF.Functions.ILike(m.Name, q))
|
|
.OrderBy(m => m.Name)
|
|
.Skip(pagingOptions.Offset.Value)
|
|
.Take(pagingOptions.Limit.Value)
|
|
.Select(m => new NameIdItem()
|
|
{
|
|
Id = m.Id,
|
|
Name = m.Name
|
|
}).ToArrayAsync();
|
|
|
|
totalRecordCount = await ct.User.Where(m => EF.Functions.ILike(m.Name, q)).CountAsync();
|
|
}
|
|
else
|
|
{
|
|
items = await ct.User
|
|
.OrderBy(m => m.Name)
|
|
.Skip(pagingOptions.Offset.Value)
|
|
.Take(pagingOptions.Limit.Value)
|
|
.Select(m => new NameIdItem()
|
|
{
|
|
Id = m.Id,
|
|
Name = m.Name
|
|
}).ToArrayAsync();
|
|
|
|
totalRecordCount = await ct.User.CountAsync();
|
|
}
|
|
|
|
|
|
|
|
var pageLinks = new PaginationLinkBuilder(Url, routeName, null, pagingOptions, totalRecordCount).PagingLinksObject();
|
|
|
|
ApiPagedResponse<NameIdItem> pr = new ApiPagedResponse<NameIdItem>(items, pageLinks);
|
|
return pr;
|
|
}
|
|
|
|
|
|
|
|
|
|
////////////////////////////////////////////////////////////////////////////////////////////////
|
|
//UPDATE
|
|
//
|
|
|
|
//put
|
|
internal bool Put(User dbObj, User inObj)
|
|
{
|
|
|
|
//Replace the db object with the PUT object
|
|
CopyObject.Copy(inObj, dbObj, "Id");
|
|
//Set "original" value of concurrency token to input token
|
|
//this will allow EF to check it out
|
|
ct.Entry(dbObj).OriginalValues["ConcurrencyToken"] = inObj.ConcurrencyToken;
|
|
|
|
Validate(dbObj, false);
|
|
if (HasErrors)
|
|
return false;
|
|
|
|
return true;
|
|
}
|
|
|
|
//patch
|
|
internal bool Patch(User dbObj, JsonPatchDocument<User> objectPatch, uint concurrencyToken)
|
|
{
|
|
//Do the patching
|
|
objectPatch.ApplyTo(dbObj);
|
|
ct.Entry(dbObj).OriginalValues["ConcurrencyToken"] = concurrencyToken;
|
|
Validate(dbObj, false);
|
|
if (HasErrors)
|
|
return false;
|
|
|
|
return true;
|
|
}
|
|
|
|
|
|
////////////////////////////////////////////////////////////////////////////////////////////////
|
|
//DELETE
|
|
//
|
|
|
|
internal bool Delete(User dbObj)
|
|
{
|
|
//Determine if the object can be deleted, do the deletion tentatively
|
|
//Probably also in here deal with tags and associated search text etc
|
|
|
|
ValidateCanDelete(dbObj);
|
|
if (HasErrors)
|
|
return false;
|
|
ct.User.Remove(dbObj);
|
|
return true;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Delete child objects like tags and attachments and etc
|
|
/// </summary>
|
|
/// <param name="dbObj"></param>
|
|
internal void DeleteChildren(User dbObj)
|
|
{
|
|
//TAGS
|
|
TagMapBiz.DeleteAllForObject(new AyaTypeId(AyaType.User, dbObj.Id), ct);
|
|
}
|
|
|
|
////////////////////////////////////////////////////////////////////////////////////////////////
|
|
//VALIDATION
|
|
//
|
|
|
|
//Can save or update?
|
|
private void Validate(User inObj, bool isNew)
|
|
{
|
|
//run validation and biz rules
|
|
if (isNew)
|
|
{
|
|
//NEW Users must be active
|
|
if (((bool)inObj.Active) == false)
|
|
{
|
|
AddError(ValidationErrorType.InvalidValue, "Active", "New User must be active");
|
|
}
|
|
}
|
|
|
|
//OwnerId required
|
|
if (!isNew)
|
|
{
|
|
if (inObj.OwnerId == 0)
|
|
AddError(ValidationErrorType.RequiredPropertyEmpty, "OwnerId");
|
|
}
|
|
|
|
//Name required
|
|
if (string.IsNullOrWhiteSpace(inObj.Name))
|
|
AddError(ValidationErrorType.RequiredPropertyEmpty, "Name");
|
|
|
|
//Name must be less than 255 characters
|
|
if (inObj.Name.Length > 255)
|
|
AddError(ValidationErrorType.LengthExceeded, "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 (ct.User.Any(m => m.Name == inObj.Name && m.Id != inObj.Id))
|
|
{
|
|
AddError(ValidationErrorType.NotUnique, "Name");
|
|
}
|
|
}
|
|
|
|
|
|
if (!inObj.UserType.IsValid())
|
|
{
|
|
AddError(ValidationErrorType.InvalidValue, "UserType");
|
|
}
|
|
|
|
//Validate client type user
|
|
if (!V7ValidationImportMode && inObj.UserType == UserType.Client)
|
|
{
|
|
if (inObj.ClientId == null || inObj.ClientId == 0)
|
|
{
|
|
AddError(ValidationErrorType.RequiredPropertyEmpty, "ClientId");
|
|
}
|
|
else
|
|
{
|
|
//verify that client exists
|
|
//TODO WHEN CLIENT OBJECT MADE if(!ct.Client.any(m))
|
|
}
|
|
}
|
|
|
|
//Validate headoffice type user
|
|
if (!V7ValidationImportMode && inObj.UserType == UserType.HeadOffice)
|
|
{
|
|
if (inObj.HeadOfficeId == null || inObj.HeadOfficeId == 0)
|
|
{
|
|
AddError(ValidationErrorType.RequiredPropertyEmpty, "HeadOfficeId");
|
|
}
|
|
else
|
|
{
|
|
//verify that HeadOfficeId exists
|
|
//TODO WHEN HEADOFFICE OBJECT MADE if(!ct.HeadOffice.any(m))
|
|
}
|
|
}
|
|
|
|
//Validate headoffice type user
|
|
if (!V7ValidationImportMode && inObj.UserType == UserType.Subcontractor)
|
|
{
|
|
if (inObj.SubVendorId == null || inObj.SubVendorId == 0)
|
|
{
|
|
AddError(ValidationErrorType.RequiredPropertyEmpty, "SubVendorId");
|
|
}
|
|
else
|
|
{
|
|
//verify that VENDOR SubVendorId exists
|
|
//TODO WHEN VENDOR OBJECT MADE if(!ct.Vendor.any(m))
|
|
}
|
|
}
|
|
|
|
if (!inObj.Roles.IsValid())
|
|
{
|
|
AddError(ValidationErrorType.InvalidValue, "Roles");
|
|
}
|
|
|
|
return;
|
|
}
|
|
|
|
|
|
//Can delete?
|
|
private void ValidateCanDelete(User inObj)
|
|
{
|
|
//whatever needs to be check to delete this object
|
|
|
|
}
|
|
|
|
|
|
|
|
////////////////////////////////////////////////////////////////////////////////////////////////
|
|
//JOB / OPERATIONS
|
|
//
|
|
public async Task HandleJobAsync(OpsJob job)
|
|
{
|
|
//just to hide compiler warning for now
|
|
await Task.CompletedTask;
|
|
//Hand off the particular job to the corresponding processing code
|
|
//NOTE: If this code throws an exception the caller (JobsBiz::ProcessJobsAsync) will automatically set the job to failed and log the exeption so
|
|
//basically any error condition during job processing should throw up an exception if it can't be handled
|
|
switch (job.JobType)
|
|
{
|
|
|
|
default:
|
|
throw new System.ArgumentOutOfRangeException($"UserBiz.HandleJob-> Invalid job type{job.JobType.ToString()}");
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task<bool> ImportV7Async(JObject j, List<ImportAyaNova7MapItem> importMap, Guid jobId)
|
|
{
|
|
V7ValidationImportMode = true;
|
|
|
|
//some types need to import from more than one source hence the seemingly redundant switch statement for futureproofing
|
|
switch (j["V7_TYPE"].Value<string>())
|
|
{
|
|
case "GZTW.AyaNova.BLL.User":
|
|
{
|
|
var V7Id = new Guid(j["ID"].Value<string>());
|
|
|
|
//Copy values
|
|
User i=new User();
|
|
i.Name= j["Name"].Value<string>();
|
|
|
|
|
|
User o = await CreateAsync(i);
|
|
if (HasErrors)
|
|
{
|
|
//If there are any validation errors, log in joblog and move on
|
|
JobsBiz.LogJob(jobId, $" -> import object \"{i.Name}\" source id {V7Id.ToString()} failed validation and was not imported: {GetErrorsAsString()} ", ct);
|
|
|
|
//This is a fundamental problem with the import as users are required for many things so bomb out entirely
|
|
//other things might be able to work around but this is too serious
|
|
throw new System.SystemException("UserBiz::ImportV7Async - FATAL ERROR, IMPORT FROM V7 CANNOT CONTINUE WITHOUT ALL USERS BEING IMPORTED, SEE JOB ERROR LOG FOR DETAILS");
|
|
// return false;
|
|
}
|
|
else
|
|
{
|
|
await ct.SaveChangesAsync();
|
|
var mapItem = new ImportAyaNova7MapItem(V7Id, AyaType.User, o.Id);
|
|
//Log
|
|
EventLogProcessor.AddEntry(new Event(userId, o.Id, AyaType.User, AyaEvent.Created), ct);
|
|
await ct.SaveChangesAsync();
|
|
}
|
|
}
|
|
break;
|
|
}
|
|
|
|
//just to hide compiler warning for now
|
|
await Task.CompletedTask;
|
|
//this is the equivalent of returning void for a Task signature with nothing to return
|
|
return true;
|
|
|
|
}
|
|
|
|
//Other job handlers here...
|
|
|
|
|
|
/////////////////////////////////////////////////////////////////////
|
|
|
|
}//eoc
|
|
|
|
|
|
}//eons
|
|
|