using Elwig.Models.Dtos; using Elwig.Models.Entities; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading.Tasks; namespace Elwig.Helpers.Export { public class Ebics(PaymentVar variant, string filename, int version) : IBankingExporter { public static string FileExtension => "xml"; private readonly StreamWriter Writer = new(filename, false, Utils.UTF8); private readonly DateOnly Date = variant.TransferDate ?? throw new ArgumentException("TransferDate has to be set in PaymentVar"); private readonly int Year = variant.Year; private readonly string Name = variant.Name; private readonly int AvNr = variant.AvNr; private readonly int Version = version; public void Dispose() { GC.SuppressFinalize(this); Writer.Dispose(); } public ValueTask DisposeAsync() { GC.SuppressFinalize(this); return Writer.DisposeAsync(); } public void Export(IEnumerable transactions, IProgress? progress = null) { ExportAsync(transactions, progress).GetAwaiter().GetResult(); } public async Task ExportAsync(IEnumerable transactions, IProgress? progress = null) { if (transactions.Any(tx => tx.Amount < 0)) throw new ArgumentException("Tranaction amount may not be negative"); progress?.Report(0.0); var nbOfTxs = transactions.Count(); int count = nbOfTxs + 2, i = 0; var ctrlSum = transactions.Sum(tx => tx.Amount); var msgId = $"ELWIG-{App.Client.NameToken}-{Year}-AV{AvNr:00}"; var pmtInfId = $"{msgId}-1"; await Writer.WriteLineAsync($""" {msgId} {DateTime.UtcNow:o} {nbOfTxs} {Transaction.FormatAmount(ctrlSum)} {App.Client.NameFull} {pmtInfId} TRF {nbOfTxs} {Transaction.FormatAmount(ctrlSum)} {(Version >= 8 ? "
" : "")}{Date:yyyy-MM-dd}{(Version >= 8 ? "
" : "")}
{App.Client.NameFull} {App.Client.Iban!.Replace(" ", "")} {(Version >= 4 ? "" : "")}{App.Client.Bic ?? "NOTPROVIDED"}{(Version >= 4 ? "" : "")} """); progress?.Report(100.0 * ++i / count); foreach (var tx in transactions) { var a = (IAddress?)tx.Member.BillingAddress ?? tx.Member; var (a1, a2) = Utils.SplitAddress(a.Address); var id = $"ELWIG-{App.Client.NameToken}-{Year}-TG{tx.Nr:0000}"; var info = $"{Name} - Traubengutschrift Nr. {Year}/{tx.Nr:000}"; await Writer.WriteLineAsync($""" {id} {Transaction.FormatAmount(tx.Amount)} {a.Name[..Math.Min(140, a.Name.Length)]} {a1?[..Math.Min(70, a1.Length)]}{a2?[..Math.Min(16, a2.Length)]} {a.PostalDest.AtPlz?.Plz}{a.PostalDest.AtPlz?.Ort.Name} {a.PostalDest.Country.Alpha2} {tx.Member.Iban!} {info} """); progress?.Report(100.0 * ++i / count); } await Writer.WriteLineAsync("""
"""); await Writer.FlushAsync(); progress?.Report(100.0); } } }