public async Task <IActionResult> CreateLoad([FromBody] OrderEntryViewModel orderEntryVM) { try { if (!_userContext.UserId.HasValue) { throw new Exception("Invalid UserId"); } // LoadService.CreateLoad expects the Customer.IdentUserId, not the Customer.CustomerId var customerIdentUserId = await _userProfileService.GetPrimaryCustomerIdentUserId(_userContext.UserId.Value); if (!customerIdentUserId.HasValue) { throw new Exception("User does not have a primary customer."); } // Saving locations requires FK to CustomerID var customerId = await _userProfileService.GetPrimaryCustomerId(_userContext.UserId.Value); if (!customerId.HasValue) { throw new Exception("User does not have a primary customer."); } /** * The UI allows entering an Order Number, which is effectively the ReferenceLoadDisplay, so in order * to generate a ReferenceLoadId, we need to get the user's primary customer's TOPS Owner ID and then * prepend that to the ReferenceLoadDisplay to get the ReferenceLoadId */ var customerOwnerId = await _userProfileService.GetPrimaryCustomerOwner(_userContext.UserId.Value); orderEntryVM.ReferenceLoadId = CalculateReferenceLoadId(customerOwnerId, orderEntryVM.ReferenceLoadDisplay); SetLoadStopDtTms(orderEntryVM); var load = _mapper.Map <LoadDetailData>(orderEntryVM); load.LoadTransaction = new LoadTransactionData() { TransactionType = TransactionTypeData.PendingAdd }; /** * LoadStop.ApptType is a calculated field, so the logic for doing so and setting its value on * all load stops is kept in the LoadService. We call it here to update the values before calling * the shared CreateLoad code, so the load stops will pass validation */ load.LoadStops = _loadService.SetApptTypeOnLoadStops(load.LoadStops); var options = new CreateLoadOptionsDto() { ValidateAddress = OrderAddressValidationEnum.Validate, ManuallyCreated = true }; var createResponse = await _loadService.CreateLoad(load, customerIdentUserId.Value, _userContext.UserName, options); if (!createResponse.IsSuccess) { var problemDetails = new ValidationProblemDetails(createResponse.ModelState) { Title = "Create Load Error", Detail = "One or more errors occurred when trying to save this load. See form for error details", Status = (int)HttpStatusCode.BadRequest, Instance = $"urn:kbxl:error:{Guid.NewGuid()}" }; return(BadRequest(problemDetails)); } else { SaveLocations(customerId.Value, load.LoadStops); } return(Success(orderEntryVM)); } catch (ValidationException exception) { return(Error <List <LocationViewModel> >(exception)); } }