Estimate validation polish + PDF/TeX generation in Yavsc.Api

- List removal: GetOngoingEstimatesAsProvider filters on
  ProviderValidationDate so a provider's signed estimate leaves their
  list; PostIt refreshes the list on navigation pop-back.
- Title renames: "Devis en attente de signature fournisseur/client"
  on both the provider and client sides (HomePage, VM, tests).
- Move the estimate/bill TeX+PDF generation flow from Yavsc.Org into
  Yavsc.Api (TeXHelpers, PdfGenerationViewModel, BillViewComponent,
  Bill/Estimate templates, _ViewImports). Program.cs wires
  AddControllersWithViews + SiteSettings; FrontOfficeApiController
  injects IRazorViewEngine (cast to IViewEngine) with optional deps
  and exposes estimate.tex/estimate.pdf endpoints keyed by query id.
- PDF generation drives through the Estimate_pdf view (side-effect
  render) and compiles via the system lualatex, fed TeX on stdin (no
  intermediate .tex), PDF to the bills dir, aux artifacts cleaned so
  only the .pdf persists. Resolve the bills dir to an absolute path so
  lualatex's -output-directory and working directory agree regardless
  of the host cwd (fixes "I can't write on file estimate-1.log").
- PostIt: DownloadAsync on the client + GetEstimateTex/PdfAsync;
  Télécharger PDF/TeX buttons on the validation and command-detail
  pages via a StorageProvider save helper.

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
Paul Schneider 2026-09-22 03:22:01 +01:00
commit 97d0584292
Signed by: notazof
GPG key ID: AD4B9B545FBD7D12
41 changed files with 1036 additions and 290 deletions

View file

@ -335,9 +335,9 @@ namespace Yavsc.ApiControllers
return new ChallengeResult();
}
var filename = AbstractFileSystemHelpers.SignFileNameFormat("pro", billingCode, id);
var filename = AbstractFileSystemHelpers.SignFileNameFormat("cli", billingCode, id);
FileInfo fi = new FileInfo(Path.Combine(siteSettings.Bills, filename));
if (!fi.Exists) return NotFound(new { Error = "Professional signature not found" });
if (!fi.Exists) return NotFound(new { Error = "Client signature not found" });
return File(fi.OpenRead(), "application/x-pdf", filename);
}

View file

@ -216,14 +216,16 @@ namespace Yavsc.Controllers
}
// GET: api/estimate/asprovider
// Ongoing estimates (not yet validated by the client) established
// by the current user as the provider.
// Estimates awaiting the provider's signature, established by the
// current user as the provider. Once the provider validates
// (ProviderValidationDate stamped), the estimate leaves this list
// and appears in the client's "awaiting client signature" list.
[HttpGet("asprovider")]
public IActionResult GetOngoingEstimatesAsProvider()
{
var uid = User.GetUserId();
return Ok(_context.Estimates.Include(e => e.Bill).Include(e => e.Signatures)
.Where(e => e.OwnerId == uid && e.ClientValidationDate == default));
.Where(e => e.OwnerId == uid && e.ProviderValidationDate == default));
}
protected override void Dispose(bool disposing)

View file

@ -1,6 +1,9 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Yavsc.Abstract.Workflow;
using Yavsc.Helpers;
using Yavsc.Models;
@ -8,6 +11,7 @@ using Yavsc.Models.Billing;
using Yavsc.Services;
using Yavsc.Server.Helpers;
using Yavsc.ViewModels.FrontOffice;
using Yavsc.ViewModels.Gen;
namespace Yavsc.ApiControllers
{
@ -18,15 +22,36 @@ namespace Yavsc.ApiControllers
ApplicationDbContext dbContext;
private readonly IBillingService billing;
private readonly ILogger logger;
private readonly SiteSettings siteSettings;
private readonly IViewEngine viewEngine;
// The view-rendering dependencies (siteSettings, viewEngine) are
// optional: only EstimateTex/EstimatePdf use them, and those run in
// the Api host where Program.cs wires AddControllersWithViews +
// SiteSettings. The accept/reject endpoints (and the Api integration
// test host, which composes with AddControllers alone) never touch
// them, so they must not be required for controller activation.
//
// .NET 10 does not register a single IViewEngine service (the view
// engine is registered as IRazorViewEngine and surfaced through
// MvcViewOptions.ViewEngines). IRazorViewEngine (RazorViewEngine)
// implements IViewEngine, so we inject that and hand it to
// TeXHelpers.RenderViewToString as an IViewEngine. RenderViewToString
// builds its ActionContext from the controller's own ControllerContext,
// so no IActionContextAccessor is needed (and that type is deprecated
// in .NET 10).
public FrontOfficeApiController(
ApplicationDbContext context,
ILoggerFactory loggerFactory,
IOptions<SiteSettings> siteSettings = null,
IRazorViewEngine viewEngine = null,
IBillingService billing = null)
{
dbContext = context;
this.billing = billing ?? new BillingService(context);
logger = loggerFactory.CreateLogger<FrontOfficeApiController>();
this.siteSettings = siteSettings?.Value;
this.viewEngine = viewEngine as IViewEngine;
}
[HttpGet("profiles/{actCode}")]
@ -35,6 +60,120 @@ namespace Yavsc.ApiControllers
return await dbContext.ListPerformersAsync(billing, actCode);
}
// GET: api/front/query/{queryId}/estimate.tex
//
// Renders the estimate linked to the query (Estimate.CommandId ==
// queryId) as a LaTeX source document. The view is a generation
// template (Layout = "null"), not a web page: it is returned with
// a text/x-tex content type so the caller can save it as a .tex
// file. Either party (client or provider) or an admin may read it.
[HttpGet("query/{queryId}/estimate.tex")]
public async Task<IActionResult> EstimateTex(long queryId, CancellationToken token)
{
if (viewEngine is null || siteSettings is null)
return Problem("TeX rendering is not configured on this host.",
statusCode: StatusCodes.Status503ServiceUnavailable);
var estimate = await LoadEstimateForRenderAsync(queryId, token);
if (estimate is null) return NotFound(new { Error = "no estimate linked to this query" });
var uid = User.GetUserId();
if (!User.IsInRole(Constants.AdminGroupName)
&& uid != estimate.ClientId && uid != estimate.OwnerId)
return Forbid();
PrepareEstimateViewBag(estimate);
Response.ContentType = "text/x-tex";
return View("Estimate_tex", estimate);
}
// GET: api/front/query/{queryId}/estimate.pdf
//
// Renders the same LaTeX template to a string, compiles it to PDF
// via texi2pdf (see SiteSettings.GenerateEstimatePdf), and streams
// the generated PDF bytes back. Requires /usr/bin/texi2pdf on the
// server host; on hosts without it the endpoint returns a problem.
[HttpGet("query/{queryId}/estimate.pdf")]
public async Task<IActionResult> EstimatePdf(long queryId, CancellationToken token)
{
if (viewEngine is null || siteSettings is null)
return Problem("PDF rendering is not configured on this host.",
statusCode: StatusCodes.Status503ServiceUnavailable);
var estimate = await LoadEstimateForRenderAsync(queryId, token);
if (estimate is null) return NotFound(new { Error = "no estimate linked to this query" });
var uid = User.GetUserId();
if (!User.IsInRole(Constants.AdminGroupName)
&& uid != estimate.ClientId && uid != estimate.OwnerId)
return Forbid();
PrepareEstimateViewBag(estimate);
var baseFileName = $"estimate-{estimate.Id}";
// Resolve the bills dir to an absolute path once: appsettings
// configures it as a relative path ("bills"), and both the
// generation (GenerateEstimatePdf) and the read-back below must
// agree on the same location regardless of the host's cwd.
var billsDir = new System.IO.DirectoryInfo(siteSettings.Bills).FullName;
var model = new PdfGenerationViewModel
{
BaseFileName = baseFileName,
DestDir = billsDir,
Temp = siteSettings.TempDir,
};
try
{
// 1. Render the LaTeX template (Estimate_tex) to a TeX source
// string, using the estimate as the view model.
model.TeXSource = this.RenderViewToString(viewEngine, "Estimate_tex", estimate);
// 2. Render the generation view (Estimate_pdf). Its @{} block
// calls SiteSettings.GenerateEstimatePdf(Model), which
// compiles the TeX to PDF on disk as a side effect of the
// render. The HTML the view emits is not what we return —
// we stream the generated PDF bytes — but driving the
// generation through the view keeps the template as the
// output producer, per the original design.
this.RenderViewToString(viewEngine, "Estimate_pdf", model);
}
catch (Exception ex)
{
logger.LogError(ex, "estimate {QueryId}: TeX/PDF render failed", queryId);
return Problem("TeX render failed: " + ex.Message);
}
if (!model.Generated)
return Problem("PDF generation failed: "
+ (model.GenerationErrorMessage?.Value ?? "unknown error"));
var pdfPath = System.IO.Path.Combine(billsDir, baseFileName + ".pdf");
var bytes = await System.IO.File.ReadAllBytesAsync(pdfPath, token);
return File(bytes, "application/pdf", baseFileName + ".pdf");
}
// Loads the estimate linked to a query with the navigation the
// Estimate_tex template reads (client + performer profile + bill).
private Task<Estimate?> LoadEstimateForRenderAsync(long queryId, CancellationToken token)
=> dbContext.Estimates
.Where(e => e.CommandId == queryId)
.OrderByDescending(e => e.Id)
.Include(e => e.Bill)
.Include(e => e.Query).ThenInclude(q => q!.Client).ThenInclude(c => c!.PostalAddress)
.Include(e => e.Query).ThenInclude(q => q!.PerformerProfile).ThenInclude(p => p!.OrganizationAddress)
.Include(e => e.Query).ThenInclude(q => q!.PerformerProfile).ThenInclude(p => p!.Performer)
.FirstOrDefaultAsync(token);
// Sets the ViewBag keys the Estimate_tex template reads. A devis
// is never a bill (AsBill=false) and is never acquitted.
private void PrepareEstimateViewBag(Estimate estimate)
{
ViewBag.AsBill = false;
ViewBag.Acquitted = false;
ViewBag.BillsDir = new System.IO.DirectoryInfo(siteSettings.Bills).FullName;
ViewBag.AvatarsDir = new System.IO.DirectoryInfo(siteSettings.Avatars).FullName;
}
// POST: api/front/query/accept
//
// Either party of the query may accept: the provider
@ -57,6 +196,15 @@ namespace Yavsc.ApiControllers
if (query is null) return BadRequest(new { Error = "query not found" });
Signature? signature = null;
// actingRole is the role the caller is signing / accepting
// as. It defaults to the role inferred from the caller's
// identity, but when a signature is submitted the caller
// declares the side (Pro/Client) and the server honors it
// only if the caller is that party. This disambiguates a
// user who is both parties (where inference would always
// pick the provider) and makes "write only for its author"
// explicit.
ActorRole actingRole = role;
if (HasSignature(body))
{
// Admins bypass authorization but are neither party of
@ -71,20 +219,37 @@ namespace Yavsc.ApiControllers
if (estimate is null)
return BadRequest(new { Error = "no estimate linked to this query" });
var type = role == ActorRole.Provider
var uid = User.GetUserId();
bool isProvider = query.PerformerId == uid;
bool isClient = query.ClientId == uid;
// The caller declares which side they sign as. Null
// falls back to the role inferred from identity.
var declared = body!.SignatureType;
if (declared.HasValue)
{
if (declared.Value == SignatureType.Pro && !isProvider)
return Forbid();
if (declared.Value == SignatureType.Client && !isClient)
return Forbid();
actingRole = declared.Value == SignatureType.Pro
? ActorRole.Provider
: ActorRole.Client;
}
var type = actingRole == ActorRole.Provider
? SignatureType.Pro
: SignatureType.Client;
var payload = new SignaturePadPayload
{
CoordinateMax = body!.CoordinateMax,
CoordinateMax = body.CoordinateMax,
CapturedAtUtc = body.CapturedAtUtc ?? DateTime.UtcNow,
Strokes = body.Strokes!,
};
try
{
var uid = User.GetUserId();
signature = await EstimateSignaturePersister.StageAsync(
dbContext, estimate.Id, type, uid, payload, token);
}
@ -94,7 +259,7 @@ namespace Yavsc.ApiControllers
return BadRequest(new { Error = "signature stage failed", Detail = ex.Message });
}
if (role == ActorRole.Provider)
if (actingRole == ActorRole.Provider)
estimate.ProviderValidationDate = DateTime.UtcNow;
else
estimate.ClientValidationDate = DateTime.UtcNow;
@ -104,7 +269,7 @@ namespace Yavsc.ApiControllers
// provider (ProAccepted) or the client (ClientAccepted).
// An admin accepting (neither party) falls back to the
// legacy generic Accepted.
query.Status = role switch
query.Status = actingRole switch
{
ActorRole.Provider => QueryStatus.ProAccepted,
ActorRole.Client => QueryStatus.ClientAccepted,
@ -222,5 +387,19 @@ namespace Yavsc.ViewModels.FrontOffice
public int CoordinateMax { get; set; } = 10_000;
public DateTime? CapturedAtUtc { get; set; }
/// <summary>
/// Which signature is being submitted:
/// <see cref="SignatureType.Pro"/> (the provider) or
/// <see cref="SignatureType.Client"/>. When <see cref="Strokes"/>
/// is present this declares the side the caller is signing as;
/// the server honors it only if the caller is that party
/// (<c>query.PerformerId</c> for Pro, <c>query.ClientId</c>
/// for Client). This disambiguates the case where one user is
/// both parties, and makes "write only for its author"
/// explicit. When null, the server falls back to the role
/// inferred from the caller's identity.
/// </summary>
public SignatureType? SignatureType { get; set; }
}
}

View file

@ -0,0 +1,226 @@
using System.Diagnostics;
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
namespace Yavsc.Helpers
{
using ViewModels.Gen;
public class TeXString : HtmlString
{
public TeXString(TeXString teXString): base(teXString.ToString())
{
}
public TeXString(string str) : base(str)
{
}
public static TeXString operator+ (TeXString a, TeXString b) {
return new TeXString(a.ToString()+b.ToString());
}
}
public class Replacement
{
string target;
string replacement;
public Replacement(string target, string replacement)
{
this.target = target;
this.replacement = replacement;
}
public string Execute(string source)
{
return source?.Replace(target, replacement) ?? null;
}
}
public static class TeXHelpers
{
public static readonly Replacement[] SpecialCharsDefaultRendering =
{
new Replacement("<","\\textless"),
new Replacement(">","\\textgreater"),
new Replacement("©","\\copyright"),
new Replacement("®","\\textregistered"),
new Replacement("\\","\\textbackslash"),
new Replacement("™","\\texttrademark"),
new Replacement("¶","\\P"),
new Replacement("|","\\textbar"),
new Replacement("%","\\%"),
new Replacement("{","\\{"),
new Replacement("}","\\}"),
new Replacement("_","\\_"),
new Replacement("#","\\#"),
new Replacement("$","\\$"),
new Replacement("_","\\_"),
new Replacement("¿","\\textquestiondown"),
new Replacement("§","\\S"),
new Replacement("£","\\pounds"),
new Replacement("&","\\&"),
new Replacement("¡","\\textexclamdown"),
new Replacement("†","\\dag"),
new Replacement("–","\\textendash"),
new Replacement("°","\\textdegree")
};
public static TeXString ToTeX(this string source, string defaultValue="\\textit{néant}")
{
if (source==null) return new TeXString(defaultValue);
string result=source;
foreach (var r in SpecialCharsDefaultRendering)
{
result = r.Execute(result);
}
return new TeXString(result);
}
public static TeXString ToTeXCell(this string source, string defaultValue="\\textit{néant}")
{
if (source==null) return new TeXString(defaultValue);
string result=source;
foreach (var r in SpecialCharsDefaultRendering)
{
result = r.Execute(result);
}
result = result.Replace("\n","\\tabularnewline ");
return new TeXString(result);
}
public static string NewLinesWith(this string target, string separator)
{
var items = target.Split(new char[] { '\n' }).Where(
s => !string.IsNullOrWhiteSpace(s));
return string.Join(separator, items);
}
public static TeXString ToTeXLines(this string source, string defaultValue, string lineSeparator = "\n\\\\")
{
if (source == null) return new TeXString(defaultValue);
return new TeXString( source.ToTeX().ToString().NewLinesWith(lineSeparator) );
}
public static TeXString SplitAddressToTeX (this string source, string lineSeparator = "\n\\\\", string defaultValue = "\\textit{pas d'adresse postale}")
{
if (string.IsNullOrWhiteSpace(source)) return new TeXString(defaultValue);
var alines = source.Split(',');
var texlines = alines.Select(l=>l.ToTeX().ToString());
return new TeXString(string.Join(lineSeparator,texlines));
}
public static bool GenerateEstimatePdf(this SiteSettings settings, PdfGenerationViewModel Model)
{
string errorMsg = null;
// Resolve to an absolute path: SiteSettings.Bills may be a
// relative path (e.g. "bills"), and lualatex resolves
// -output-directory against its working directory — passing a
// relative path to both would nest them (<cwd>/bills/bills) and
// the log/pdf write would fail.
var billdir = new DirectoryInfo(Model.DestDir).FullName;
string name = Model.BaseFileName;
FileInfo fo = new FileInfo(System.IO.Path.Combine(billdir, name + ".pdf"));
System.IO.Directory.CreateDirectory(billdir);
// Compile the LaTeX source with the system lualatex, feeding it
// the TeX on standard input (no intermediate .tex file) and
// directing the resulting <name>.pdf straight into the bills
// directory. lualatex is a file-based engine — it cannot emit
// the PDF on stdout — so the pdf lands at its final destination
// and we only clean the transient aux/log artifacts beside it.
int exitCode;
try
{
using (Process p = new Process())
{
p.StartInfo = new ProcessStartInfo
{
UseShellExecute = false,
WorkingDirectory = billdir,
FileName = "lualatex",
Arguments = $"-interaction=nonstopmode -halt-on-error"
+ $" -jobname=\"{name}\" -output-directory=\"{billdir}\"",
RedirectStandardInput = true,
};
p.Start();
using (var stdin = p.StandardInput)
{
stdin.Write(Model.TeXSource);
}
p.WaitForExit();
exitCode = p.ExitCode;
}
}
catch (Exception ex)
{
errorMsg = "lualatex invocation failed: " + ex.Message;
exitCode = -1;
}
if (exitCode != 0 && errorMsg == null)
errorMsg = $"Pdf generation failed with exit code: {exitCode}";
else if (!fo.Exists && errorMsg == null)
errorMsg = "Pdf generation produced no output";
// Remove the LaTeX build artifacts left beside the pdf so only
// <name>.pdf persists in the bills directory.
foreach (var ext in new[] { ".aux", ".log", ".out", ".fls",
".fdb_latexmk", ".synctex.gz", ".toc" })
{
var f = new FileInfo(System.IO.Path.Combine(billdir, name + ext));
if (f.Exists) { try { f.Delete(); } catch { } }
}
Model.Generated = fo.Exists;
Model.GenerationErrorMessage = new HtmlString(errorMsg);
return fo.Exists;
}
public static string RenderViewToString(
this Controller controller, IViewEngine engine,
string viewName, object model, bool isMainPage = true)
{
if (engine == null)
throw new InvalidOperationException("no engine");
// Build an ActionContext from the controller's own context —
// .NET 10 deprecated IActionContextAccessor, and the controller
// already holds the live request context on its ControllerContext.
var controllerContext = controller.ControllerContext;
var actionContext = new ActionContext(
controllerContext.HttpContext,
controllerContext.RouteData,
controllerContext.ActionDescriptor);
ViewEngineResult viewResult = engine.FindView(actionContext, viewName, isMainPage);
if (!viewResult.Success)
throw new InvalidOperationException(
$"View '{viewName}' not found. Searched locations: "
+ string.Join(", ", viewResult.SearchedLocations));
// Hand the model to the view through ViewData so the template's
// @model directive resolves it (the previous implementation never
// set ViewData.Model, leaving Model null inside the template).
controller.ViewData.Model = model;
using (var sw = new StringWriter())
{
var viewContext = new ViewContext(
actionContext,
viewResult.View,
controller.ViewData,
controller.TempData,
sw,
new HtmlHelperOptions());
viewResult.View.RenderAsync(viewContext).GetAwaiter().GetResult();
return sw.GetStringBuilder().ToString();
}
}
}
}

View file

@ -55,7 +55,11 @@ internal class Program
});
})
.AddYavscCors(builder.Configuration)
.AddControllers();
.AddControllersWithViews();
// Binds the "Site" section (Bills, TempDir, Avatars, …) used by
// the document-generation flow and BillingController.
services.Configure<SiteSettings>(builder.Configuration.GetSection("Site"));
// accepts any access token issued by identity server
services.AddAuthentication("Bearer")

View file

@ -0,0 +1,108 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Localization;
using Yavsc.Billing;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.ViewModels;
using Yavsc.ViewModels.Gen;
using Yavsc.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
namespace Yavsc.ViewComponents
{
public class BillViewComponent : ViewComponent
{
readonly ApplicationDbContext dbContext;
readonly IBillingService billing;
readonly IStringLocalizer<BillViewComponent> localizer;
private readonly SiteSettings siteSettings;
public BillViewComponent(ApplicationDbContext dbContext,
IStringLocalizer<BillViewComponent> localizer,
IBillingService billing,
IOptions<SiteSettings> siteSettings)
{
this.billing = billing;
this.dbContext = dbContext;
this.localizer = localizer;
this.siteSettings = siteSettings.Value;
}
public async Task<IViewComponentResult> InvokeAsync(
string code,
IBillable billable,
OutputFormat format,
bool asBill,
SiteSettings settings
)
{
var di = new DirectoryInfo(settings.Bills);
var dia = new DirectoryInfo(settings.Avatars);
ViewBag.BillsDir = di.FullName;
ViewBag.AvatarsDir = dia.FullName;
ViewBag.AsBill = asBill; // vrai pour une facture, sinon, c'est un devis
ViewBag.Acquitted = billable.GetIsAcquitted();
ViewBag.BillingCode = code;
var client = await dbContext.Users
.Include(u=>u.PostalAddress)
.SingleAsync(u=>u.Id == billable.ClientId);
ViewBag.Client = client;
var performer = await dbContext.Users
.Include(u=>u.BankInfo)
.Include(u=>u.PostalAddress)
.SingleAsync(u=>u.Id == billable.PerformerId);
ViewBag.Performer = performer;
string clientAddress = client.PostalAddress?.Address ?? null;
ViewBag.ClientAddress = clientAddress.SplitAddressToTeX();
var profile = await dbContext.Performers
.Include(p=>p.OrganizationAddress)
.SingleAsync(p=>p.PerformerId == billable.PerformerId);
ViewBag.PerformerProfile = profile;
ViewBag.ActivityLabel = (await dbContext.Activities.SingleAsync(a => a.Code == billable.ActivityCode)).Name;
var proAddr = profile.OrganizationAddress.Address;
ViewBag.PerformerOrganizationAddress = proAddr.SplitAddressToTeX() ;
ViewBag.FooterPerformerOrganizationAddress = proAddr.SplitAddressToTeX(", ");
ViewBag.PerformerAddress = performer.PostalAddress?.Address.SplitAddressToTeX() ;
switch (format) {
case OutputFormat.LaTeX :
return this.View("Bill_tex", billable);
case OutputFormat.Pdf :
string tex = null;
var oldWriter = ViewComponentContext.ViewContext.Writer;
using (var writer = new StringWriter())
{
this.ViewComponentContext.ViewContext.Writer = writer;
var resultTex = View("Bill_tex", billable);
await resultTex.ExecuteAsync(this.ViewComponentContext);
tex = writer.ToString();
}
ViewComponentContext.ViewContext.Writer = oldWriter;
var pdfGenerationViewModel = new PdfGenerationViewModel
{
Temp = siteSettings.TempDir,
TeXSource = tex,
DestDir = siteSettings.Bills,
BaseFileName = billable.GetFileBaseName(billing)
};
if (settings.GenerateEstimatePdf(pdfGenerationViewModel)) {
return this.View(new { Generated = pdfGenerationViewModel.BaseFileName+".pdf" });
} else {
return View(new { Error = pdfGenerationViewModel.GenerationErrorMessage } );
}
}
ViewBag.BillFileInfo = billable.GetBillInfo(billing, siteSettings);
ViewBag.Settings = settings;
return View("Default",billable);
}
}
}

View file

@ -0,0 +1,19 @@
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Html;
namespace Yavsc.ViewModels.Gen
{
public class PdfGenerationViewModel
{
[Required]
public string TeXSource { get; set; }
[Required]
public string BaseFileName { get; set; }
[Required]
public string DestDir { get; set; }
public bool Generated { get; set; }
public HtmlString GenerationErrorMessage { get; set; }
public string Temp { get; set; }
}
}

View file

@ -0,0 +1,21 @@
@using System.Reflection
@using System.IO
@using Microsoft.Extensions.WebEncoders
@using System.Diagnostics
@using System.Text
@using Yavsc.Helpers
@model Yavsc.ViewModels.Gen.PdfGenerationViewModel
@{
ViewBag.Settings.GenerateEstimatePdf(Model);
}
@if (Model.Generated) {
<div>
@(Model.BaseFileName).pdf was generated
</div>
} else {
<div class="error">
@Model.GenerationErrorMessage
<p>Something went wrong ...</p>
</div>
}

View file

@ -0,0 +1,228 @@
@using Yavsc.Helpers
@using System.IO
@using System.Globalization
@model IBillable
@{
Layout = null;
var pro = ViewBag.PerformerProfile;
var from = ViewBag.Performer;
var to = ViewBag.Client;
var PostalAddress = ViewBag.ClientAddress;
var proaddr = ViewBag.PerformerOrganizationAddress;
var isestimate = !ViewBag.AsBill;
var prosign = new FileInfo($"{ViewBag.BillsDir}/sign-{ViewBag.BillingCode}-{Model.Id}.png");
var clisign = new FileInfo($"{ViewBag.BillsDir}/sign-{ViewBag.BillingCode}-{Model.Id}.png");
var activity = ViewBag.ActivityLabel;
var bill = Model.GetBillItems();
string validationDate = null ;
if (Model.ValidationDate.HasValue) {
validationDate = Model.ValidationDate.Value.ToString("dddd dd MMMM yyyy", CultureInfo.CreateSpecificCulture("fr-FR"));
}
}
\documentclass[french,11pt]{article}
\usepackage{eurosym}
\usepackage{textcomp}
\usepackage{babel}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[a4paper]{geometry}
\usepackage{units}
\usepackage{graphicx}
\usepackage{fancyhdr}
\usepackage{fp}
\usepackage[space]{grffile}
\def\TVA{20} % Taux de la TVA
\def\TotalHT{0}
\def\TotalTVA{0}
\newcommand{\AjouterService}[3]{% Arguments : Désignation, quantité, prix
\FPround{\prix}{#3}{2}
\FPeval{\montant}{#2 * #3}
\FPround{\montant}{\montant}{2}
\FPadd{\TotalHT}{\TotalHT}{\montant}
\eaddto\ListeProduits{#1 & \prix & #2 & \montant \cr}
}
\newcommand{\AfficheResultat}{%
\ListeProduits
\FPeval{\TotalTVA}{\TotalHT * \TVA / 100}
\FPadd{\TotalTTC}{\TotalHT}{\TotalTVA}
\FPround{\TotalHT}{\TotalHT}{2}
\FPround{\TotalTVA}{\TotalTVA}{2}
\FPround{\TotalTTC}{\TotalTTC}{2}
\global\let\TotalHT\TotalHT
\global\let\TotalTVA\TotalTVA
\global\let\TotalTTC\TotalTTC
\cr
\hline
\textbf{Total} & & & \TotalHT
}
\newcommand*\eaddto[2]{% version développée de \addto
\edef\tmp{#2}%
\expandafter\addto
\expandafter#1%
\expandafter{\tmp}%
}
\newcommand{\ListeProduits}{}
%%%%%%%%%%%%%%%%%%%%% A MODIFIER DANS LA FACTURE %%%%%%%%%%%%%%%%%%%%%
\def\FactureNum {@Model.Id.ToString()} % Numéro de facture
\def\FactureAcquittee {@(ViewBag.Acquitted?"oui":"non")} % Facture acquittée : oui/non
\def\FactureLieu {@proaddr} % Lieu de l'édition de la facture
\def\FactureObjet {@(new HtmlString(isestimate?"Devis":"Facture")) en @TeXHelpers.ToTeX(activity)} % Objet du document
% Description de la facture
\def\FactureDescr {
@TeXHelpers.ToTeX(Model.Description)
}
% Infos Client
\def\ClientNom{@TeXHelpers.ToTeX(to.UserName)} % Nom du client
\def\ClientAdresse{
% Adresse du client
@PostalAddress @if (!string.IsNullOrWhiteSpace(to.PhoneNumber)) {<text>\\
@TeXHelpers.ToTeX(to.PhoneNumber)
</text>}\\
E-mail: @TeXHelpers.ToTeX(to.Email)
}
% Liste des produits facturés : Désignation, prix
@foreach (var line in bill) {
<text>\AjouterService{@TeXHelpers.ToTeXCell(line.Description)}{@line.Count}{@line.UnitaryCost.ToString("F2",CultureInfo.InvariantCulture)}
</text>}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\geometry{verbose,tmargin=4em,bmargin=8em,lmargin=6em,rmargin=6em}
\setlength{\parindent}{0pt}
\setlength{\parskip}{1ex plus 0.5ex minus 0.2ex}
\thispagestyle{fancy}
\pagestyle{fancy}
\setlength{\parindent}{0pt}
\renewcommand{\headrulewidth}{0pt}
\cfoot{ @TeXHelpers.ToTeX(from.UserName) - @ViewBag.FooterPerformerOrganizationAddress \\
\small{ E-mail: @TeXHelpers.ToTeX(from.Email) @if (!string.IsNullOrWhiteSpace(from.PhoneNumber)) { <text> - Téléphone : @TeXHelpers.ToTeX(from.PhoneNumber) </text> }
}
}
\begin{document}
% Logo de la société
@if (from.Avatar != null) {
<text>\includegraphics[height=60pt]{@(ViewBag.AvatarsDir)/@(from.UserName).png}
</text>
} else {
<text>%\includegraphics{logo.png}
</text>
}
% Nom et adresse de la société
@TeXHelpers.ToTeX(from.UserName) \\
@proaddr
@(isestimate?"Devis":"Facture") n\textdegree\FactureNum
{\addtolength{\leftskip}{10.5cm} %in ERT
\textbf{\ClientNom} \\
\ClientAdresse \\
} %in ERT
\hspace*{10.5cm}
\FactureLieu, le \today
~\\~\\
\textbf{Objet : \FactureObjet \\}
\textnormal{\FactureDescr}
~\\
\begin{center}
\begin{tabular}{lrrr}
\textbf{Désignation ~~~~~~} & \textbf{Prix unitaire} & \textbf{Quantité} & \textbf{Montant (\euro)} \\
\hline
\AfficheResultat{}
\end{tabular}
\end{center}
\begin{flushright}
\textit{Auto entreprise en franchise de TVA}\\
\end{flushright}
~\\
@if (ViewBag.AsBill) {
if (ViewBag.Acquitted) {
<text>
\ifthenelse{\equal{\FactureAcquittee}{oui}}{
Facture acquittée.
}
</text>
} else {
var bi = from.BankInfo;
if (bi==null){
<text>À régler sur site, en utilisant le paiment PayPal:\\
Le relevé d'identité bancaire de ce prestaire n'est pas renseigné.
</text>
} else {
<text>À régler par chèque ou par virement bancaire :
\begin{center}
\begin{tabular}{|c c c c|}
@if (!string.IsNullOrWhiteSpace(bi.BankCode) && !string.IsNullOrWhiteSpace(bi.WicketCode)
&& !string.IsNullOrWhiteSpace(bi.AccountNumber) ) {
<text>\hline \textbf{Code banque} & \textbf{Code guichet} & \textbf{N\textdegree de Compte} & \textbf{Clé RIB} \\
@bi.BankCode & @bi.WicketCode & @bi.AccountNumber & @bi.BankedKey \\
</text>
}
@if (!string.IsNullOrWhiteSpace(@bi.IBAN) && !string.IsNullOrWhiteSpace(@bi.BIC)) {
<text>
\hline \textbf{IBAN N\textdegree} & \multicolumn{3}{|l|}{ @bi.IBAN } \\
\hline \textbf{Code BIC} & \multicolumn{3}{|l|}{ @bi.BIC }
</text>
} \\
\hline
\end{tabular}
\end{center}</text>
}
}
}
@if (validationDate!=null) {
<text>
\begin{flushright}
@(new TeXString(isestimate?"Devis demandé le ":"Facture suite à la demande du ")+
TeXHelpers.ToTeX(validationDate))
\end{flushright}
@if (prosign.Exists) {
<text>
\begin{center}
\hspace{263pt}
\includegraphics[height=60pt]{@(ViewBag.BillsDir)/{ViewBag.BillingCode}-prosign-@(Model.Id).png}
\end{center}
</text>
}
@if (clisign.Exists) {
<text>
\begin{center}
\hspace{263pt}
\includegraphics[height=60pt]{@(ViewBag.BillsDir)/{ViewBag.BillingCode}-clisign-@(Model.Id).png}
\end{center}
</text>
}
</text>
}
\end{document}

View file

@ -0,0 +1,33 @@
@model IBillable
<div class="bill">
@if (ViewBag.BillFileInfo.Exists) {
<a class="btn btn-link" href="~/api/bill/facture-@(ViewBag.BillingCode)-@(Model.Id).pdf" >La facture au format Pdf</a>
} else {
<script>
var onGenerate = function () {
var _btn = "this";
$.post('/api/bill/genpdf/@ViewBag.BillingCode/@Model.Id')
.done(function(data){
var res = JSON.parse(data);
window.location.href = '/api/bill/' + res.Generated;
_btn.disabled = "true";
})
.fail(function( jqXHR, textStatus, errorThrown ) {
$('#billgenerr').html('<em>La génération a échoué</em><p>'+textStatus+'</p>')
})
};
$(document).ready(function(){$('#btnGen').on('click',onGenerate)})
</script>
<div id="billgen">
<form action= method="POST">
<input id="btnGen" class="btn btn-primary" type="button" onclick="onGenerate" value="Générer la facture au format Pdf" />
<div id="billgenerr" class="error">
</div>
</form>
</div>
}
</div>

View file

@ -0,0 +1,21 @@
@using System.Reflection
@using System.IO
@using Microsoft.Extensions.WebEncoders
@using System.Diagnostics
@using System.Text
@using Yavsc.Helpers
@model Yavsc.ViewModels.Gen.PdfGenerationViewModel
@{
SiteSettings.Value.GenerateEstimatePdf(Model);
}
@if (Model.Generated) {
<div>
@(Model.BaseFileName).pdf was generated
</div>
} else {
<div class="error">
@Model.GenerationErrorMessage
<p>Something went wrong ...</p>
</div>
}

View file

@ -0,0 +1,206 @@
@using Yavsc.Helpers
@using System.IO
@using System.Globalization
@model Estimate
@{
Layout = null;
var pro = Model.Query.PerformerProfile;
var from = Model.Query.PerformerProfile.Performer;
var to = Model.Query.Client;
var PostalAddress = to.PostalAddress?.Address.SplitAddressToTeX();
var proaddr = Model.Query.PerformerProfile.OrganizationAddress.Address.SplitAddressToTeX();
var proaddrm = new HtmlString(Model.Query.PerformerProfile.OrganizationAddress.Address);
var isestimate = !ViewBag.AsBill;
var prosign = new FileInfo($"{ViewBag.BillsDir}/estimate-prosign-{Model.Id}.png");
}
\documentclass[french,11pt]{article}
\usepackage{eurosym}
\usepackage{babel}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[a4paper]{geometry}
\usepackage{units}
\usepackage{bera}
\usepackage{graphicx}
\usepackage{fancyhdr}
\usepackage{fp}
\def\TVA{20} % Taux de la TVA
\def\TotalHT{0}
\def\TotalTVA{0}
\newcommand{\AjouterService}[3]{% Arguments : Désignation, quantité, prix
\FPround{\prix}{#3}{2}
\FPeval{\montant}{#2 * #3}
\FPround{\montant}{\montant}{2}
\FPadd{\TotalHT}{\TotalHT}{\montant}
\eaddto\ListeProduits{#1 & \prix & #2 & \montant \cr}
}
\newcommand{\AfficheResultat}{%
\ListeProduits
\FPeval{\TotalTVA}{\TotalHT * \TVA / 100}
\FPadd{\TotalTTC}{\TotalHT}{\TotalTVA}
\FPround{\TotalHT}{\TotalHT}{2}
\FPround{\TotalTVA}{\TotalTVA}{2}
\FPround{\TotalTTC}{\TotalTTC}{2}
\global\let\TotalHT\TotalHT
\global\let\TotalTVA\TotalTVA
\global\let\TotalTTC\TotalTTC
\cr
\hline
\textbf{Total} & & & \TotalHT
}
\newcommand*\eaddto[2]{% version développée de \addto
\edef\tmp{#2}%
\expandafter\addto
\expandafter#1%
\expandafter{\tmp}%
}
\newcommand{\ListeProduits}{}
%%%%%%%%%%%%%%%%%%%%% A MODIFIER DANS LA FACTURE %%%%%%%%%%%%%%%%%%%%%
\def\FactureNum {@Model.Id.ToString()} % Numéro de facture
\def\FactureAcquittee {@ViewBag.Acquitted?"oui":"non"} % Facture acquittée : oui/non
\def\FactureLieu {@proaddrm} % Lieu de l'édition de la facture
\def\FactureObjet {@(new HtmlString(isestimate?"Devis":"Facture")) : @TeXHelpers.ToTeX(Model.Title)} % Objet du document
% Description de la facture
\def\FactureDescr {
@TeXHelpers.ToTeX(Model.Description)
}
% Infos Client
\def\ClientNom{@TeXHelpers.ToTeX(to.UserName)} % Nom du client
\def\ClientAdresse{
% Adresse du client
@PostalAddress
@if (PostalAddress!=null) {<text>@PostalAddress</text>}
@if (!string.IsNullOrWhiteSpace(to.PhoneNumber)) {<text>@TeXHelpers.ToTeX(to.PhoneNumber)<text>\\</text>
</text>}
E-mail: @TeXHelpers.ToTeX(to.Email)
}
% Liste des produits facturés : Désignation, prix
@if (Model.Bill!=null) { foreach (CommandLine line in Model.Bill) {
<text>\AjouterService{@TeXHelpers.ToTeX(line.Description)}{@line.Count}{@line.UnitaryCost.ToString("F2",CultureInfo.InvariantCulture)}
</text>} }
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\geometry{verbose,tmargin=4em,bmargin=8em,lmargin=6em,rmargin=6em}
\setlength{\parindent}{0pt}
\setlength{\parskip}{1ex plus 0.5ex minus 0.2ex}
\thispagestyle{fancy}
\pagestyle{fancy}
\setlength{\parindent}{0pt}
\renewcommand{\headrulewidth}{0pt}
\cfoot{ @TeXHelpers.ToTeX(from.UserName) @if (proaddrm!=null) { <text> - @proaddrm </text> } \newline
\small{ E-mail: @TeXHelpers.ToTeX(from.Email) @if (!string.IsNullOrWhiteSpace(from.PhoneNumber)) { <text> - Téléphone fixe: @TeXHelpers.ToTeX(from.PhoneNumber) </text> }
}
}
\begin{document}
% Logo de la société
@if (from.Avatar != null) {
<text>\includegraphics[height=60pt]{@(ViewBag.AvatarsDir)/@(from.UserName).png}
</text>
} else {
<text>%\includegraphics{logo.png}
</text>
}
% Nom et adresse de la société
@TeXHelpers.ToTeX(from.UserName) \\
@proaddr
@(isestimate?"Devis":"Facture") n°\FactureNum
{\addtolength{\leftskip}{10.5cm} %in ERT
\textbf{\ClientNom} \\
\ClientAdresse \\
} %in ERT
\hspace*{10.5cm}
\FactureLieu, le \today
~\\~\\
\textbf{Objet : \FactureObjet \\}
\textnormal{\FactureDescr}
~\\
\begin{center}
\begin{tabular}{lrrr}
\textbf{Désignation ~~~~~~} & \textbf{Prix unitaire} & \textbf{Quantité} & \textbf{Montant (\euro)} \\
\hline
\AfficheResultat{}
\end{tabular}
\end{center}
\begin{flushright}
\textit{Auto entreprise en franchise de TVA}\\
\end{flushright}
~\\
@if (!isestimate) {
<text>
\ifthenelse{\equal{\FactureAcquittee}{oui}}{
Facture acquittée.
}{ </text>
if (from.BankInfo!=null) foreach (var bi in from.BankInfo){
<text>À régler par chèque ou par virement bancaire :
\begin{center}
\begin{tabular}{|c c c c|}
@if (!string.IsNullOrWhiteSpace(bi.BankCode) && !string.IsNullOrWhiteSpace(bi.WicketCode)
&& !string.IsNullOrWhiteSpace(bi.AccountNumber) ) {
<text>\hline \textbf{Code banque} & \textbf{Code guichet} & \textbf{N° de Compte} & \textbf{Clé RIB} \\
@bi.BankCode & @bi.WicketCode & @bi.AccountNumber & @bi.BankedKey \\
</text>
}
@if (!string.IsNullOrWhiteSpace(@bi.IBAN) && !string.IsNullOrWhiteSpace(@bi.BIC)) {
<text>
\hline \textbf{IBAN N°} & \multicolumn{3}{|l|}{ @bi.IBAN } \\
\hline \textbf{Code BIC} & \multicolumn{3}{|l|}{ @bi.BIC }
</text>
} \\
\hline
\end{tabular}
\end{center}</text>
}
}
@if (!(Model.ProviderValidationDate==null)) {
<text>
\begin{flushright}
@(new HtmlString(isestimate?"Devis validé":"Facture validée")) le @TeXHelpers.ToTeX(Model.ProviderValidationDate.ToString("dddd dd MMMM yyyy"))
\end{flushright}
@if (prosign.Exists) {
<text>
\begin{center}
\hspace{263pt}
\includegraphics[height=60pt]{@(ViewBag.BillsDir)/estimate-prosign-@(Model.Id).png}
\end{center}
</text>
}
</text>
}
\end{document}

View file

@ -0,0 +1,12 @@
@using Yavsc
@using Yavsc.Helpers
@using Yavsc.Billing
@using Yavsc.Models
@using Yavsc.Models.Billing
@using Yavsc.ViewModels.Gen
@using Microsoft.AspNetCore.Mvc
@using Microsoft.AspNetCore.Html
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@inject Microsoft.Extensions.Options.IOptions<SiteSettings> SiteSettings