2023-04-22 21:42:57 -07:00

175 lines
8.5 KiB
C#

using Adaptation.FileHandlers.ConvertExcelToJson;
using Adaptation.FileHandlers.json.WorkItems;
using Adaptation.Shared;
using Adaptation.Shared.Duplicator;
using Adaptation.Shared.Methods;
using Microsoft.TeamFoundation.WorkItemTracking.WebApi;
using Microsoft.VisualStudio.Services.WebApi.Patch;
using Microsoft.VisualStudio.Services.WebApi.Patch.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace Adaptation.FileHandlers.json;
public class ProcessData : IProcessData
{
private readonly List<object> _Details;
List<object> Shared.Properties.IProcessData.Details => _Details;
public ProcessData(IFileRead fileRead, Logistics logistics, List<FileInfo> fileInfoCollection, HttpClient httpClient, string basePage, string api, string query, WorkItemTrackingHttpClient workItemTrackingHttpClient, string project, string json)
{
fileInfoCollection.Clear();
_Details = new List<object>();
Parse(fileRead, logistics, fileInfoCollection, httpClient, basePage, api, query, workItemTrackingHttpClient, project, json);
}
string IProcessData.GetCurrentReactor(IFileRead fileRead, Logistics logistics, Dictionary<string, string> reactors)
=> throw new Exception(string.Concat("See ", nameof(Parse)));
Tuple<string, Test[], JsonElement[], List<FileInfo>> IProcessData.GetResults(IFileRead fileRead, Logistics logistics, List<FileInfo> fileInfoCollection)
=> new(logistics.Logistics1[0], Array.Empty<Test>(), Array.Empty<JsonElement>(), fileInfoCollection);
internal static List<Description> GetDescriptions(JsonElement[] jsonElements) => throw new NotImplementedException();
#nullable enable
private static void AddPatch(JsonPatchDocument document, string path, object value) => document.Add(new JsonPatchOperation { From = null, Operation = Operation.Add, Path = path, Value = value });
private static Dictionary<string, FIBacklogMesa> GetFIBacklogMesaCollection(string json, string keySection)
{
Dictionary<string, FIBacklogMesa> results = new();
string key;
FIBacklogMesa[]? fiBacklogMesaCollection;
fiBacklogMesaCollection = JsonSerializer.Deserialize<FIBacklogMesa[]>(json, new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
if (fiBacklogMesaCollection is null || !fiBacklogMesaCollection.Any())
throw new NullReferenceException();
foreach (FIBacklogMesa fIBacklogMesa in fiBacklogMesaCollection)
{
if (string.IsNullOrEmpty(fIBacklogMesa.Requestor))
continue;
if (string.IsNullOrEmpty(fIBacklogMesa.Req))
continue;
key = $"{fIBacklogMesa.Requestor.Split(' ').First()}{keySection}{fIBacklogMesa.Req}";
if (results.ContainsKey(key))
continue;
results.Add(key, fIBacklogMesa);
}
return results;
}
private static string GetIds(HttpClient httpClient, string basePage, string api, string query)
{
StringBuilder result = new();
Task<HttpResponseMessage> httpResponseMessageTask = httpClient.GetAsync(string.Concat(basePage, api, query));
httpResponseMessageTask.Wait();
if (!httpResponseMessageTask.Result.IsSuccessStatusCode)
throw new Exception(httpResponseMessageTask.Result.StatusCode.ToString());
Task<Stream> streamTask = httpResponseMessageTask.Result.Content.ReadAsStreamAsync();
streamTask.Wait();
if (!streamTask.Result.CanRead)
throw new NullReferenceException(nameof(streamTask));
WIQL.Root? root = JsonSerializer.Deserialize<WIQL.Root>(streamTask.Result, new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
streamTask.Result.Dispose();
if (root is null || root.WorkItems is null)
throw new NullReferenceException(nameof(root));
foreach (WIQL.WorkItem workItem in root.WorkItems)
_ = result.Append(workItem.Id).Append(',');
if (result.Length > 0)
_ = result.Remove(result.Length - 1, 1);
return result.ToString();
}
private static Value[] GetWorkItems(HttpClient httpClient, string basePage, string api, string ids)
{
Value[]? results;
// List<Value> results = new();
// Value? value;
Task<HttpResponseMessage> httpResponseMessageTask = httpClient.GetAsync(string.Concat(basePage, api, $"/workitems?ids={ids}"));
httpResponseMessageTask.Wait();
if (!httpResponseMessageTask.Result.IsSuccessStatusCode)
throw new Exception(httpResponseMessageTask.Result.StatusCode.ToString());
Task<Stream> streamTask = httpResponseMessageTask.Result.Content.ReadAsStreamAsync();
streamTask.Wait();
if (!streamTask.Result.CanRead)
throw new NullReferenceException(nameof(streamTask));
JsonElement? jsonElement = JsonSerializer.Deserialize<JsonElement>(streamTask.Result);
if (jsonElement is null || jsonElement.Value.ValueKind != JsonValueKind.Object)
throw new NullReferenceException(nameof(jsonElement));
results = JsonSerializer.Deserialize<Value[]>(jsonElement.Value.EnumerateObject().Last().Value);
if (results is null || !results.Any())
throw new NullReferenceException(nameof(results));
return results;
}
private static Value[] GetExtra(string keySection, IReadOnlyList<Value> workItems, Dictionary<string, FIBacklogMesa> keyToFIBacklogMesa)
{
List<Value> results = new();
foreach (Value value in workItems)
{
if (!value.Fields.SystemTitle.Contains(keySection))
continue;
if (keyToFIBacklogMesa.Remove(value.Fields.SystemTitle))
continue;
results.Add(value);
}
return results.ToArray();
}
private static string GetDescription(FIBacklogMesa fiBacklogMesa, DateTime dateTime) =>
$"Req:{fiBacklogMesa.Req}; Submitted:{(dateTime == DateTime.MinValue ? fiBacklogMesa.Submitted : dateTime.ToString("d-MMM-yy"))}; Requestor:{fiBacklogMesa.Requestor}; AssignedTo:{fiBacklogMesa.AssignedTo}; SecondResource:{fiBacklogMesa.SecondResource}; Systems:{fiBacklogMesa.SystemS}; ";
private void Parse(IFileRead fileRead, Logistics logistics, List<FileInfo> fileInfoCollection, HttpClient httpClient, string basePage, string api, string query, WorkItemTrackingHttpClient workItemTrackingHttpClient, string project, string json)
{
if (fileRead is null)
throw new NullReferenceException();
if (logistics is null)
throw new NullReferenceException();
if (fileInfoCollection is null)
throw new NullReferenceException();
int counter = 0;
DateTime dateTime;
string description;
string keySection = " UAT for ";
string ids = GetIds(httpClient, basePage, api, query);
Value[] workItems = GetWorkItems(httpClient, basePage, api, ids);
Task<Microsoft.TeamFoundation.WorkItemTracking.WebApi.Models.WorkItem> workItemTask;
Dictionary<string, FIBacklogMesa> keyToFIBacklogMesa = GetFIBacklogMesaCollection(json, keySection);
int count = keyToFIBacklogMesa.Count;
Value[] extra = GetExtra(keySection, workItems, keyToFIBacklogMesa);
if (count != extra.Length)
{ }
if (count != keyToFIBacklogMesa.Count)
{ }
_Details.AddRange(workItems);
foreach (KeyValuePair<string, FIBacklogMesa> keyValuePair in keyToFIBacklogMesa)
{
if (counter > 5)
break;
JsonPatchDocument document = new();
if (!DateTime.TryParse(keyValuePair.Value.Submitted, out dateTime))
dateTime = DateTime.MinValue;
AddPatch(document, "/fields/System.AreaPath", project);
description = GetDescription(keyValuePair.Value, dateTime);
AddPatch(document, "/fields/System.Title", keyValuePair.Key);
AddPatch(document, "/fields/System.Description", description);
AddPatch(document, "/fields/System.IterationPath", $"{project}\\(Default)");
// AddPatch(document, "/fields/System.AssignedTo", "Mike.Phares@infineon.com");
if (!fileRead.IsEAFHosted)
continue;
workItemTask = workItemTrackingHttpClient.CreateWorkItemAsync(document, project, "Task");
workItemTask.Wait();
counter++;
if (workItemTask.Result is null)
continue;
}
}
}