Skip to content

Commit

Permalink
document changes
Browse files Browse the repository at this point in the history
  • Loading branch information
paullocknimble committed May 24, 2024
1 parent 47d8414 commit 801aafa
Show file tree
Hide file tree
Showing 16 changed files with 364 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ public class AcademyConversionProject
public int Id { get; set; }
public int? Urn { get; set; }
public int? FormAMatProjectId { get; set; }
public Guid? SharePointId { get; set; }
public bool? IsFormAMat { get; set; }
public DateTime CreatedOn { get; set; }
public string SchoolName { get; set; }
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
namespace Dfe.PrepareConversions.Configuration
{
public class SharePointApiOptions
{
public bool Enabled { get; set; }
public string ApiUrl { get; set; }
public string ClientId { get; set; }
public string Secret { get; set; }
public string Authority { get; set; }
}
}
13 changes: 13 additions & 0 deletions Dfe.PrepareConversions/Dfe.PrepareConversions/Models/Links.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using DocumentFormat.OpenXml.InkML;
using System;
using System.Collections.Generic;

Expand All @@ -9,6 +10,9 @@ public static class Links
private static string _transfersUrl;
public static string TransfersUrl => _transfersUrl;

private static bool _isProjectDocumentsEnabled;
public static bool IsProjectDocumentsEnabled => _isProjectDocumentsEnabled;

private static LinkItem AddLinkItem(string page, string backText = "Back")
{
LinkItem item = new() { Page = page, BackText = backText };
Expand All @@ -19,6 +23,10 @@ public static void InitializeTransfersUrl(string transfersUrl)
{
_transfersUrl = transfersUrl;
}

public static void InializeProjectDocumentsEnabled(bool isProjectDocumentsEnabled) {
_isProjectDocumentsEnabled = isProjectDocumentsEnabled;
}
public static LinkItem ByPage(string page)
{
return _links.Find(x => string.Equals(page, x.Page, StringComparison.InvariantCultureIgnoreCase));
Expand Down Expand Up @@ -64,6 +72,11 @@ public static class ProjectNotes
public static readonly LinkItem NewNote = AddLinkItem(page: "/ProjectNotes/NewNote");
}

public static class ProjectDocuments
{
public static readonly LinkItem Index = AddLinkItem(page: "/ProjectDocuments/Index");
}

public static class TaskList
{
public static readonly LinkItem Index = AddLinkItem(backText: "Back", page: "/TaskList/Index");
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
using Dfe.PrepareConversions.Data;

using Dfe.PrepareConversions.Data;
using Dfe.PrepareConversions.Data.Models;
using Dfe.PrepareConversions.Data.Services;
using Dfe.PrepareConversions.Models;
using Dfe.PrepareConversions.ViewModels;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Configuration;
using System.Security.Claims;
using System.Threading.Tasks;

Expand Down Expand Up @@ -46,6 +48,7 @@ protected async Task<IActionResult> SetProject(int id)
}

Project = new ProjectViewModel(project.Body);

return Page();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
@page "/project-documents/{id:int}"
@using Dfe.PrepareConversions.Data.Models
@using Dfe.PrepareConversions.Services.Helpers
@model Dfe.PrepareConversions.Pages.ProjectDocuments.IndexModel
@{
ViewData["Title"] = "Project documents";
}

@section BeforeMain
{
<a asp-page="@Model.ReturnPage" asp-route-id="@Model.ReturnId" class="govuk-back-link">@Links.ProjectList.Index.BackText</a>
}

<partial name="Shared/_ProjectHeader" model="Model.Project" />

<div class="govuk-grid-row">
<div class="govuk-grid-column-two-thirds">
<form asp-page-handler="GetFile" method="get">


<partial name="Shared/_FilesPartial" model='new FilesViewModel {
Urn = Model.Project.SchoolURN,
EntityId = Model.Project.SharePointId.Value,
ApplicationReference = Model.Project.ApplicationReferenceNumber,
FilePrefixSection = FileUploadConstants.ResolutionConsentfilePrefixFieldName,
SectionName = "Resolution Consent",
FileNames = Model.ResolutionConsentFileNames
}' />
</form>
<partial name="Shared/_FilesPartial" model='new FilesViewModel {
Urn = Model.Project.SchoolURN,
EntityId = Model.Project.SharePointId.Value,
ApplicationReference = Model.Project.ApplicationReferenceNumber,
FilePrefixSection = FileUploadConstants.DioceseFilePrefixFieldName,
SectionName = "Diocese",
FileNames = Model.DioceseFileNames
}' />
</div>
</div>
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
using AngleSharp.Io.Dom;
using Dfe.PrepareConversions.Data.Services;
using Dfe.PrepareConversions.Models;
using Dfe.PrepareConversions.Services;
using Dfe.PrepareConversions.Services.Helpers;
using Dfe.PrepareConversions.ViewModels;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net;
using System.Threading.Tasks;

namespace Dfe.PrepareConversions.Pages.ProjectDocuments;

public class IndexModel : BaseAcademyConversionProjectPageModel
{
private readonly IFileService _fileService;

public string ReturnPage { get; set; }
public string ReturnId { get; set; }

public IndexModel(IAcademyConversionProjectRepository repository, IFileService fileService) : base(repository)
{
_fileService = fileService;
}

[BindProperty]
public List<string> DioceseFileNames { get; set; }
[BindProperty]
public List<string> ResolutionConsentFileNames { get; private set; }

public override async Task<IActionResult> OnGetAsync(int id)
{
await base.OnGetAsync(id);

DioceseFileNames = await _fileService.GetFiles(FileUploadConstants.TopLevelSchoolFolderName, Project.SharePointId.ToString(), Project.ApplicationReferenceNumber, FileUploadConstants.DioceseFilePrefixFieldName);
//TempDataHelper.StoreSerialisedValue($"{EntityId}-dioceseFiles", TempData, DioceseFileNames);
//FoundationConsentFileNames = await _fileUploadService.GetFiles(FileUploadConstants.TopLevelSchoolFolderName, EntityId.ToString(), ApplicationReference, FileUploadConstants.FoundationConsentFilePrefixFieldName);

ResolutionConsentFileNames = await _fileService.GetFiles(FileUploadConstants.TopLevelSchoolFolderName, Project.SharePointId.ToString(), Project.ApplicationReferenceNumber, FileUploadConstants.ResolutionConsentfilePrefixFieldName);

return Page();
}

public async Task<HttpResponseMessage> GetFile(string entityName, string recordId, string recordName, string fieldName, string fileName)
{
//if (String.IsNullOrEmpty(id))
// return Request.CreateResponse(HttpStatusCode.BadRequest);

var file = await _fileService.DownloadFile(entityName, recordId, recordName, fieldName, fileName);

HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);

response.Content = new StreamContent(GenerateStreamFromString(file));
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = fileName;
//response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");

return response;
}

public static Stream GenerateStreamFromString(string s)
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
@model Dfe.PrepareConversions.ViewModels.FilesViewModel

<legend class="govuk-fieldset__legend govuk-fieldset__legend--s">
@Model.SectionName files
</legend>
<hr />


@foreach (var fileName in Model.FileNames)
{
<table class="govuk-table">
<tbody class="govuk-table__body">
<tr class="govuk-table__row">
<td class="govuk-table__cell govuk-!-text-align-left">
<p class="govuk-label">@fileName</p>
</td>
<td><button class="btn btn-default">Download</button></td>


</tr>

</tbody>
</table>
}
Original file line number Diff line number Diff line change
Expand Up @@ -60,5 +60,12 @@
Project notes
</sub-menu-link>
</li>
<li if="@Links.IsProjectDocumentsEnabled" class="moj-sub-navigation__item">
<sub-menu-link class="moj-sub-navigation__link"
asp-page="@Links.ProjectDocuments.Index.Page"
asp-route-id="@id">
Project documents
</sub-menu-link>
</li>
</ul>
</nav>
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using Dfe.PrepareConversions.Services;
using Dfe.PrepareConversions.ViewModels;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Primitives;
using System.Linq;
using System.Net;
Expand All @@ -14,14 +15,16 @@ namespace Dfe.PrepareConversions.Pages.TaskList;
public class IndexModel : BaseAcademyConversionProjectPageModel
{
private readonly ErrorService _errorService;
private readonly IConfiguration _configuration;
private readonly KeyStagePerformanceService _keyStagePerformanceService;

public IndexModel(KeyStagePerformanceService keyStagePerformanceService,
IAcademyConversionProjectRepository repository,
ErrorService errorService) : base(repository)
ErrorService errorService, IConfiguration configuration) : base(repository)
{
_keyStagePerformanceService = keyStagePerformanceService;
_errorService = errorService;
_configuration = configuration;
}

public bool ShowGenerateHtbTemplateError { get; set; }
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Dfe.PrepareConversions.Services.Helpers;
using Microsoft.VisualBasic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Dfe.PrepareConversions.Services;

public interface IFileService
{
Task<List<string>> GetFiles(string entityName, string recordId, string recordName, string fieldName);
Task<string> DownloadFile(string entityName, string recordId, string recordName, string fieldName, string fileName);
}

public class FileService : IFileService
{
private readonly HttpClient _httpClient;
private readonly IAadAuthorisationHelper _aadAuthorisationHelper;

public FileService() { }

public FileService(HttpClient httpClient, IAadAuthorisationHelper aadAuthorisationHelper)
{
_httpClient = httpClient;
_aadAuthorisationHelper = aadAuthorisationHelper;
}

public async Task<List<string>> GetFiles(string entityName, string recordId, string recordName, string fieldName)
{
var url = $"?entityName={entityName}&recordName={recordName}&recordId={recordId}&fieldName={fieldName}";

using var request = new HttpRequestMessage(HttpMethod.Get, url);

var content = await DoHttpRequest(request);

return ParseJResponse(content);
}

public async Task<string> DownloadFile(string entityName, string recordId, string recordName, string fieldName, string fileName)
{
var url = $@"download?entityName={entityName}&recordName={recordName}&recordId={recordId}&fieldName={fieldName}&fileName={fileName}";

using var request = new HttpRequestMessage(HttpMethod.Get, url);
var content = await DoHttpRequest(request);

return content;

}

private async Task<string> DoHttpRequest(HttpRequestMessage request)
{
var accessToken = await _aadAuthorisationHelper.GetAccessToken();
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

var response = await _httpClient.SendAsync(request);
var content = await response.Content.ReadAsStringAsync();

if (!response.IsSuccessStatusCode)
throw new Exception($"The file service failed with a status of {response.ReasonPhrase} {content}");

var receiveStream = await response.Content.ReadAsStreamAsync();
using var readStream = new StreamReader(receiveStream, Encoding.UTF8);
return await readStream.ReadToEndAsync();
}

private List<string> ParseJResponse(string content)
{
var jobject = JObject.Parse(content);
var jfiles = (JArray)jobject?.GetValue("Files", StringComparison.OrdinalIgnoreCase)!;
return jfiles.Select(x => (string)x).ToList();
}

internal static string GetJsonAsString(JObject jObject)
{
var sb = new StringBuilder();
sb.Append("\"");
using (var sw = new StringWriter(sb))
using (var writer = new JsonTextWriter(sw))
{
writer.QuoteChar = '\'';

var ser = new JsonSerializer();
ser.Serialize(writer, jObject);
}

sb.Append("\"");

return sb.ToString();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Identity.Client;
using System.Threading.Tasks;

namespace Dfe.PrepareConversions.Services.Helpers;

public interface IAadAuthorisationHelper
{
Task<string> GetAccessToken();
}

public class AadAuthorisationHelper : IAadAuthorisationHelper
{
private readonly IConfiguration _configuration;

public AadAuthorisationHelper(IConfiguration configuration)
{
_configuration = configuration;
}
public async Task<string> GetAccessToken()
{
var app = ConfidentialClientApplicationBuilder
.Create(_configuration["Sharepoint:ClientId"])
.WithClientSecret(_configuration["Sharepoint:Secret"])
.WithAuthority(AzureCloudInstance.AzurePublic, _configuration["Sharepoint:TenantId"])
.Build();

var result = app.AcquireTokenForClient(new string[] { $"{_configuration["Sharepoint:Authority"]}/.default" });

return (await result.ExecuteAsync()).AccessToken;
}
}
Loading

0 comments on commit 801aafa

Please sign in to comment.