public static async Task DeleteJobAsync(ApiGatewayRequest request, McmaApiResponse response) { Logger.Debug(nameof(DeleteJobAsync)); Logger.Debug(request.ToMcmaJson().ToString()); var table = new DynamoDbTable(request.StageVariables["TableName"]); var jobId = request.StageVariables["PublicUrl"] + request.Path; var job = await table.GetAsync <Job>(jobId); if (job == null) { response.StatusCode = (int)HttpStatusCode.NotFound; response.StatusMessage = "No resource found on path '" + request.Path + "'."; return; } await table.DeleteAsync <Job>(jobId); // invoking worker lambda function that will delete the JobProcess created for this Job if (!string.IsNullOrEmpty(job.JobProcess)) { var lambdaClient = new AmazonLambdaClient(); var invokeRequest = new InvokeRequest { FunctionName = request.StageVariables["WorkerLambdaFunctionName"], InvocationType = "Event", LogType = "None", Payload = new { action = "deleteJobProcess", request = request, jobProcessId = job.JobProcess }.ToMcmaJson().ToString() }; await lambdaClient.InvokeAsync(invokeRequest); } }
/// <summary> /// Client will call to retrieve time slots that are currently available for the requested date and service window /// </summary> /// <param name="apiGatewayRequest"> /// Instance of ApiGatewayRequest object /// </param> /// <returns> /// Returns instance of ApiGateWayResponse object /// </returns> public ApiGateWayResponse GetAppointmentDetails(ApiGatewayRequest apiGatewayRequest) { ApiGateWayResponse apiGateWayResponse = new ApiGateWayResponse(); apiGateWayResponse.Login = apiGatewayRequest.Login; apiGateWayResponse.ReturnCode = ServiceStatus.Success; apiGateWayResponse.HostName = Environment.MachineName; apiGateWayResponse.TimeStamp = DateTime.Now; List <Message> messages = new List <Message>(); Message message = new Message(); message.MessageCode = "OK"; message.Description = "OK Description"; messages.Add(message); String payload = "<![CDATA[<AppointmentAvailabilityList> </AppointmentAvailabilityList>]]>"; apiGateWayResponse.Payload = payload; apiGateWayResponse.Messages = messages; return(apiGateWayResponse); }
public void GetAppointmentDetailsTest() { var svc = new AppointmentService(); var apiGatewayRequest = new ApiGatewayRequest { FromDate = DateTime.Now.AddDays(4), ToDate = DateTime.Now.AddDays(5), //)DateTime.Now.AddDays(1), ExternalOrgId = "033W", //477O PostalCode = "92128", //92127 TaskQueryType = new TaskQueryType() { Estimate = true }, TimeSlot = TimeSlot.ALL }; var result = svc.GetAppointmentDetails(apiGatewayRequest).ToList(); foreach (var r in result) { Assert.AreEqual(r.ReturnCode, ServiceStatus.Success); Assert.IsTrue(r.CapacityAvailable != 0); Assert.IsTrue(r.CapacityQuota != 0); Assert.IsTrue(r.DataKey != null); Assert.IsTrue(r.HostName != null); } }
/// <summary> /// Transfers values from ApiGateway to WebApi object /// </summary> /// <param name="apiGatewayRequest">Incoming request object from client</param> /// <returns>CapacityRequest object for call to GetCapacity WebAPI</returns> private static CapacityRequest InitializeCapacityRequest(ApiGatewayRequest apiGatewayRequest) { var capacityRequest = new CapacityRequest { ExternalOrgId = apiGatewayRequest.ExternalOrgId, FromDate = apiGatewayRequest.FromDate, PostalCode = apiGatewayRequest.PostalCode, ToDate = apiGatewayRequest.ToDate, TimeSlot = apiGatewayRequest.TimeSlot == null ? (ServiceWindow?)null : (ServiceWindow)apiGatewayRequest.TimeSlot, TaskQueryType = new DispatchServices.Data.Models.TaskQueryType { Audit = apiGatewayRequest.TaskQueryType.Audit, Catastrophe = apiGatewayRequest.TaskQueryType.Catastrophe, DeskReview = apiGatewayRequest.TaskQueryType.DeskReview, DriveIn = apiGatewayRequest.TaskQueryType.DriveIn, Estimate = apiGatewayRequest.TaskQueryType.Estimate, SalvageYard = apiGatewayRequest.TaskQueryType.SalvageYard, Supplement = apiGatewayRequest.TaskQueryType.Supplement } //ServiceWindow = apiGatewayRequest.ServiceWindow, //See below //TaskQueryType = apiGatewayRequest.TaskQueryType, //See below //ServerURL = apiGatewayRequest.ServerURL,//Set in Web API //UserCompany = apiGatewayRequest.UserCompany//Set in Web API }; return(capacityRequest); }
public static async Task ProcessNotificationAsync(ApiGatewayRequest request, McmaApiResponse response) { var table = new DynamoDbTable(request.StageVariables["TableName"]); var jobAssignmentId = request.StageVariables["PublicUrl"] + "/job-assignments/" + request.PathVariables["id"]; var jobAssignment = await table.GetAsync <JobAssignment>(jobAssignmentId); if (jobAssignment == null) { response.StatusCode = (int)HttpStatusCode.NotFound; response.StatusMessage = "No resource found on path '" + request.Path + "'"; return; } var notification = request.JsonBody?.ToMcmaObject <Notification>(); if (notification == null) { response.StatusCode = (int)HttpStatusCode.BadRequest; response.StatusMessage = "Missing notification in request body"; return; } var lambdaClient = new AmazonLambdaClient(); var invokeRequest = new InvokeRequest { FunctionName = request.StageVariables["WorkerLambdaFunctionName"], InvocationType = "Event", LogType = "None", Payload = new { action = "ProcessNotification", request = request, jobAssignmentId = jobAssignmentId, notification = notification }.ToMcmaJson().ToString() }; await lambdaClient.InvokeAsync(invokeRequest); }
public static async Task PutBmContentAsync(ApiGatewayRequest request, McmaApiResponse response) { Logger.Debug(nameof(PutBmContentAsync)); Logger.Debug(request.ToMcmaJson().ToString()); var bmContent = request.JsonBody?.ToMcmaObject <BMContent>(); if (bmContent == null) { response.StatusCode = (int)HttpStatusCode.BadRequest; response.StatusMessage = "Missing request body."; return; } var table = new DynamoDbTable(request.StageVariables["TableName"]); var bmContentId = request.StageVariables["PublicUrl"] + request.Path; bmContent.Id = bmContentId; bmContent.DateModified = DateTime.UtcNow; if (!bmContent.DateCreated.HasValue) { bmContent.DateCreated = bmContent.DateModified; } await table.PutAsync <BMContent>(bmContentId, bmContent); response.JsonBody = bmContent.ToMcmaJson(); }
public static async Task AddServiceAsync(ApiGatewayRequest request, McmaApiResponse response) { Logger.Debug(nameof(AddServiceAsync)); Logger.Debug(request.ToMcmaJson().ToString()); var service = request.JsonBody?.ToMcmaObject <Service>(); if (service == null) { response.StatusCode = (int)HttpStatusCode.BadRequest; response.StatusMessage = "Missing request body."; return; } var serviceId = request.StageVariables["PublicUrl"] + "/services/" + Guid.NewGuid(); service.Id = serviceId; service.DateCreated = DateTime.UtcNow; service.DateModified = service.DateCreated; var table = new DynamoDbTable(request.StageVariables["TableName"]); await table.PutAsync <Service>(serviceId, service); response.StatusCode = (int)HttpStatusCode.Created; response.Headers["Location"] = service.Id; response.JsonBody = service.ToMcmaJson(); Logger.Debug(response.ToMcmaJson().ToString()); }
public static async Task AddBmContentAsync(ApiGatewayRequest request, McmaApiResponse response) { Logger.Debug(nameof(AddBmContentAsync)); Logger.Debug(request.ToMcmaJson().ToString()); var bmContent = request.JsonBody?.ToMcmaObject <BMContent>(); if (bmContent == null) { response.StatusCode = (int)HttpStatusCode.BadRequest; response.StatusMessage = "Missing request body."; return; } var bmContentId = request.StageVariables["PublicUrl"] + "/bm-contents/" + Guid.NewGuid(); bmContent.Id = bmContentId; bmContent.Status = "NEW"; bmContent.DateCreated = DateTime.UtcNow; bmContent.DateModified = bmContent.DateCreated; var table = new DynamoDbTable(request.StageVariables["TableName"]); await table.PutAsync <BMContent>(bmContentId, bmContent); response.StatusCode = (int)HttpStatusCode.Created; response.Headers["Location"] = bmContent.Id; response.JsonBody = bmContent.ToMcmaJson(); Logger.Debug(response.ToMcmaJson().ToString()); }
public static async Task PutServiceAsync(ApiGatewayRequest request, McmaApiResponse response) { Logger.Debug(nameof(PutServiceAsync)); Logger.Debug(request.ToMcmaJson().ToString()); var service = request.JsonBody?.ToMcmaObject <Service>(); if (service == null) { response.StatusCode = (int)HttpStatusCode.BadRequest; response.StatusMessage = "Missing request body."; return; } var table = new DynamoDbTable(request.StageVariables["TableName"]); var serviceId = request.StageVariables["PublicUrl"] + request.Path; service.Id = serviceId; service.DateModified = DateTime.UtcNow; if (!service.DateCreated.HasValue) { service.DateCreated = service.DateModified; } await table.PutAsync <Service>(serviceId, service); response.JsonBody = service.ToMcmaJson(); }
public static async Task GetJobAssignmentsAsync(ApiGatewayRequest request, McmaApiResponse response) { Logger.Debug(nameof(GetJobAssignmentsAsync)); Logger.Debug(request.ToMcmaJson().ToString()); var table = new DynamoDbTable(request.StageVariables["TableName"]); response.JsonBody = (await table.GetAllAsync <JobAssignment>()).ToMcmaJson(); Logger.Debug(response.ToMcmaJson().ToString()); }
public static async Task ProcessNotificationAsync(ApiGatewayRequest request, McmaApiResponse response) { Logger.Debug(nameof(ProcessNotificationAsync)); Logger.Debug(request.ToMcmaJson().ToString()); var table = new DynamoDbTable(request.StageVariables["TableName"]); var jobAssignmentId = request.StageVariables["PublicUrl"] + "/job-assignments/" + request.PathVariables["id"]; var jobAssignment = await table.GetAsync <JobAssignment>(jobAssignmentId); Logger.Debug("jobAssignment = {0}", jobAssignment); if (jobAssignment == null) { Logger.Debug("jobAssignment not found", jobAssignment); response.StatusCode = (int)HttpStatusCode.NotFound; response.StatusMessage = "No resource found on path '" + request.Path + "'."; return; } var notification = request.QueryStringParameters; Logger.Debug("notification = {0}", notification); if (notification == null || !notification.Any()) { response.StatusCode = (int)HttpStatusCode.BadRequest; response.StatusMessage = "Missing notification in request Query String"; return; } // invoking worker lambda function that will process the notification var lambdaClient = new AmazonLambdaClient(); var invokeRequest = new InvokeRequest { FunctionName = request.StageVariables["WorkerLambdaFunctionName"], InvocationType = "Event", LogType = "None", Payload = new { action = "ProcessNotification", stageVariables = request.StageVariables, jobAssignmentId, notification }.ToMcmaJson().ToString() }; Logger.Debug("Invoking Lambda with payload: {0}", invokeRequest.Payload); await lambdaClient.InvokeAsync(invokeRequest); }
public static async Task GetBmEssencesAsync(ApiGatewayRequest request, McmaApiResponse response) { Logger.Debug(nameof(GetBmEssencesAsync)); Logger.Debug(request.ToMcmaJson().ToString()); var table = new DynamoDbTable(request.StageVariables["TableName"]); var essences = await table.GetAllAsync <BMEssence>(); response.JsonBody = essences.ToMcmaJson(); Logger.Debug(response.ToMcmaJson().ToString()); }
/// <summary> /// Client will call to retrieve time slots that are currently available for the requested date and service window /// </summary> /// <param name="apiGatewayRequest"> /// Instance of ApiGatewayRequest object /// </param> /// <returns> /// Returns instance of ApiGatewayResponse object /// </returns> public IEnumerable <ApiGatewayResponse> GetAppointmentDetails(ApiGatewayRequest apiGatewayRequest) { var requestId = Guid.NewGuid().ToString(); var url = WebOperationContext.Current == null || WebOperationContext.Current.IncomingRequest.UriTemplateMatch == null ? "GetAppointmentDetails" : WebOperationContext.Current.IncomingRequest.UriTemplateMatch.RequestUri.AbsoluteUri; var method = WebOperationContext.Current == null ? "POST" : WebOperationContext.Current.IncomingRequest.Method; LoggerRequestResponse.LogRequestInfo(requestId, url, method, apiGatewayRequest); var response = CapacityApiClient.GetApiGatewayResponses(apiGatewayRequest, ConfigurationManager.AppSettings["capacityPath"]); LoggerRequestResponse.LogResponseInfo(requestId, url, method, null, null, response); return(response); }
public static async Task AddJobAssignmentAsync(ApiGatewayRequest request, McmaApiResponse response) { Logger.Debug(nameof(AddJobAssignmentAsync)); Logger.Debug(request.ToMcmaJson().ToString()); var jobAssignment = request.JsonBody?.ToMcmaObject <JobAssignment>(); if (jobAssignment == null) { response.StatusCode = (int)HttpStatusCode.BadRequest; response.StatusMessage = "Missing request body."; return; } var jobAssignmentId = request.StageVariables["PublicUrl"] + "/job-assignments/" + Guid.NewGuid(); jobAssignment.Id = jobAssignmentId; jobAssignment.Status = "NEW"; jobAssignment.DateCreated = DateTime.UtcNow; jobAssignment.DateModified = jobAssignment.DateCreated; var table = new DynamoDbTable(request.StageVariables["TableName"]); await table.PutAsync <JobAssignment>(jobAssignmentId, jobAssignment); response.StatusCode = (int)HttpStatusCode.Created; response.Headers["Location"] = jobAssignment.Id; response.JsonBody = jobAssignment.ToMcmaJson(); Logger.Debug(response.ToMcmaJson().ToString()); // invoking worker lambda function that will create a jobAssignment assignment for this new jobAssignment var lambdaClient = new AmazonLambdaClient(); var invokeRequest = new InvokeRequest { FunctionName = request.StageVariables["WorkerLambdaFunctionName"], InvocationType = "Event", LogType = "None", Payload = new { action = "ProcessJobAssignment", stageVariables = request.StageVariables, jobAssignmentId = jobAssignmentId }.ToMcmaJson().ToString() }; await lambdaClient.InvokeAsync(invokeRequest); }
public static async Task DeleteJobAssignmentsAsync(ApiGatewayRequest request, McmaApiResponse response) { Logger.Debug(nameof(DeleteJobAssignmentsAsync)); Logger.Debug(request.ToMcmaJson().ToString()); var table = new DynamoDbTable(request.StageVariables["TableName"]); var jobAssignments = await table.GetAllAsync <JobAssignment>(); foreach (var jobAssignment in jobAssignments) { await table.DeleteAsync <JobAssignment>(jobAssignment.Id); } Logger.Debug(response.ToMcmaJson().ToString()); }
public void GetAppointmentDetailsNoTaskQueryTypeTest() { var svc = new AppointmentService(); var apiGatewayRequest = new ApiGatewayRequest { ExternalOrgId = "477O", //TaskQueryType = new string[] { "Estimate" }, TimeSlot = TimeSlot.ALL }; var result = svc.GetAppointmentDetails(apiGatewayRequest).First(); Assert.AreEqual(result.ReturnCode, ServiceStatus.Failed); Assert.IsTrue(result.Message.Contains("TaskQueryType is required")); }
public static async Task GetServiceAsync(ApiGatewayRequest request, McmaApiResponse response) { Logger.Debug(nameof(GetServiceAsync)); Logger.Debug(request.ToMcmaJson().ToString()); var table = new DynamoDbTable(request.StageVariables["TableName"]); var serviceId = request.StageVariables["PublicUrl"] + request.Path; response.JsonBody = (await table.GetAsync <Service>(serviceId))?.ToMcmaJson(); if (response.JsonBody == null) { response.StatusCode = (int)HttpStatusCode.NotFound; response.StatusMessage = "No resource found on path '" + request.Path + "'."; } }
public static async Task GetServicesAsync(ApiGatewayRequest request, McmaApiResponse response) { Logger.Debug(nameof(GetServicesAsync)); Logger.Debug(request.ToMcmaJson().ToString()); var table = new DynamoDbTable(request.StageVariables["TableName"]); var services = await table.GetAllAsync <Service>(); if (request.QueryStringParameters.Any()) { services.Filter(request.QueryStringParameters); } response.JsonBody = services.ToMcmaJson(); Logger.Debug(response.ToMcmaJson().ToString()); }
public static async Task CancelJobAsync(ApiGatewayRequest request, McmaApiResponse response) { var table = new DynamoDbTable(request.StageVariables["TableName"]); var jobId = request.StageVariables["PublicUrl"] + "/jobs/" + request.PathVariables["id"]; var job = await table.GetAsync <Job>(jobId); if (job == null) { response.StatusCode = (int)HttpStatusCode.NotFound; response.StatusMessage = "No resource found on path '" + request.Path + "'"; return; } response.StatusCode = (int)HttpStatusCode.NotImplemented; response.StatusMessage = "Canceling job is not implemented"; }
public static async Task GetJobAssignmentAsync(ApiGatewayRequest request, McmaApiResponse response) { Logger.Debug(nameof(GetJobAssignmentAsync)); Logger.Debug(request.ToMcmaJson().ToString()); var table = new DynamoDbTable(request.StageVariables["TableName"]); var jobAssignmentId = request.StageVariables["PublicUrl"] + request.Path; var jobAssignment = await table.GetAsync <JobAssignment>(jobAssignmentId); response.JsonBody = jobAssignment != null?jobAssignment.ToMcmaJson() : null; if (response.JsonBody == null) { response.StatusCode = (int)HttpStatusCode.NotFound; response.StatusMessage = "No resource found on path '" + request.Path + "'."; } }
public void GetAppointmentDetailsNoPostalCodeCannotResolveTest() { var svc = new AppointmentService(); var apiGatewayRequest = new ApiGatewayRequest { ExternalOrgId = "477O", TaskQueryType = new TaskQueryType() { Estimate = true }, TimeSlot = TimeSlot.ALL }; var result = svc.GetAppointmentDetails(apiGatewayRequest).First(); Assert.AreEqual(result.ReturnCode, ServiceStatus.Failed); Assert.IsTrue(result.Message.Contains("Cannot resolve ExternalOrgId/PostalCode to an office")); }
public void GetAppointmentDetailsNoExtOrgIdTest() { var svc = new AppointmentService(); var apiGatewayRequest = new ApiGatewayRequest { //ExternalOrgId = "033", TaskQueryType = new TaskQueryType() { Estimate = true }, TimeSlot = TimeSlot.ALL }; var result = svc.GetAppointmentDetails(apiGatewayRequest).First(); Assert.AreEqual(result.ReturnCode, ServiceStatus.Failed); Assert.IsTrue(result.Message.Contains("ExternalOrgId is required")); }
public void GetAppointmentDetailsZipOutOfRangeTest() { var svc = new AppointmentService(); var apiGatewayRequest = new ApiGatewayRequest { ExternalOrgId = "XXX", //mexico PostalCode = "92127", TaskQueryType = new TaskQueryType() { Estimate = true }, TimeSlot = TimeSlot.ALL }; var result = svc.GetAppointmentDetails(apiGatewayRequest).First(); Assert.AreEqual(result.ReturnCode, ServiceStatus.Failed); Assert.IsTrue(result.Message.Contains("No external office found")); }
public static async Task GetJobProfilesAsync(ApiGatewayRequest request, McmaApiResponse response) { Logger.Debug(nameof(GetJobProfilesAsync)); Logger.Debug(request.ToMcmaJson().ToString()); var table = new DynamoDbTable(request.StageVariables["TableName"]); var jobProfiles = await table.GetAllAsync <JobProfile>(); if (request.QueryStringParameters.Any()) { Logger.Debug( "Applying job profile filter from query string: " + string.Join(", ", request.QueryStringParameters.Select(kvp => $"{kvp.Key}={kvp.Value}"))); jobProfiles.Filter(request.QueryStringParameters); } response.JsonBody = jobProfiles.ToMcmaJson(); Logger.Debug(response.ToMcmaJson().ToString()); }
public void GetAppointmentDetailsBadExternalOrgIdNoZipTest() { var svc = new AppointmentService(); var apiGatewayRequest = new ApiGatewayRequest { ExternalOrgId = "YYY", //PostalCode = "92127", TaskQueryType = new TaskQueryType() { Estimate = true }, TimeSlot = TimeSlot.ALL }; var result = svc.GetAppointmentDetails(apiGatewayRequest).First(); Assert.AreEqual(result.ReturnCode, ServiceStatus.Failed); Assert.IsTrue(result.Message.Contains("Could not find LDAP ID for the given region legacy id")); }
public static async Task DeleteBmEssenceAsync(ApiGatewayRequest request, McmaApiResponse response) { Logger.Debug(nameof(DeleteBmEssenceAsync)); Logger.Debug(request.ToMcmaJson().ToString()); var table = new DynamoDbTable(request.StageVariables["TableName"]); var bmEssenceId = request.StageVariables["PublicUrl"] + request.Path; var bmEssence = await table.GetAsync <BMEssence>(bmEssenceId); if (bmEssence == null) { response.StatusCode = (int)HttpStatusCode.NotFound; response.StatusMessage = "No resource found on path '" + request.Path + "'."; return; } await table.DeleteAsync <BMEssence>(bmEssenceId); }
public static IEnumerable <ApiGatewayResponse> GetApiGatewayResponses(ApiGatewayRequest apiGatewayRequest, string capacityUrl) { var apiGatewayResponses = new List <ApiGatewayResponse>(); if (apiGatewayRequest == null) { Logger.Error("GetAppointmentDetails Receieved Null Request"); return(CreateErrorResponse(apiGatewayResponses, "ApiGatewayRequest must not be null.")); } try { Logger.Debug("GetAppointmentDetails received request: " + JsonConvert.SerializeObject(apiGatewayRequest)); var capacityRequest = InitializeCapacityRequest(apiGatewayRequest); Logger.Debug("About to call: JsonConvert.SerializeObject(capacityRequest);"); var postBody = JsonConvert.SerializeObject(capacityRequest); Logger.Debug($"successfully called: SerializeObject(capacityRequest), resulting postBody: {postBody}"); using (var client = new HttpClient()) { Logger.Debug($"About to call: client.PostAsync({capacityUrl}, ...)"); //Call GetCapacity WebAPI using (var response = client.PostAsync(capacityUrl, new StringContent(postBody, Encoding.UTF8, "application/json")).Result) { if (response.StatusCode == HttpStatusCode.OK) { var result = response.Content.ReadAsStringAsync().Result; Logger.Debug($"StatusCode == OK, result={result}"); Logger.Debug("About to Deserialize(result)..."); var capacityResponses = JsonConvert.DeserializeObject <IEnumerable <CapacityResponse> >(result); apiGatewayResponses.AddRange(capacityResponses.Select(cr => new ApiGatewayResponse() { CapacityAvailable = cr.CapacityAvailable, CapacityQuota = cr.CapacityQuota, DataKey = cr.DataKey, EndTime = cr.EndTime, HostName = Environment.MachineName, Login = apiGatewayRequest.Login, Resource = cr.Resource, ReturnCode = ServiceStatus.Success, StartTime = cr.StartTime, Message = "OK", TaskType = (TaskType)cr.TaskType, TimeStamp = DateTime.Now })); } else { var result = response.Content.ReadAsStringAsync().Result; Logger.Debug($"StatusCode != OK, result={result}"); Logger.Debug("About to Deserialize(result)..."); var error = JsonConvert.DeserializeObject <HttpError>(result); Logger.Debug($"About to CreateErrorResponse with error {error.Message}"); return(CreateErrorResponse(apiGatewayResponses, error.Message)); } } } } catch (Exception ex) { Logger.Debug($"About to CreateErrorResponse with error {ex.Message}..."); return(CreateErrorResponse(apiGatewayResponses, $"GetAppointmentDetails threw this exception: {ex.Message}")); } return(apiGatewayResponses); }