foxygit / digitalskrivare_merge Log in
commits tags

/src/Remiss.Core/RemissWorkflow.cs · 2.67 KB

raw
using Remiss.Core.Abstractions;
using Remiss.Core.Audit;
using Remiss.Core.Models;
using Remiss.Core.Pdf;
using Remiss.Core.Printing;
using Remiss.Core.Security;

namespace Remiss.Core;

/// <summary>
/// Steg [3]–[6] i arkitekturen: generera försättsblad, merge, tyst utskrift,
/// audit. Städning av temp-filer ägs av anroparen via <see cref="SecureTempStore"/>.
/// </summary>
public sealed class RemissWorkflow
{
    private readonly AppConfig _config;
    private readonly IPrinter _printer;
    private readonly AuditLogger _audit;

    public RemissWorkflow(AppConfig config, IPrinter printer, AuditLogger audit)
    {
        _config = config;
        _printer = printer;
        _audit = audit;
    }

    public void Run(string sourcePdfPath, Mottagning mottagning, SecureTempStore temp)
    {
        var coverPath = temp.NewFile("cover.pdf");
        var mergedPath = temp.NewFile("merged.pdf");

        var stage = "init";
        try
        {
            stage = "cover";
            CoverPageGenerator.Generate(coverPath, new CoverInfo(mottagning.Namn, mottagning.HsaId, DateTime.Now));

            stage = "merge";
            PdfMerger.Merge(mergedPath, coverPath, sourcePdfPath);

            stage = "debug-copy";
            DumpForDebug(mergedPath);

            stage = "print";
            var printerName = string.IsNullOrWhiteSpace(_config.TargetPrinter)
                ? DefaultPrinter.TryGetName() ?? "(systemets standardskrivare)"
                : _config.TargetPrinter;
            _printer.Print(mergedPath, _config.TargetPrinter);

            stage = "source-cleanup";
            if (_config.DeleteSourceAfterPrint)
                SecureFile.Shred(sourcePdfPath);

            _audit.Write("remiss.sent", mottagning.Namn, mottagning.HsaId,
                success: true, stage: "done", detail: $"printer={printerName}");
        }
        catch (Exception ex)
        {
            _audit.Write("remiss.failed", mottagning.Namn, mottagning.HsaId,
                success: false, stage: stage, detail: ex.GetType().Name);
            _audit.Error($"workflow/{stage}", ex);
            throw;
        }
    }

    // ENDAST TEST: kopiera ut mergad PDF (patientdata, städas inte) om debugOutputDir är satt.
    private void DumpForDebug(string mergedPath)
    {
        if (string.IsNullOrWhiteSpace(_config.DebugOutputDir))
            return;

        Directory.CreateDirectory(_config.DebugOutputDir);
        var target = Path.Combine(_config.DebugOutputDir, $"remiss-debug-{DateTime.Now:yyyyMMdd-HHmmss}.pdf");
        File.Copy(mergedPath, target, overwrite: true);
        _audit.Write("remiss.debugcopy", null, null, success: true, stage: "debug-copy", detail: "test-only");
    }
}