Files
raven/server/AyaNova/biz/PurchaseOrderBiz.cs

1085 lines
55 KiB
C#

using System;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using AyaNova.Util;
using AyaNova.Api.ControllerHelpers;
using Microsoft.Extensions.Logging;
using AyaNova.Models;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Storage;
namespace AyaNova.Biz
{
internal class PurchaseOrderBiz : BizObject, IJobObject, ISearchAbleObject, IReportAbleObject, IExportAbleObject, INotifiableObject
{
internal PurchaseOrderBiz(AyContext dbcontext, long currentUserId, long userTranslationId, AuthorizationRoles UserRoles)
{
ct = dbcontext;
UserId = currentUserId;
UserTranslationId = userTranslationId;
CurrentUserRoles = UserRoles;
BizType = AyaType.PurchaseOrder;
}
internal static PurchaseOrderBiz GetBiz(AyContext ct, Microsoft.AspNetCore.Http.HttpContext httpContext = null)
{
if (httpContext != null)
return new PurchaseOrderBiz(ct, UserIdFromContext.Id(httpContext.Items), UserTranslationIdFromContext.Id(httpContext.Items), UserRolesFromContext.Roles(httpContext.Items));
else
return new PurchaseOrderBiz(ct, 1, ServerBootConfig.AYANOVA_DEFAULT_TRANSLATION_ID, AuthorizationRoles.BizAdmin);
}
////////////////////////////////////////////////////////////////////////////////////////////////
//EXISTS
internal async Task<bool> ExistsAsync(long id)
{
return await ct.PurchaseOrder.AnyAsync(z => z.Id == id);
}
////////////////////////////////////////////////////////////////////////////////////////////////
//CREATE
//
internal async Task<PurchaseOrder> CreateAsync(PurchaseOrder newObject, bool populateDisplayFields)
{
await ValidateAsync(newObject, null);
if (HasErrors)
return null;
else
{
using (var transaction = await ct.Database.BeginTransactionAsync())
{
newObject.Tags = TagBiz.NormalizeTags(newObject.Tags);
newObject.CustomFields = JsonUtil.CompactJson(newObject.CustomFields);
await ct.PurchaseOrder.AddAsync(newObject);
await ct.SaveChangesAsync();//needs to exist so inventory adjustment accepts it as source id (biz rule checks)
var RequestsToUpdate = await BizActionsAsync(AyaEvent.Created, newObject, null, transaction);
if (HasErrors)
{
await transaction.RollbackAsync();
return null;
}
await ct.SaveChangesAsync();
await UpdateWorkOrderItemPartRequestsAsync(RequestsToUpdate);
await transaction.CommitAsync();
await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserId, newObject.Id, BizType, AyaEvent.Created), ct);
await SearchIndexAsync(newObject, true);
await TagBiz.ProcessUpdateTagsInRepositoryAsync(ct, newObject.Tags, null);
await HandlePotentialNotificationEvent(AyaEvent.Created, newObject);
if (populateDisplayFields)
await PopulateVizFields(newObject, false);
return newObject;
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////
//GET
//
internal async Task<PurchaseOrder> GetAsync(long id, bool populateDisplayFields, bool logTheGetEvent)
{
var ret = await ct.PurchaseOrder.Include(z => z.Items).AsNoTracking().SingleOrDefaultAsync(z => z.Id == id);
if (populateDisplayFields)
await PopulateVizFields(ret, false);
if (logTheGetEvent && ret != null)
await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserId, id, BizType, AyaEvent.Retrieved), ct);
return ret;
}
////////////////////////////////////////////////////////////////////////////////////////////////
//DISPLAY FIELDS
//
private async Task PopulateVizFields(PurchaseOrder po, bool forReporting)
{
//NOTE: This expects to run AFTER bizActions have been performed
if (po == null) return;
//populate server fields for client ui
//Show Warehouses
po.HasSelectableWarehouses = await ct.PartWarehouse.CountAsync() > 1;
//default hidden and show when traverse items if applicable
po.HasPartRequest = false;
po.HasTaxes = false;
po.HasReceipt = false;
po.HasVendorNumber = false;
po.HasUnreceived = false;
if (po.DropShipToCustomerId != null)
{
var pid = po.DropShipToCustomerId;
if (!vc.Has("custname", po.DropShipToCustomerId))
{
var ds = await ct.Customer.AsNoTracking().Where(x => x.Id == pid).FirstOrDefaultAsync();
vc.Add(ds.Name, "custname", pid);
vc.Add(ds.Address, "custaddr", pid);
vc.Add(ds.City, "custcity", pid);
vc.Add(ds.Region, "custregion", pid);
vc.Add(ds.Country, "custcountry", pid);
vc.Add(ds.Latitude.ToString(), "custlat", pid);
vc.Add(ds.Longitude.ToString(), "custlong", pid);
vc.Add(ds.PostAddress, "custpostaddr", pid);
vc.Add(ds.PostCity, "custpostcity", pid);
vc.Add(ds.PostRegion, "custpostregion", pid);
vc.Add(ds.PostCountry, "custpostcountry", pid);
vc.Add(ds.PostCode, "custpostcode", pid);
vc.Add(ds.Phone1, "custp1", pid);
vc.Add(ds.Phone2, "custp2", pid);
vc.Add(ds.Phone3, "custp3", pid);
vc.Add(ds.Phone4, "custp4", pid);
vc.Add(ds.Phone5, "custp5", pid);
vc.Add(ds.EmailAddress, "custemail", pid);
}
po.DropShipToCustomerViz = vc.Get("custname", pid);
if (forReporting)
{
po.DropShipToCustomerAddressViz = vc.Get("custaddr", pid);
po.DropShipToCustomerCityViz = vc.Get("custcity", pid);
po.DropShipToCustomerRegionViz = vc.Get("custregion", pid);
po.DropShipToCustomerCountryViz = vc.Get("custcountry", pid);
po.DropShipToCustomerLatitudeViz = vc.GetAsDecimal("custlat", pid);
po.DropShipToCustomerLongitudeViz = vc.GetAsDecimal("custlong", pid);
po.DropShipToCustomerPostAddressViz = vc.Get("custpostaddr", pid);
po.DropShipToCustomerPostCityViz = vc.Get("custpostcity", pid);
po.DropShipToCustomerPostRegionViz = vc.Get("custpostregion", pid);
po.DropShipToCustomerPostCountryViz = vc.Get("custpostcountry", pid);
po.DropShipToCustomerPostCodeViz = vc.Get("custpostcode", pid);
po.DropShipToCustomerPhone1Viz = vc.Get("custp1", pid);
po.DropShipToCustomerPhone2Viz = vc.Get("custp2", pid);
po.DropShipToCustomerPhone3Viz = vc.Get("custp3", pid);
po.DropShipToCustomerPhone4Viz = vc.Get("custp4", pid);
po.DropShipToCustomerPhone5Viz = vc.Get("custp5", pid);
po.DropShipToCustomerEmailAddressViz = vc.Get("custemail", pid);
}
}
var vid = po.VendorId;
if (!vc.Has("vndname", vid))
{
var vnd = await ct.Vendor.AsNoTracking().Where(x => x.Id == vid).FirstOrDefaultAsync();
vc.Add(vnd.Name, "vndname", vid);
vc.Add(vnd.AlertNotes, "vndalert", vid);
if (forReporting)
{
vc.Add(vnd.Address, "vndaddr", vid);
vc.Add(vnd.City, "vndcity", vid);
vc.Add(vnd.Region, "vndregion", vid);
vc.Add(vnd.Country, "vndcountry", vid);
vc.Add(vnd.Latitude.ToString(), "vndlat", vid);
vc.Add(vnd.Longitude.ToString(), "vndlong", vid);
vc.Add(vnd.PostAddress, "vndpostaddr", vid);
vc.Add(vnd.PostCity, "vndpostcity", vid);
vc.Add(vnd.PostRegion, "vndpostregion", vid);
vc.Add(vnd.PostCountry, "vndpostcountry", vid);
vc.Add(vnd.PostCode, "vndpostcode", vid);
vc.Add(vnd.Phone1, "vndp1", vid);
vc.Add(vnd.Phone2, "vndp2", vid);
vc.Add(vnd.Phone3, "vndp3", vid);
vc.Add(vnd.Phone4, "vndp4", vid);
vc.Add(vnd.Phone5, "vndp5", vid);
vc.Add(vnd.EmailAddress, "vndemail", vid);
vc.Add(vnd.Contact, "vndcontact", vid);
vc.Add(vnd.ContactNotes, "vndcontactnotes", vid);
vc.Add(vnd.AccountNumber, "vndacct", vid);
}
}
po.VendorViz = vc.Get("vndname", vid);
po.VendorAlertNotesViz = vc.Get("vndalert", vid);
if (forReporting)
{
po.VendorAddressViz = vc.Get("vndaddr", vid);
po.VendorCityViz = vc.Get("vndcity", vid);
po.VendorRegionViz = vc.Get("vndregion", vid);
po.VendorCountryViz = vc.Get("vndcountry", vid);
po.VendorLatitudeViz = vc.GetAsDecimal("vndlat", vid);
po.VendorLongitudeViz = vc.GetAsDecimal("vndlong", vid);
po.VendorPostAddressViz = vc.Get("vndpostaddr", vid);
po.VendorPostCityViz = vc.Get("vndpostcity", vid);
po.VendorPostRegionViz = vc.Get("vndpostregion", vid);
po.VendorPostCountryViz = vc.Get("vndpostcountry", vid);
po.VendorPostCodeViz = vc.Get("vndpostcode", vid);
po.VendorPhone1Viz = vc.Get("vndp1", vid);
po.VendorPhone2Viz = vc.Get("vndp2", vid);
po.VendorPhone3Viz = vc.Get("vndp3", vid);
po.VendorPhone4Viz = vc.Get("vndp4", vid);
po.VendorPhone5Viz = vc.Get("vndp5", vid);
po.VendorEmailAddressViz = vc.Get("vndemail", vid);
po.VendorContactViz = vc.Get("vndcontact", vid);
po.VendorContactNotesViz = vc.Get("vndcontactnotes", vid);
po.VendorAccountNumberViz = vc.Get("vndacct", vid);
if (PoStatusEnumList == null)
PoStatusEnumList = await AyaNova.Api.Controllers.EnumListController.GetEnumList(
StringUtil.TrimTypeName(typeof(PurchaseOrderStatus).ToString()),
UserTranslationId,
CurrentUserRoles);
po.StatusViz = PoStatusEnumList.Where(x => x.Id == (long)po.Status).Select(x => x.Name).First();
}
if (po.ProjectId != null)
po.ProjectViz = await ct.Project.AsNoTracking().Where(x => x.Id == po.ProjectId).Select(x => x.Name).FirstOrDefaultAsync();
if (po.ProjectId != null)
{
if (!vc.Has("projname", po.ProjectId))
vc.Add(await ct.Project.AsNoTracking().Where(x => x.Id == po.ProjectId).Select(x => x.Name).FirstOrDefaultAsync(), "projname", po.ProjectId);
po.ProjectViz = vc.Get("projname", po.ProjectId);
}
foreach (PurchaseOrderItem item in po.Items)
{
if (!vc.Has("partname", item.PartId))
{
var partInfo = await ct.Part.AsNoTracking().Where(x => x.Id == item.PartId).Select(x => new { x.Description, x.Name, x.UPC, x.UnitOfMeasure, x.ManufacturerNumber }).FirstOrDefaultAsync();
vc.Add(partInfo.Name, "partname", item.PartId);
vc.Add(partInfo.Description, "partdescription", item.PartId);
vc.Add(partInfo.UPC, "partupc", item.PartId);
vc.Add(partInfo.UnitOfMeasure, "partuofm", item.PartId);
vc.Add(partInfo.ManufacturerNumber, "partmanunum", item.PartId);
}
item.PartDescriptionViz = vc.Get("partdescription", item.PartId);
item.PartNameViz = vc.Get("partname", item.PartId);
item.UpcViz = vc.Get("partupc", item.PartId);
item.PartUnitOfMeasureViz = vc.Get("partuofm", item.PartId);
item.PartManufacturerNumberViz = vc.Get("partmanunum", item.PartId);
if (item.PartWarehouseId != 0)
{
if (!vc.Has("partwarehouse", item.PartWarehouseId))
vc.Add(await ct.PartWarehouse.AsNoTracking().Where(x => x.Id == item.PartWarehouseId).Select(x => x.Name).FirstOrDefaultAsync(), "partwarehouse", item.PartWarehouseId);
item.WarehouseViz = vc.Get("partwarehouse", item.PartWarehouseId);
}
if (item.WorkOrderItemPartRequestId != null)
{
po.HasPartRequest = true;
item.WorkOrderItemPartRequestViz = (await WorkOrderBiz.GetWorkOrderSerialFromRelativeAsync(AyaType.WorkOrderItemPartRequest, (long)item.WorkOrderItemPartRequestId, ct)).ToString();
if (!vc.Has("woserial", item.WorkOrderItemPartRequestId))
vc.Add((await WorkOrderBiz.GetWorkOrderSerialFromRelativeAsync(AyaType.WorkOrderItemPartRequest, (long)item.WorkOrderItemPartRequestId, ct)).ToString(), "woserial", item.WorkOrderItemPartRequestId);
item.WorkOrderItemPartRequestViz = vc.Get("woserial", item.WorkOrderItemPartRequestId);
if (item.PartRequestedById != null)
{
if (!vc.Has("user", item.PartRequestedById))
vc.Add(await ct.User.AsNoTracking().Where(x => x.Id == item.PartRequestedById).Select(x => x.Name).FirstOrDefaultAsync(), "user", item.PartRequestedById);
item.PartRequestedByViz = vc.Get("user", item.PartRequestedById);
}
}
TaxCode tax = null;
if (item.PurchaseTaxCodeId != null)
{
if (!oc.Has("tax", item.PurchaseTaxCodeId))
{
tax = await ct.TaxCode.AsNoTracking().FirstOrDefaultAsync(z => z.Id == item.PurchaseTaxCodeId);
oc.Add(tax, "tax", item.PurchaseTaxCodeId);
}
tax = (TaxCode)oc.Get("tax", item.PurchaseTaxCodeId);
item.PurchaseTaxCodeViz = tax.Name;
po.HasTaxes = true;
}
if (!string.IsNullOrWhiteSpace(item.VendorPartNumber))
po.HasVendorNumber = true;
if (item.QuantityReceived > 0)
po.HasReceipt = true;
if (item.QuantityReceived < item.QuantityOrdered)
po.HasUnreceived = true;
//Calculate line totals
if (item.QuantityOrdered != 0 && item.PurchaseOrderCost != 0)
{
decimal dNet = item.QuantityOrdered * item.PurchaseOrderCost;
decimal dTaxA = 0M;
decimal dTaxB = 0M;
if (tax != null)
{
//Tax A is always just tax A percent times net...
dTaxA = (tax.TaxAPct / 100) * dNet;
//Tax B on the other hand could be simple or tax on tax...
if (!tax.TaxOnTax)
dTaxB = (tax.TaxBPct / 100) * dNet;//simple
else
dTaxB = (dNet + dTaxA) * (tax.TaxBPct / 100);//tax on tax
}
//set line total and taxes display values
item.TaxAViz = dTaxA;
item.TaxBViz = dTaxB;
item.NetTotalViz = dNet;
item.LineTotalViz = dNet + dTaxA + dTaxB;
}
}
}
List<NameIdItem> PoStatusEnumList = null;
private VizCache vc = new VizCache();
private ObjectCache oc = new ObjectCache();
////////////////////////////////////////////////////////////////////////////////////////////////
//UPDATE
//
internal async Task<PurchaseOrder> PutAsync(PurchaseOrder putObject)
{
var dbObject = await GetAsync(putObject.Id, false, false);
if (dbObject == null)
{
AddError(ApiErrorCode.NOT_FOUND, "id");
return null;
}
if (dbObject.Concurrency != putObject.Concurrency)
{
AddError(ApiErrorCode.CONCURRENCY_CONFLICT);
return null;
}
putObject.Tags = TagBiz.NormalizeTags(putObject.Tags);
putObject.CustomFields = JsonUtil.CompactJson(putObject.CustomFields);
await ValidateAsync(putObject, dbObject);
if (HasErrors) return null;
using (var transaction = await ct.Database.BeginTransactionAsync())
{
try
{
ct.Replace(dbObject, putObject);
await ct.SaveChangesAsync();//needs to exist so woitempartrequest can be set with poitemid
var RequestsToUpdate = await BizActionsAsync(AyaEvent.Modified, putObject, dbObject, transaction);
if (HasErrors)
{
await transaction.RollbackAsync();
return null;
}
//ct.Replace(dbObject, putObject);
//await ct.SaveChangesAsync();//this is the save that sets the item id
await UpdateWorkOrderItemPartRequestsAsync(RequestsToUpdate);
await transaction.CommitAsync();
}
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(putObject, false);
await TagBiz.ProcessUpdateTagsInRepositoryAsync(ct, putObject.Tags, dbObject.Tags);
await HandlePotentialNotificationEvent(AyaEvent.Modified, putObject, dbObject);
await PopulateVizFields(putObject, false);
return putObject;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////
//DELETE
//
internal async Task<bool> DeleteAsync(long id)
{
using (var transaction = await ct.Database.BeginTransactionAsync())
{
var dbObject = await GetAsync(id, false, false);
if (dbObject == null)
{
AddError(ApiErrorCode.NOT_FOUND);
return false;
}
await ValidateCanDeleteAsync(dbObject);
if (HasErrors)
return false;
{
var IDList = await ct.Review.AsNoTracking().Where(x => x.AType == AyaType.PurchaseOrder && x.ObjectId == id).Select(x => x.Id).ToListAsync();
if (IDList.Count() > 0)
{
ReviewBiz b = new ReviewBiz(ct, UserId, UserTranslationId, CurrentUserRoles);
foreach (long ItemId in IDList)
if (!await b.DeleteAsync(ItemId, transaction))
{
AddError(ApiErrorCode.CHILD_OBJECT_ERROR, null, $"Review [{ItemId}]: {b.GetErrorsAsString()}");
return false;
}
}
}
ct.PurchaseOrder.Remove(dbObject);
var RequestsToUpdate = await BizActionsAsync(AyaEvent.Deleted, null, dbObject, transaction);
if (HasErrors)
{
await transaction.RollbackAsync();
return false;
}
await ct.SaveChangesAsync();
await UpdateWorkOrderItemPartRequestsAsync(RequestsToUpdate);
await transaction.CommitAsync();
await EventLogProcessor.DeleteObjectLogAsync(UserId, BizType, dbObject.Id, dbObject.Serial.ToString(), ct);
await Search.ProcessDeletedObjectKeywordsAsync(dbObject.Id, BizType, ct);
await TagBiz.ProcessDeleteTagsInRepositoryAsync(ct, dbObject.Tags);
await FileUtil.DeleteAttachmentsForObjectAsync(BizType, dbObject.Id, ct);
await HandlePotentialNotificationEvent(AyaEvent.Deleted, dbObject);
return true;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////
//SEARCH
//
private async Task SearchIndexAsync(PurchaseOrder obj, bool isNew)
{
var SearchParams = new Search.SearchIndexProcessObjectParameters(UserTranslationId, obj.Id, BizType);
DigestSearchText(obj, SearchParams);
if (isNew)
await Search.ProcessNewObjectKeywordsAsync(SearchParams);
else
await Search.ProcessUpdatedObjectKeywordsAsync(SearchParams);
}
public async Task<Search.SearchIndexProcessObjectParameters> GetSearchResultSummary(long id, AyaType specificType)
{
var obj = await GetAsync(id, false, false);
var SearchParams = new Search.SearchIndexProcessObjectParameters();
DigestSearchText(obj, SearchParams);
return SearchParams;
}
public void DigestSearchText(PurchaseOrder obj, Search.SearchIndexProcessObjectParameters searchParams)
{
if (obj != null)
searchParams.AddText(obj.Serial)
.AddText(obj.Notes)
.AddText(obj.VendorMemo)
.AddText(obj.ReferenceNumber)
.AddText(obj.Text1)
.AddText(obj.Text2)
.AddText(obj.Wiki)
.AddText(obj.Tags)
.AddCustomFields(obj.CustomFields);
}
////////////////////////////////////////////////////////////////////////////////////////////////
//VALIDATION
//
private async Task ValidateAsync(PurchaseOrder proposedObj, PurchaseOrder currentObj)
{
bool isNew = currentObj == null;
//No poitem can receive negative amounts
for (int i = 0; i < proposedObj.Items.Count; i++)
{
var propPOItem = proposedObj.Items[i];
if (propPOItem.QuantityReceived < 0 || propPOItem.QuantityReceived > propPOItem.QuantityOrdered)
{
AddError(ApiErrorCode.VALIDATION_INVALID_VALUE, $"Items[{i}].QuantityReceived", "LT:PurchaseOrderReceiptItemQuantityReceivedErrorInvalid");
}
}
//Any form customizations to validate?
var FormCustomization = await ct.FormCustom.AsNoTracking().SingleOrDefaultAsync(z => z.FormKey == AyaType.PurchaseOrder.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 async Task ValidateCanDeleteAsync(PurchaseOrder inObj)
{
//We allow delete even if received, will reverse automatically all inventory and affected objects
//not sure if there is anything here to check
await Task.CompletedTask;
}
private class RequestUpdate
{
public long PartRequestId { get; set; }
public long? POItemId { get; set; }
public decimal ReceivedQuantity { get; set; }
}
////////////////////////////////////////////////////////////////////////////////////////////////
//BIZ ACTIONS
//A PO can now be edited in any way user wishes at any time so this method is to fix up
//any changes they make in affected objects and inventory
//
private async Task<List<RequestUpdate>> BizActionsAsync(AyaEvent ayaEvent, PurchaseOrder newObj, PurchaseOrder oldObj, IDbContextTransaction transaction)
{
List<RequestUpdate> RequestsToUpdate = new List<RequestUpdate>();
//Get inventory object for updating
PartInventoryBiz pib = new PartInventoryBiz(ct, UserId, UserTranslationId, CurrentUserRoles);
//DELETED
if (ayaEvent == AyaEvent.Deleted)
{
//REVERSE ENTIRE PO
//any received remove from inventory
var inventoryAffectingItems = oldObj.Items.Where(z => z.QuantityReceived > 0).ToList();
foreach (var poItem in inventoryAffectingItems)
{
//make reversing inventory adjustment
dtInternalPartInventory i = new dtInternalPartInventory();
i.PartId = poItem.PartId;
i.PartWarehouseId = poItem.PartWarehouseId;
i.Quantity = poItem.QuantityReceived * -1;
i.SourceType = null;//null because the po no longer exists so this is technically a manual adjustment
i.SourceId = null;//''
i.Description = await Translate("PurchaseOrder") + $" {oldObj.Serial} " + await Translate("EventDeleted");
if (await pib.CreateAsync(i) == null)
{
AddError(ApiErrorCode.API_SERVER_ERROR, "generalerror", $"Error updating inventory ({i.Description}):{pib.GetErrorsAsString()}");
return RequestsToUpdate;
}
//might have contributed serials so remove them here, handles empty serials so no issue calling this
await PartBiz.RemoveSerialsAsync(poItem.PartId, poItem.Serials, ct, UserId);
}
//Database itself will set null on delete no need to handle it in biz object
// foreach (var poItem in oldObj.Items)
// {
// if (poItem.WorkOrderItemPartRequestId != null)
// {
// //De-request it
// RequestsToUpdate.Add(new RequestUpdate { PartRequestId = (long)poItem.WorkOrderItemPartRequestId, POItemId = null, ReceivedQuantity = 0 });
// }
// }
return RequestsToUpdate;//done, nothing more to do here
}
//Some kind of update so fetch the parts so the default part values can be set on the poItem if necessary
var listOfPoPartIds = newObj.Items.Select(x => x.PartId).ToList();
var PoParts = await ct.Part.AsNoTracking().Where(x => listOfPoPartIds.Contains(x.Id)).ToListAsync();
//CREATED
if (ayaEvent == AyaEvent.Created)
{
//any received go into inventory
var inventoryAffectingItems = newObj.Items.Where(z => z.QuantityReceived > 0).ToList();
foreach (var poItem in inventoryAffectingItems)
{
//make inventory adjustment here
dtInternalPartInventory i = new dtInternalPartInventory();
i.PartId = poItem.PartId;
i.PartWarehouseId = poItem.PartWarehouseId;
i.Quantity = poItem.QuantityReceived;
i.SourceType = AyaType.PurchaseOrder;
i.SourceId = newObj.Id;
i.Description = await Translate("PurchaseOrder") + $" {newObj.Serial} " + await Translate("EventCreated");
if (await pib.CreateAsync(i) == null)
{
AddError(ApiErrorCode.API_SERVER_ERROR, "generalerror", $"Error updating inventory ({i.Description}):{pib.GetErrorsAsString()}");
return RequestsToUpdate;
}
await PartBiz.AppendSerialsAsync(poItem.PartId, poItem.Serials, ct, UserId);
}
//All new so set them all
foreach (var poItem in newObj.Items)
SetPoItemDefaultPartValues(poItem, PoParts, newObj.VendorId, true);
foreach (var poItem in newObj.Items)
{
if (poItem.WorkOrderItemPartRequestId != null)
{
RequestsToUpdate.Add(new RequestUpdate { PartRequestId = (long)poItem.WorkOrderItemPartRequestId, POItemId = poItem.Id, ReceivedQuantity = poItem.QuantityReceived });
}
}
return RequestsToUpdate;
}
//MODIFIED
if (ayaEvent == AyaEvent.Modified)
{
//any old po items deleted?
foreach (var oldItem in oldObj.Items)
{
//get the matching new item
var newItem = newObj.Items.FirstOrDefault(z => z.Id == oldItem.Id);
//OLD ITEM DELETED
if (newItem == null)
{
//an old item with received stock was deleted, fixup inventory
if (oldItem.QuantityReceived > 0)
{
//make reversing inventory adjustment
dtInternalPartInventory i = new dtInternalPartInventory();
i.PartId = oldItem.PartId;
i.PartWarehouseId = oldItem.PartWarehouseId;
i.Quantity = oldItem.QuantityReceived * -1;
i.SourceType = AyaType.PurchaseOrder;
i.SourceId = oldObj.Id;
i.Description = await Translate("PurchaseOrder") + $" {oldObj.Serial} " + await Translate("PurchaseOrderItem") + " " + await Translate("EventDeleted");
if (await pib.CreateAsync(i) == null)
{
AddError(ApiErrorCode.API_SERVER_ERROR, "generalerror", $"Error updating inventory ({i.Description}):{pib.GetErrorsAsString()}");
return RequestsToUpdate;
}
//might have serials so remove those as well
await PartBiz.RemoveSerialsAsync(oldItem.PartId, oldItem.Serials, ct, UserId);
}
//Database itself will set null on delete no need to handle it in biz object
// //fixup woitempartrequest if any
// if (oldItem.WorkOrderItemPartRequestId != null)
// {
// RequestsToUpdate.Add(new RequestUpdate { PartRequestId = (long)oldItem.WorkOrderItemPartRequestId, POItemId = null, ReceivedQuantity = 0 });
// }
}
}
//ITERATE NEW ITEMS LOOK FOR CHANGES
foreach (var newItem in newObj.Items)
{
//get the matching oldItem
var oldItem = oldObj.Items.FirstOrDefault(z => z.Id == newItem.Id);
//CHANGED THE VENDOR? (this doesn't preclude other changes as well below)
if (oldObj.VendorId != newObj.VendorId)
{
SetPoItemDefaultPartValues(newItem, PoParts, newObj.VendorId, false);
}
//NEW ITEM ADDED
if (oldItem == null)
{
if (newItem.QuantityReceived > 0)
{
//It's a new receipt with received amounts - add to inventory
dtInternalPartInventory i = new dtInternalPartInventory();
i.PartId = newItem.PartId;
i.PartWarehouseId = newItem.PartWarehouseId;
i.Quantity = newItem.QuantityReceived;
i.SourceType = AyaType.PurchaseOrder;
i.SourceId = newObj.Id;
i.Description = await Translate("PurchaseOrder") + $" {newObj.Serial} " + await Translate("PurchaseOrderItem") + " " + await Translate("EventCreated");
if (await pib.CreateAsync(i) == null)
{
AddError(ApiErrorCode.API_SERVER_ERROR, "generalerror", $"Error updating inventory ({i.Description}):{pib.GetErrorsAsString()}");
return RequestsToUpdate;
}
await PartBiz.AppendSerialsAsync(newItem.PartId, newItem.Serials, ct, UserId);
}
SetPoItemDefaultPartValues(newItem, PoParts, newObj.VendorId, false);
if (newItem.WorkOrderItemPartRequestId != null)
{
RequestsToUpdate.Add(new RequestUpdate { PartRequestId = (long)newItem.WorkOrderItemPartRequestId, POItemId = newItem.Id, ReceivedQuantity = newItem.QuantityReceived });
}
continue;//on to next item no possible other changes here
}
//CHANGED PART OR WAREHOUSE ID
if (oldItem.PartId != newItem.PartId || oldItem.PartWarehouseId != newItem.PartWarehouseId)
{
if (oldItem.QuantityReceived > 0)
{
//reverse inventory
dtInternalPartInventory i = new dtInternalPartInventory();
i.PartId = oldItem.PartId;
i.PartWarehouseId = oldItem.PartWarehouseId;
i.Quantity = oldItem.QuantityReceived * -1;
i.SourceType = AyaType.PurchaseOrder;
i.SourceId = oldObj.Id;
i.Description = await Translate("PurchaseOrder") + $" {oldObj.Serial} " + await Translate("PurchaseOrderItem") + " " + await Translate("EventModified") + " " + await Translate("Part") + "/" + await Translate("PartWarehouse");
if (await pib.CreateAsync(i) == null)
{
AddError(ApiErrorCode.API_SERVER_ERROR, "generalerror", $"Error updating inventory ({i.Description}):{pib.GetErrorsAsString()}");
return RequestsToUpdate;
}
await PartBiz.RemoveSerialsAsync(oldItem.PartId, oldItem.Serials, ct, UserId);
//Database itself will set null on delete no need to handle it in biz object
// //change of serial or part invalidates the workorderitempartrequest as it has specific part and warehouse so remove it here
// if (oldItem.WorkOrderItemPartRequestId != null)
// {
// RequestsToUpdate.Add(new RequestUpdate { PartRequestId = (long)oldItem.WorkOrderItemPartRequestId, POItemId = null, ReceivedQuantity = 0 });
// }
}
if (newItem.QuantityReceived > 0)
{
//set new inventory
dtInternalPartInventory i = new dtInternalPartInventory();
i.PartId = newItem.PartId;
i.PartWarehouseId = newItem.PartWarehouseId;
i.Quantity = newItem.QuantityReceived;
i.SourceType = AyaType.PurchaseOrder;
i.SourceId = newObj.Id;
i.Description = await Translate("PurchaseOrder") + $" {newObj.Serial} " + await Translate("PurchaseOrderItem") + " " + await Translate("EventModified") + " " + await Translate("Part") + "/" + await Translate("PartWarehouse");
if (await pib.CreateAsync(i) == null)
{
AddError(ApiErrorCode.API_SERVER_ERROR, "generalerror", $"Error updating inventory ({i.Description}):{pib.GetErrorsAsString()}");
return RequestsToUpdate;
}
await PartBiz.AppendSerialsAsync(newItem.PartId, newItem.Serials, ct, UserId);
if (newItem.WorkOrderItemPartRequestId != null)
{
RequestsToUpdate.Add(new RequestUpdate { PartRequestId = (long)newItem.WorkOrderItemPartRequestId, POItemId = newItem.Id, ReceivedQuantity = newItem.QuantityReceived });
}
}
//Update part values into poitem if the part or vendor has changed
if (oldItem.PartId != newItem.PartId || oldObj.VendorId != newObj.VendorId)
SetPoItemDefaultPartValues(newItem, PoParts, newObj.VendorId, false);
continue;//Note: this accounts also for any change received quantities so no need to check that below
}
//CHANGED ONLY THE RECEIVED AMOUNT
if (oldItem.QuantityReceived != newItem.QuantityReceived)
{
decimal netChange = 0;
if (oldItem.QuantityReceived < newItem.QuantityReceived)
netChange = newItem.QuantityReceived - oldItem.QuantityReceived;//More received
else
netChange = newItem.QuantityReceived - oldItem.QuantityReceived;//less received
dtInternalPartInventory i = new dtInternalPartInventory();
i.PartId = newItem.PartId;
i.PartWarehouseId = newItem.PartWarehouseId;
i.Quantity = netChange;
i.SourceType = AyaType.PurchaseOrder;
i.SourceId = newObj.Id;
i.Description = await Translate("PurchaseOrder") + $" {newObj.Serial} " + await Translate("PurchaseOrderItem") + " " + await Translate("EventModified") + " " + await Translate("PurchaseOrderItemQuantityReceived");
if (await pib.CreateAsync(i) == null)
{
AddError(ApiErrorCode.API_SERVER_ERROR, "generalerror", $"Error updating inventory ({i.Description}):{pib.GetErrorsAsString()}");
return RequestsToUpdate;
}
//Update part values into poitem if the vendor has changed
if (oldObj.VendorId != newObj.VendorId)
SetPoItemDefaultPartValues(newItem, PoParts, newObj.VendorId, false);
//Set received cost if appropriate but don't overwrite an existing one
if (newItem.QuantityReceived > 0 && newItem.ReceivedCost == 0 && newItem.PurchaseOrderCost != 0)
newItem.ReceivedCost = newItem.PurchaseOrderCost;
//update serials if they have changed
if (oldItem.Serials != newItem.Serials)
{
await PartBiz.RemoveSerialsAsync(oldItem.PartId, oldItem.Serials, ct, UserId);
await PartBiz.AppendSerialsAsync(newItem.PartId, newItem.Serials, ct, UserId);
}
//update workorderitempartrequest if applicable
if (newItem.WorkOrderItemPartRequestId != null)
{
RequestsToUpdate.Add(new RequestUpdate { PartRequestId = (long)newItem.WorkOrderItemPartRequestId, POItemId = newItem.Id, ReceivedQuantity = newItem.QuantityReceived });
}
continue;//on to next
}
//SERIALS CHANGED
if (oldItem.Serials != newItem.Serials)
{
await PartBiz.RemoveSerialsAsync(oldItem.PartId, oldItem.Serials, ct, UserId);
await PartBiz.AppendSerialsAsync(newItem.PartId, newItem.Serials, ct, UserId);
}
//### BEFORE ADDING MORE CHECKS HERE MAKE SURE LOGIC WORKS WITH ABOVE (and add continue statement) ###
}
}//modified block
return RequestsToUpdate;
}
//save changes to part requests now that we have the ID's required
private async Task UpdateWorkOrderItemPartRequestsAsync(List<RequestUpdate> requestsToUpdate)
{
foreach (var r in requestsToUpdate)
{
var w = await ct.WorkOrderItemPartRequest.FirstOrDefaultAsync(x => x.Id == r.PartRequestId);
if (w != null)
{
w.PurchaseOrderItemId = r.POItemId;
w.Received = r.ReceivedQuantity;
await ct.SaveChangesAsync();
}
}
}
//Called to update Part values into poitem like VendorNumber and costs etc
private void SetPoItemDefaultPartValues(PurchaseOrderItem poItem, List<Part> poParts, long vendorId, bool isNewRecord)
{
var ThisPart = poParts.Single(x => x.Id == poItem.PartId);//part should always be there, if it isn't we have deeper problems
//VendorPartNumber
if (string.IsNullOrWhiteSpace(poItem.VendorPartNumber))//only set if empty, user may have typed in one already on create
{
if (ThisPart.ManufacturerId == vendorId)
poItem.VendorPartNumber = ThisPart.ManufacturerNumber;
else if (ThisPart.WholeSalerId == vendorId)
poItem.VendorPartNumber = ThisPart.WholeSalerNumber;
else if (ThisPart.AlternativeWholeSalerId == vendorId)
poItem.VendorPartNumber = ThisPart.AlternativeWholeSalerNumber;
}
//Costs
if (!isNewRecord || (isNewRecord && poItem.PurchaseOrderCost == 0))//this is an exemption for migration purposes otherwise the cost is overwritten
poItem.PurchaseOrderCost = ThisPart.Cost;
}
////////////////////////////////////////////////////////////////////////////////////////////////
//REPORTING
//
public async Task<JArray> GetReportData(DataListSelectedRequest dataListSelectedRequest, Guid jobId)
{
var idList = dataListSelectedRequest.SelectedRowIds;
JArray ReportData = new JArray();
while (idList.Any())
{
var batch = idList.Take(IReportAbleObject.REPORT_DATA_BATCH_SIZE);
idList = idList.Skip(IReportAbleObject.REPORT_DATA_BATCH_SIZE).ToArray();
//query for this batch, comes back in db natural order unfortunately
var batchResults = await ct.PurchaseOrder.Include(x => x.Items).AsNoTracking().Where(z => batch.Contains(z.Id)).ToArrayAsync();
//order the results back into original
var orderedList = from id in batch join z in batchResults on id equals z.Id select z;
batchResults = null;
foreach (PurchaseOrder w in orderedList)
{
if (!ReportRenderManager.KeepGoing(jobId)) return null;
await PopulateVizFields(w, true);
var jo = JObject.FromObject(w);
if (!JsonUtil.JTokenIsNullOrEmpty(jo["CustomFields"]))
jo["CustomFields"] = JObject.Parse((string)jo["CustomFields"]);
ReportData.Add(jo);
}
orderedList = null;
}
vc.Clear();
oc.Clear();
return ReportData;
}
////////////////////////////////////////////////////////////////////////////////////////////////
// IMPORT EXPORT
//
public async Task<JArray> GetExportData(DataListSelectedRequest dataListSelectedRequest, Guid jobId)
{
//for now just re-use the report data code
//this may turn out to be the pattern for most biz object types but keeping it seperate allows for custom usage from time to time
return await GetReportData(dataListSelectedRequest, jobId);
}
////////////////////////////////////////////////////////////////////////////////////////////////
//JOB / OPERATIONS
//
public async Task HandleJobAsync(OpsJob job)
{
//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)
{
case JobType.BatchCoreObjectOperation:
await ProcessBatchJobAsync(job);
break;
default:
throw new System.ArgumentOutOfRangeException($"PurchaseOrderBiz.HandleJob-> Invalid job type{job.JobType.ToString()}");
}
}
private async Task ProcessBatchJobAsync(OpsJob job)
{
await JobsBiz.UpdateJobStatusAsync(job.GId, JobStatus.Running);
await JobsBiz.LogJobAsync(job.GId, $"LT:StartJob {job.SubType}");
List<long> idList = new List<long>();
long FailedObjectCount = 0;
JObject jobData = JObject.Parse(job.JobInfo);
if (jobData.ContainsKey("idList"))
idList = ((JArray)jobData["idList"]).ToObject<List<long>>();
else
idList = await ct.PurchaseOrder.AsNoTracking().Select(z => z.Id).ToListAsync();
bool SaveIt = false;
foreach (long id in idList)
{
try
{
SaveIt = false;
ClearErrors();
PurchaseOrder o = null;
//save a fetch if it's a delete
if (job.SubType != JobSubType.Delete)
o = await GetAsync(id, false, false);
switch (job.SubType)
{
case JobSubType.TagAddAny:
case JobSubType.TagAdd:
case JobSubType.TagRemoveAny:
case JobSubType.TagRemove:
case JobSubType.TagReplaceAny:
case JobSubType.TagReplace:
SaveIt = TagBiz.ProcessBatchTagOperation(o.Tags, (string)jobData["tag"], jobData.ContainsKey("toTag") ? (string)jobData["toTag"] : null, job.SubType);
break;
case JobSubType.Delete:
if (!await DeleteAsync(id))
{
await JobsBiz.LogJobAsync(job.GId, $"LT:Errors {GetErrorsAsString()} id {id}");
FailedObjectCount++;
}
break;
default:
throw new System.ArgumentOutOfRangeException($"ProcessBatchJobAsync -> Invalid job Subtype{job.SubType}");
}
if (SaveIt)
{
o = await PutAsync(o);
if (o == null)
{
await JobsBiz.LogJobAsync(job.GId, $"LT:Errors {GetErrorsAsString()} id {id}");
FailedObjectCount++;
}
}
}
catch (Exception ex)
{
await JobsBiz.LogJobAsync(job.GId, $"LT:Errors id({id})");
await JobsBiz.LogJobAsync(job.GId, ExceptionUtil.ExtractAllExceptionMessages(ex));
}
}
await JobsBiz.LogJobAsync(job.GId, $"LT:BatchJob {job.SubType} {idList.Count}{(FailedObjectCount > 0 ? " - LT:Failed " + FailedObjectCount : "")}");
await JobsBiz.UpdateJobStatusAsync(job.GId, JobStatus.Completed);
}
////////////////////////////////////////////////////////////////////////////////////////////////
// NOTIFICATION PROCESSING
//
public async Task HandlePotentialNotificationEvent(AyaEvent ayaEvent, ICoreBizObjectModel proposedObj, ICoreBizObjectModel currentObj = null)
{
ILogger log = AyaNova.Util.ApplicationLogging.CreateLogger<PurchaseOrderBiz>();
if (ServerBootConfig.SEEDING || ServerBootConfig.MIGRATING) return;
log.LogDebug($"HandlePotentialNotificationEvent processing: [AyaType:{this.BizType}, AyaEvent:{ayaEvent}]");
bool isNew = currentObj == null;
var p = (PurchaseOrder)proposedObj;
proposedObj.Name = p.Serial.ToString();
//STANDARD EVENTS FOR ALL OBJECTS
await NotifyEventHelper.ProcessStandardObjectEvents(ayaEvent, proposedObj, ct);
//SPECIFIC EVENTS FOR THIS OBJECT
//CREATED / MODIFIED
if (ayaEvent == AyaEvent.Created || ayaEvent == AyaEvent.Modified)
{
var c = (PurchaseOrder)currentObj;
//# PartRequestReceived
{
//get a list of all items with part requests and received inventory
var proposedRequestItems = p.Items.Where(z => z.WorkOrderItemPartRequestId != null && z.QuantityReceived != 0);
//are there any potential notify items?
if (proposedRequestItems.Count() > 0)
{
//Look for new receipts of requested parts
foreach (var proposedRequestItem in proposedRequestItems)
{
//Get the matching item from db collection
var currentMatchingRequestItem = c.Items.FirstOrDefault(z => z.Id == proposedRequestItem.Id);
//if it doesn't exist or received less than the proposed item then we have actionable notification
if (currentMatchingRequestItem == null || currentMatchingRequestItem.QuantityReceived < proposedRequestItem.QuantityReceived)
{
//is there a subscriber for this user id and event?
var sub = await ct.NotifySubscription.FirstOrDefaultAsync(z => z.EventType == NotifyEventType.PartRequestReceived && z.UserId == proposedRequestItem.PartRequestedById);
if (sub != null)
{
//yes. So we have a subscriber, a change in received for a request, time to notify
//not for inactive users
if (!await UserBiz.UserIsActive(sub.UserId)) continue;
NotifyEvent n = new NotifyEvent()
{
EventType = NotifyEventType.PartRequestReceived,
UserId = sub.UserId,
AyaType = AyaType.WorkOrderItemPartRequest,
ObjectId = (long)proposedRequestItem.WorkOrderItemPartRequestId,
NotifySubscriptionId = sub.Id,
Name = BizObjectNameFetcherDirect.Name(AyaType.WorkOrderItemPartRequest, (long)proposedRequestItem.WorkOrderItemPartRequestId, UserTranslationId, ct)
};
await ct.NotifyEvent.AddAsync(n);
log.LogDebug($"Adding NotifyEvent: [{n.ToString()}]");
await ct.SaveChangesAsync();
}
}
}
}
}
}
}//end of process notifications
/////////////////////////////////////////////////////////////////////
}//eoc
}//eons