Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added support for displaying a text if the user is previewing the pdf #904

Merged
merged 11 commits into from
Nov 15, 2024
7 changes: 1 addition & 6 deletions src/Altinn.App.Api/Controllers/PdfController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -73,19 +73,14 @@ public async Task<ActionResult> GetPdfPreview(
[FromRoute] Guid instanceGuid
)
{
if (_env.IsProduction())
{
return NotFound();
}

var instance = await _instanceClient.GetInstance(app, org, instanceOwnerPartyId, instanceGuid);
string? taskId = instance.Process?.CurrentTask?.ElementId;
if (instance == null || taskId == null)
{
return NotFound("Did not find instance or task");
}

Stream pdfContent = await _pdfService.GeneratePdf(instance, taskId, CancellationToken.None);
Stream pdfContent = await _pdfService.GeneratePdf(instance, taskId, true, CancellationToken.None);
return new FileStreamResult(pdfContent, "application/pdf");
}

Expand Down
13 changes: 13 additions & 0 deletions src/Altinn.App.Core/Internal/Pdf/IPdfService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,17 @@ public interface IPdfService
/// <param name="taskId">The task id for witch the pdf is generated</param>
/// <param name="ct">Cancellation Token for when a request should be stopped before it's completed.</param>
Task<Stream> GeneratePdf(Instance instance, string taskId, CancellationToken ct);

// <inheritdoc cref="GeneratePdf(Instance, string, CancellationToken)" select="summary"/>
/// <param name="instance">
/// <inheritdoc cref="GeneratePdf(Instance, string, CancellationToken)" path="/param[@name='instance']"/>
/// </param>
/// <param name="taskId">
/// <inheritdoc cref="GeneratePdf(Instance, string, CancellationToken)" path="/param[@name='taskId']"/>
/// </param>
/// <param name="ct">
/// <inheritdoc cref="GeneratePdf(Instance, string, CancellationToken)" path="/param[@name='ct']"/>
/// </param>
/// <param name="isPreview">Indicates whether the PDF is a preview version.</param>
Task<Stream> GeneratePdf(Instance instance, string taskId, bool isPreview, CancellationToken ct);
}
53 changes: 48 additions & 5 deletions src/Altinn.App.Core/Internal/Pdf/PdfService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,14 +84,14 @@

TextResource? textResource = await GetTextResource(instance, language);

var pdfContent = await GeneratePdfContent(instance, taskId, language, textResource, ct);
var pdfContent = await GeneratePdfContent(instance, language, false, textResource, ct);

string fileName = GetFileName(instance, textResource);
await _dataClient.InsertBinaryData(instance.Id, PdfElementType, PdfContentType, fileName, pdfContent, taskId);
}

/// <inheritdoc/>
public async Task<Stream> GeneratePdf(Instance instance, string taskId, CancellationToken ct)
public async Task<Stream> GeneratePdf(Instance instance, string taskId, bool isPreview, CancellationToken ct)
{
using var activity = _telemetry?.StartGeneratePdfActivity(instance, taskId);

Expand All @@ -103,13 +103,19 @@

TextResource? textResource = await GetTextResource(instance, language);

return await GeneratePdfContent(instance, taskId, language, textResource, ct);
return await GeneratePdfContent(instance, language, isPreview, textResource, ct);
}

/// <inheritdoc/>
public async Task<Stream> GeneratePdf(Instance instance, string taskId, CancellationToken ct)
{
return await GeneratePdf(instance, taskId, false, ct);
}

private async Task<Stream> GeneratePdfContent(
Instance instance,
string taskId,
string language,
bool isPreview,
TextResource? textResource,
CancellationToken ct
)
Expand All @@ -122,7 +128,17 @@
Uri uri = BuildUri(baseUrl, pagePath, language);

bool displayFooter = _pdfGeneratorSettings.DisplayFooter;
string? footerContent = displayFooter ? GetFooterContent(instance, textResource) : null;

string? footerContent = null;

if (isPreview == true)

Check notice

Code scanning / CodeQL

Unnecessarily complex Boolean expression Note

The expression 'A == true' can be simplified to 'A'.
adamhaeger marked this conversation as resolved.
Show resolved Hide resolved
{
footerContent = GetPreviewFooter(textResource);
}
else if (displayFooter)
{
footerContent = GetFooterContent(instance, textResource);
}

Stream pdfContent = await _pdfGeneratorClient.GeneratePdf(uri, footerContent, ct);

Expand Down Expand Up @@ -249,12 +265,39 @@
return null;
}

private static string GetPdfPreviewText(TextResource? textResource)
{
if (textResource is not null)
{
TextResourceElement? titleText = textResource.Resources.Find(textResourceElement =>
textResourceElement.Id.Equals("pdfPreviewText", StringComparison.Ordinal)
);

if (titleText is not null)
{
return titleText.Value;
}
}

return "Dokumentet er en forhåndsvisning";
}

private static string GetValidFileName(string fileName)
{
fileName = Uri.EscapeDataString(fileName.AsFileName(false));
return fileName;
}

private static string GetPreviewFooter(TextResource? textResource)
{
string previewText = GetPdfPreviewText(textResource);
return $@"<div style='font-family: Inter; font-size: 12px; width: 100%; display: flex; flex-direction: row; align-items: center; gap: 12px; padding: 0 70px 0 70px;'>
<div style='display: flex; flex-direction: row; width: 100%; align-items: center; font-style: italic; color: #e02e49;'>
<span>{previewText}</span>
</div>
</div>";
}

private string GetFooterContent(Instance instance, TextResource? textResource)
{
TimeZoneInfo timeZone = TimeZoneInfo.Utc;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public async Task End(string taskId, Instance instance)
if (paymentStatus != PaymentStatus.Paid)
throw new PaymentException("The payment is not completed.");

Stream pdfStream = await _pdfService.GeneratePdf(instance, taskId, CancellationToken.None);
Stream pdfStream = await _pdfService.GeneratePdf(instance, taskId, false, CancellationToken.None);

ValidAltinnPaymentConfiguration validatedPaymentConfiguration = paymentConfiguration.Validate();

Expand Down
51 changes: 0 additions & 51 deletions test/Altinn.App.Api.Tests/Controllers/PdfControllerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,57 +66,6 @@ public PdfControllerTests()
);
}

[Fact]
public async Task Request_In_Prod_Should_Be_Blocked()
{
var env = new Mock<IWebHostEnvironment>();
env.Setup(a => a.EnvironmentName).Returns("Production");

IOptions<GeneralSettings> generalSettingsOptions = Options.Create<GeneralSettings>(
new() { HostName = "org.apps.altinn.no" }
);

var httpContextAccessor = new Mock<IHttpContextAccessor>();
httpContextAccessor.Setup(x => x.HttpContext!.Request!.Query["lang"]).Returns(LanguageConst.Nb);

var handler = new Mock<HttpMessageHandler>();
var httpClient = new HttpClient(handler.Object);

var pdfGeneratorClient = new PdfGeneratorClient(
httpClient,
_pdfGeneratorSettingsOptions,
_platformSettingsOptions,
_userTokenProvider.Object,
httpContextAccessor.Object
);
var pdfService = new PdfService(
_appResources.Object,
_dataClient.Object,
httpContextAccessor.Object,
_profile.Object,
pdfGeneratorClient,
_pdfGeneratorSettingsOptions,
generalSettingsOptions,
_logger.Object
);
var pdfController = new PdfController(
_instanceClient.Object,
_pdfFormatter.Object,
_appResources.Object,
_appModel.Object,
_dataClient.Object,
env.Object,
pdfService
);

var result = await pdfController.GetPdfPreview(_org, _app, _partyId, _instanceId);

result.Should().BeOfType(typeof(NotFoundResult));
handler
.Protected()
.Verify("SendAsync", Times.Never(), ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>());
}

[Fact]
public async Task Request_In_Dev_Should_Generate()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,4 @@
"value": "Avvis"
}
]
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ public async Task End_PaymentCompleted_ShouldGeneratePdfReceipt()
await _paymentProcessTask.End(taskId, instance);

// Assert
_pdfServiceMock.Verify(x => x.GeneratePdf(instance, taskId, CancellationToken.None));
_pdfServiceMock.Verify(x => x.GeneratePdf(instance, taskId, false, CancellationToken.None));
_dataClientMock.Verify(x =>
x.InsertBinaryData(
instance.Id,
Expand Down Expand Up @@ -110,7 +110,7 @@ public async Task End_PaymentSkipped_ShouldNotGeneratePdfReceipt()
await _paymentProcessTask.End(taskId, instance);

// Assert
_pdfServiceMock.Verify(x => x.GeneratePdf(instance, taskId, CancellationToken.None), Times.Never);
_pdfServiceMock.Verify(x => x.GeneratePdf(instance, taskId, false, CancellationToken.None), Times.Never);
_dataClientMock.Verify(
x =>
x.InsertBinaryData(
Expand Down Expand Up @@ -142,7 +142,7 @@ public async Task End_PaymentNotCompleted_ShouldThrowException()
.ReturnsAsync(PaymentStatus.Created);

// Act and assert
_pdfServiceMock.Verify(x => x.GeneratePdf(instance, taskId, CancellationToken.None), Times.Never);
_pdfServiceMock.Verify(x => x.GeneratePdf(instance, taskId, false, CancellationToken.None), Times.Never);
_dataClientMock.Verify(
x =>
x.InsertBinaryData(
Expand Down Expand Up @@ -220,7 +220,9 @@ public async Task End_ValidConfiguration_ShouldNotThrow()

using var memoryStream = new MemoryStream();
_pdfServiceMock
.Setup(ps => ps.GeneratePdf(It.IsAny<Instance>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.Setup(ps =>
ps.GeneratePdf(It.IsAny<Instance>(), It.IsAny<string>(), false, It.IsAny<CancellationToken>())
)
.ReturnsAsync(memoryStream);

Func<Task> act = async () => await _paymentProcessTask.End("taskId", new Instance());
Expand Down
Loading