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 ExistsAsync(long id) { return await ct.PurchaseOrder.AnyAsync(z => z.Id == id); } //////////////////////////////////////////////////////////////////////////////////////////////// //CREATE // internal async Task 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) await BizActionsAsync(AyaEvent.Created, newObject, null, transaction); if (HasErrors) { await transaction.RollbackAsync(); return null; } await ct.SaveChangesAsync(); 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 SetDisplayFields(newObject, false); return newObject; } } } // //////////////////////////////////////////////////////////////////////////////////////////////// // //DUPLICATE // // // internal async Task DuplicateAsync(long id) // { // //TODO: allow this but only with ZEROS set for the actual received amount and ignore woitempart requested during dupe? // var dbObject = await GetAsync(id, false, false); // if (dbObject == null) // { // AddError(ApiErrorCode.NOT_FOUND, "id"); // return null; // } // PurchaseOrder newObject = new PurchaseOrder(); // CopyObject.Copy(dbObject, newObject, "Wiki,Serial"); // newObject.Id = 0; // newObject.Concurrency = 0; // newObject.Status = PurchaseOrderStatus.OpenNotYetOrdered; // foreach (var item in newObject.Items) // { // item.Id = 0; // item.Concurrency = 0; // item.QuantityReceived = 0; // item.ReceivedCost = 0; // item.ReceivedDate = null; // item.PurchaseOrderId = 0; // item.WorkOrderItemPartRequestId = null; // item.PartRequestedById = null; // } // await ct.PurchaseOrder.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); // await HandlePotentialNotificationEvent(AyaEvent.Created, newObject); // await SetDisplayFields(newObject); // return newObject; // } //////////////////////////////////////////////////////////////////////////////////////////////// //GET // internal async Task 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 SetDisplayFields(ret, false); if (logTheGetEvent && ret != null) await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserId, id, BizType, AyaEvent.Retrieved), ct); return ret; } //////////////////////////////////////////////////////////////////////////////////////////////// //DISPLAY FIELDS // private async Task SetDisplayFields(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 ds = await ct.Customer.AsNoTracking().Where(x => x.Id == po.DropShipToCustomerId).FirstOrDefaultAsync(); po.DropShipToCustomerViz = ds.Name; if (forReporting) { po.DropShipToCustomerAddressViz = ds.Address; po.DropShipToCustomerCityViz = ds.City; po.DropShipToCustomerRegionViz = ds.Region; po.DropShipToCustomerCountryViz = ds.Country; po.DropShipToCustomerLatitudeViz = ds.Latitude; po.DropShipToCustomerLongitudeViz = ds.Longitude; po.DropShipToCustomerPostAddressViz = ds.PostAddress; po.DropShipToCustomerPostCityViz = ds.PostCity; po.DropShipToCustomerPostRegionViz = ds.PostRegion; po.DropShipToCustomerPostCountryViz = ds.PostCountry; po.DropShipToCustomerPostCodeViz = ds.PostCode; po.DropShipToCustomerPhone1Viz = ds.Phone1; po.DropShipToCustomerPhone2Viz = ds.Phone2; po.DropShipToCustomerPhone3Viz = ds.Phone3; po.DropShipToCustomerPhone4Viz = ds.Phone4; po.DropShipToCustomerPhone5Viz = ds.Phone5; po.DropShipToCustomerEmailAddressViz = ds.EmailAddress; } } var vnd = await ct.Vendor.AsNoTracking().Where(x => x.Id == po.VendorId).FirstOrDefaultAsync(); po.VendorViz = vnd.Name; if (forReporting) { po.VendorAddressViz = vnd.Address; po.VendorCityViz = vnd.City; po.VendorRegionViz = vnd.Region; po.VendorCountryViz = vnd.Country; po.VendorLatitudeViz = vnd.Latitude; po.VendorLongitudeViz = vnd.Longitude; po.VendorPostAddressViz = vnd.PostAddress; po.VendorPostCityViz = vnd.PostCity; po.VendorPostRegionViz = vnd.PostRegion; po.VendorPostCountryViz = vnd.PostCountry; po.VendorPostCodeViz = vnd.PostCode; po.VendorPhone1Viz = vnd.Phone1; po.VendorPhone2Viz = vnd.Phone2; po.VendorPhone3Viz = vnd.Phone3; po.VendorPhone4Viz = vnd.Phone4; po.VendorPhone5Viz = vnd.Phone5; po.VendorEmailAddressViz = vnd.EmailAddress; po.VendorContactViz = vnd.Contact; po.VendorContactNotesViz = vnd.ContactNotes; } if (po.ProjectId != null) po.ProjectViz = await ct.Project.AsNoTracking().Where(x => x.Id == po.ProjectId).Select(x => x.Name).FirstOrDefaultAsync(); foreach (PurchaseOrderItem item in po.Items) { var partInfo = await ct.Part.AsNoTracking().Where(x => x.Id == item.PartId).Select(x => new { partViz = x.PartNumber, partNameViz = x.Name }).FirstOrDefaultAsync(); item.PartViz = partInfo.partViz; item.PartNameViz = partInfo.partNameViz; item.WarehouseViz = await ct.PartWarehouse.AsNoTracking().Where(x => x.Id == item.PartWarehouseId).Select(x => x.Name).FirstOrDefaultAsync(); if (item.WorkOrderItemPartRequestId != null) { po.HasPartRequest = true; var wid = (await WorkOrderBiz.GetWorkOrderIdFromRelativeAsync(AyaType.WorkOrderItemPartRequest, (long)item.WorkOrderItemPartRequestId, ct)).ParentId; var WOSerial = await ct.WorkOrder.AsNoTracking().Where(x => x.Id == wid).Select(x => new { x.Serial }).FirstOrDefaultAsync(); if (WOSerial != null) item.WorkOrderItemPartRequestViz = WOSerial.Serial.ToString(); if (item.PartRequestedById != null) item.PartRequestedByViz = await ct.User.AsNoTracking().Where(x => x.Id == item.PartRequestedById).Select(x => x.Name).FirstOrDefaultAsync(); } TaxCode tax = null; if (item.PurchaseTaxCodeId != null) { tax = await ct.TaxCode.AsNoTracking().Where(x => x.Id == item.PurchaseTaxCodeId).FirstOrDefaultAsync(); 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; } } } //////////////////////////////////////////////////////////////////////////////////////////////// //UPDATE // internal async Task 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()) { await BizActionsAsync(AyaEvent.Modified, putObject, dbObject, transaction); if (HasErrors) { await transaction.RollbackAsync(); return null; } ct.Replace(dbObject, putObject); try { await ct.SaveChangesAsync(); 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 SetDisplayFields(putObject, false); return putObject; } } //////////////////////////////////////////////////////////////////////////////////////////////// //DELETE // internal async Task 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; ct.PurchaseOrder.Remove(dbObject); await BizActionsAsync(AyaEvent.Deleted, null, dbObject, transaction); if (HasErrors) { await transaction.RollbackAsync(); return false; } await ct.SaveChangesAsync(); 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 GetSearchResultSummary(long id) { 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.Serial) .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; } //////////////////////////////////////////////////////////////////////////////////////////////// //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 BizActionsAsync(AyaEvent ayaEvent, PurchaseOrder newObj, PurchaseOrder oldObj, IDbContextTransaction transaction) { //MIGRATE_OUTSTANDING - woitempart request update //if received on woitempartrequest then need to update woitempartrequest (notification separate not a concern here) //if workorderitempartrequest item removed, need to fixup woitempartrequest //BUT *only* if the woitempartrequest still exists and isn't completed already //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; } //MIGRATE_OUTSTANDING - update workorderitempart here if applicable } return;//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; } await PartBiz.AppendSerialsAsync(poItem.PartId, poItem.Serials, ct, UserId); //MIGRATE_OUTSTANDING - update workorderitempart here if applicable } //All new so set them all foreach (var poItem in newObj.Items) SetPoItemDefaultPartValues(poItem, PoParts, newObj.VendorId); return; } //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; } //might have serials so remove those as well await PartBiz.RemoveSerialsAsync(oldItem.PartId, oldItem.Serials, ct, UserId); } } } //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); } //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; } await PartBiz.AppendSerialsAsync(newItem.PartId, newItem.Serials, ct, UserId); } SetPoItemDefaultPartValues(newItem, PoParts, newObj.VendorId); //MIGRATE_OUTSTANDING - update workorderitempart here if applicable 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; } await PartBiz.RemoveSerialsAsync(oldItem.PartId, oldItem.Serials, ct, UserId); } 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; } await PartBiz.AppendSerialsAsync(newItem.PartId, newItem.Serials, ct, UserId); } //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); 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; } //MIGRATE_OUTSTANDING - update workorderitempart here if applicable //Update part values into poitem if the vendor has changed if (oldObj.VendorId != newObj.VendorId) SetPoItemDefaultPartValues(newItem, PoParts, newObj.VendorId); //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); } 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 } //Called to update Part values into poitem like VendorNumber and costs etc private void SetPoItemDefaultPartValues(PurchaseOrderItem poItem, List poParts, long vendorId) { 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 poItem.PurchaseOrderCost = ThisPart.Cost; } //////////////////////////////////////////////////////////////////////////////////////////////// //REPORTING // public async Task GetReportData(DataListSelectedRequest dataListSelectedRequest) { 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; foreach (PurchaseOrder w in orderedList) { await SetDisplayFields(w, true); var jo = JObject.FromObject(w); if (!JsonUtil.JTokenIsNullOrEmpty(jo["CustomFields"])) jo["CustomFields"] = JObject.Parse((string)jo["CustomFields"]); ReportData.Add(jo); } } return ReportData; } //////////////////////////////////////////////////////////////////////////////////////////////// // IMPORT EXPORT // public async Task GetExportData(DataListSelectedRequest dataListSelectedRequest) { //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); } //////////////////////////////////////////////////////////////////////////////////////////////// //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 idList = new List(); long FailedObjectCount = 0; JObject jobData = JObject.Parse(job.JobInfo); if (jobData.ContainsKey("idList")) idList = ((JArray)jobData["idList"]).ToObject>(); 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(); 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, ct) }; await ct.NotifyEvent.AddAsync(n); log.LogDebug($"Adding NotifyEvent: [{n.ToString()}]"); await ct.SaveChangesAsync(); } } } } } } }//end of process notifications ///////////////////////////////////////////////////////////////////// }//eoc }//eons