ZUGFeRD 2.2/ Factur-X 1.0 for Dynamics 365 FO

ZUGFeRD 2.2/ Factur-X 1.0 for Dynamics 365 FO

We are excited to announce the release of the common German-French electronic invoice ZUGFeRD / Factur-X in Dynamics 365 for Finance and SCM. This plug-and-play solution in its “Light” version does not require any customisation and can be easily installed in the standard Electronic Reporting module of D365. It supports the ZUGFeRD 2.2/Factur-X 1.0 profile EN 16931, also known as the “COMFORT” profile, which meets all tax law requirements and must be accepted by customers unless explicitly denied.

In the ZUGFeRD/Factur-X standard, the invoicing information is included in an XML payload attached to a human-readable PDF file (see https://de.wikipedia.org/wiki/ZUGFeRD). This is in contrast to the Italian electronic invoicing system, where a PDF is embedded in a Base64 encoded block within an XML. The PDF document is just a visualisation of the electronic content, what counts is the XML attachment. The XML file is always named factur-x.xml and it is attached to at the PDF document level, not to a single PDF page:

Here is an example: factur-x.xml

Our solution, which utilizes Configurable business documents in D365, supports Sales invoices with separate buyer, seller, and order accounts. Other types of invoices such as the Free text invoice or any of the 3 Project invoices, can be provided upon request at a discounted price. Our solution also handles form notes, line and header notes and footers, line discounts, total discounts, and cash discounts, document level charges, properly reflecting VAT for domestic, EU, and export sales. The settlement instructions orchestrate a SEPA credit transfer or a SEPA direct debit withdrawal; partially prepaid invoices are properly interpreted. The solution is available in French, German, and American English.

Price

The solution is offered at a fixed fee per end customer / D365 tenant:
VersionPriceDeliverablesNotes
Light€890A ZUGFeRD Sales invoice ER configuration, the XML file onlyThis option does not require any X++ customisations or 3rd party software and can be installed and used right away.
Light+€1200Same as the Light version but with 5 hours of prepaid support and installation 
Heavy€2200Contains the full solution, including a PDF template, and a PDF post-processor with 8 hours of prepaid support.Includes the iTextSharp 5.5.13.2 .NET library under the GNU Affero General Public License
Includes the BouncyCastle 1.8.9 .NET cryptographic library under a variant of the MIT license.

You may acquire the solution on the official Microsoft App Source portal: https://appsource.microsoft.com/en-us/product/dynamics-365-for-operations/er-consultgmbh1674479095356.zugferd_light_plus

Setup and use

 

 

Basic setup: “Light” and “Heavy”

  1.  Import the Electronic configuration “ZUGFeRD Sales invoice” provided to you (Organisation administration > Electronic reporting > Configurations, button Exchange / Load from XML file). For the ease of installation, configuration and integration, the standard Invoice model Invoice model v 277 and the standard Invoice model mapping 277.258 are used, make sure they have been imported upfront.
  2. Beware: the standard Invoice model mapping from Microsoft has a number of shortcomings. For instance, the buyer and seller addresses are passed in a de-normalized form as multi line strings. As a walkaround, some heuristics and regular expressions have been applied to extract the ISO2 code of the country and the zip (postal) code. A well-known modification to the standard Invoice model mapping will fix that and reinforce the report. Futhermore, the current Microsoft Invoice model mapping does not pass the EU Tax directives to the report. At the moment, the report relies on the non-EU Tax exempt codes in the same way as the standard Excel invoice does. To leverage the Tax directives, fix the model mapping, then modify the ZipFolder/InvoicePDF/SalesTax/SalesTax* mappings in ZUGFeRD Sales invoice format like this:
    IF(OR(@.Value.TaxExemptDescription<>"",@.Value.TaxDirective<>""),
    IF(@.Value.TaxExemptDescription<>"",@.Value.TaxExemptDescription,@.Value.TaxDirective),
    @"GER_LABEL:PlusVAT")
  3. Under the button Configurations / Application specific parameters / Setup, provide a mapping of the VAT (en-us: Sales tax) Print codes to the ZUGFeRD categories S, K, AE, G, O (for example, the 19% and 7% VAT belong to the “S” category). Also provide a mapping of the D365 Unit of measure codes to the UNECE Recommendation No. 20 list called “Codes for Units of Measure Used in International Trade” (see Codes for Units of Measure used in International Trade: Recommendation N°.20 – Revision 7 | UNECE). For instance, a piece has the standard code H87. An “each” ea  may be translated to C62. A sample parameter setup can be downloaded here: 03-01-2023 03.29.45 pm_ZUGFeRD Sales invoice.277.11
  4. Pay attention to the sample VAT print codes on the screenshot above: the standard Invoice model mapping does not pass the tax rates to the report, and the VAT Print code must contain the VAT rate in numbers, if applicable. In other words, they should look like “19%” and “7%” in Germany or “20%” and “5,5%” in France. Beware: these symbolic “print codes” persist in the tax transactions and invoice lines along with the VAT codes, i.e. they are historized and must be set correctly from the beginning.
  5. The mapping of the sales units of measure is against the language-specific, translated unit code (if exists), not the UoM symbol used in D365 globally, i.e. not pcs but Stk. This Stk. then becomes H87 in the output file. The configuration translates the local units of measure to one of the H87, KGM, MTR, LTR, TNE, CMT, HUR, DAY, GRM, MIN, MON, WEE, MMT, SEC, C26, YRD, APZ, FOT, GLL, INH, ONZ, LBT. The Years class is used as a fallback: no translation is applied; for example, a ea mapped to Years remans ea in the output file.
  6. Once both the mappings have been established, set the Application specific parameters State to Completed.
  7. Open Sales ledger (en-us: Accounts receivable) > Setup > Forms > Form setup. Make sure that the VAT specification option is set to Registration currency. You will also probably Print VAT number on invoice, show some invoice line inventory dimensions and/or notes, and display external item numbers (Item number in forms = Both).
  8. Finally, open Print management and select the Report format = ZUGFeRD Sales invoice at the Customer invoice node. The Light version setup ends here.

Supplementary setup: “Heavy”

  1. For the Heavy version, first deploy the X++ customisations and libraries from a D365 deployable package provided to you.
  2. Create a new File document type in the Organisation administration > Document management > Document types list. Name it exactly like this: ZUGFeRD.
  3. Create a new ER destination (Organisation administration > Electronic reporting > Electronic reporting destination) for the report ZUGFeRD Sales invoice. Under File destination, add a new line and choose the ZipFolder file component.
  4. Click Settings. To show the invoice on the Screen, divert the file to the Archive: set Enabled and Save in job archive, and choose file Type = ZUGFeRD. For this screen destination, make sure that the feature Configure action-dependent ER destinations (https://learn.microsoft.com/en-us/dynamics365/fin-ops-core/dev-itpro/analytics/er-action-dependent-destinations) is not used: the selection Document type in the ER destination must be set to Any.
  5. To send the invoice per Email, add a new file destination line, click Settings, open the tab ZUGFeRD, and flip the Email slider. In the Email ID parameter, you may also select an Organisation administration > Setup > Organisation email template with an appropriate subject and a HTML body in your corporate design. Placeholders%ExchangedDocument% (invoice ID), %DuePayableAmount% (invoice amount) and %BuyerTradeParty% (customer ID) are supported out of the box i.e., the email subject and body of the email are dynamic. The selection Document type in this ER destination must remain Any or Electronic. ZUGFeRD ER destinations: Email
  6. The steps to configure the Heavy version end here. The Electronic Reporting engine will fill out the PDF form, populate an XML file and put both into a folder (i.e. a ZIP). This ZIP file is intercepted, unpacked, and the XML part is embedded into the PDF, adding some references and mandatory attributes. The PDF file is not fully PDF-A/3 compliant, but it can be read and parsed, the XML payload passes the validations (see the links below).
  7. Print the sales invoice with the option Use print management turned on. The resulting PDF document is rendered on the screen (the Light version offers an XML file to download) in a separate browser window or sent per e-mail to the email contact of the customer with the role Invoice. In the batch invoicing mode (de: “Autofaktura”), the Screen destination is obsolete.
  8. You may also re-print invoices out of the Invoice journal form (Sales ledger > Enquiries and reports > Invoices > …) with the button View. Be aware of the hardcoded safeguards against re-sending the invoice per email if already sent, and against mailing proforma invoices to the end customer:  “The file may not be sent: Pro forma invoice or Invoice copy“.
  9.  Here is a sample, you buy what you see:

Useful links

Extensibility

To implement a custom invoice design with a corporate logo, a certain colour palette or fonts, extend the ER configuration “ZUGFeRD Sales invoice” as any other ER configurable business document. Derive an own configuration, then extract, amend and replace the PDF template attached to the ER configuration version. Please bear in mind that PDF forms do not contain dynamic, repeatable ranges or cells. This is the reason why the number of invoice lines in the template is currently limited by 10; this number will be extended on demand. Refer to Design ER configurations to fill in PDF templates – Finance & Operations | Dynamics 365 | Microsoft Learn for more details.
 

The “output actions” are extendable: new output actions may be offered upon request at a discounted price. You may even implement your own /Class/ERFileOutputActionXXX_ZUGFeRD, for example:

				
					/// <summary>
/// Send the resulting PDF to a browser window interactively
/// </summary>
[ERFileOutputAttribute_ZUGFeRD(SRSPrintMediumType::Screen)]
class ERFileOutputActionScreen_ZUGFeRD extends ERFileOutputAction_ZUGFeRD
{
    /// <summary>
    /// The screen destination does not need to extract any contact info
    /// </summary>
    /// <returns>An empty visitor class</returns>
    public ERFileOutputActionXmlVisitor_ZUGFeRD makeVisitor()
    {
        return new ERFileOutputActionXmlVisitor_ZUGFeRD();
    }

    /// <summary>
    /// Display  the PDF file formed by ERFileDestinationPostProcessor_ZUGFeRD on the screen 
    /// </summary>
    /// <param name = "_outputPDF">Stream with a PDF file, with a CII XML attached</param>
    /// <returns>Success or failure to display</returns>
    public boolean sendFile(System.IO.MemoryStream _outputPDF)
    {
        Browser br = new Browser();
        
        str downloadUrl = File::SendFileToTempStore(_outputPDF,
                                                    ERConstants_ZUGFeRD::ZUGFeRD_Filename,
                                                    classstr(FileUploadTemporaryStorageStrategy),
                                                    true);
        if (downloadUrl != '')
        {
            br.navigate(downloadUrl, true, false);
        }
        else
        {
            return checkFailed("@ApplicationPlatform:DownloadFailed");
        }
        return true;
    }

}
				
			

Enumerate lines in Configurable Business Documents

Enumerate lines in Configurable Business Documents

The delivery note, invoice etc. Report Data Providers in Dynamics 365 for Finance do not expose line numbers for no obvious reason. For instance, the SalesInvoiceTmp  table sent from D365 to the report renderer – whatever it is – misses the line number. The situation becomes dire when it comes to Electronic Reporting / Configurable Business Documents.

The ENUMERATE(Lines) function applied to the lines makes a totally new object {Number, Value} and every binding “@” becomes “@.Value“. This is a massive change in the report, very hard to maintain and upgrade (rebase).

In XML or CSV outbound formats there is a Counter element, it auto-counts itself. In Excel and Word outbound formats there are just RangesCells. I thought we worked with lists as isolated objects and there were no internal variables in Electronic Reporting which were aware of the execution history.

But today I finally understood what the DATA COLLECTION does. It is a listener, you pass a value to it, it returns it back unchanged but keeps a global variable to count and summarise the values.

For example, to enumerate delivery note (en-us: packing slip) lines, first create a root Data collection class of the integer type in the Mapping to the right, Collect all values = Yes, let’s call it a LineNumberCollection.

Then put the following formula into the Excel Cell with the line number:
LineNumberCollection.Collect(1)+LineNumberCollection.Sum(false)-1 

The first LineNumberCollection.Collect() call takes 1, records 1 internally, and returns the 1 back into the cell. The second call LineNumberCollection.Sum(false) adds the running total of 1’es recorded so far. The last operand subtracts 1.

Here is the result: Bingo!

D365 Electronic Reporting: JOIN records in pairs

Test for odd number
Test for odd number

D365 Electronic Reporting: JOIN records in pairs

Recently, I came across a really challenging requirement in Electronic Reporting / Configurable Business Documents in Dynamics: in an additional section in the Delivery note, print a flat table where every pair of consecutive records becomes one line:

No Not like this But like this No
1 Left lace Left lace – Right lace 1
2 Right lace Left shoe – Right shoe 2
3 Left shoe
4 Right shoe

This required a set of sophisticated techniques I am thrilled to share. The idea is to split into odd and even records and build something like

SELECT *, ROW_NUMBER as Rn1 FROM Records JOIN *, ROW_NUMBER as Rn2 from Records ON Rn2= Rn1+1

  1. Enumerate: make a so called Calculated field at the ER configuration’s root level with a record list and a row Number inside:
    ENUMERATE(ALLITEMS(MyRecords))
  2. Add another Calculated field at the row level to check if the current record has an odd or an even row number: LEN(REPLACE("13579",RIGHT(NUMBERFORMAT(@.Number,"#"),1),"",false))<5 I’ll leave the formula uncommented, but I wonder if somebody manages to write a shorter function. I can also imagine using TRANSLATE() or the VALUEIN(SPLIT(“1,3,5,7,9″…) functions. The problem is the missing MOD operator in Electronic Reporting: https://experience.dynamics.com/ideas/idea/?ideaid=09590ad4-70a4-e711-80c0-00155d7cd0b4. They promised, but failed to deliver. Anyway, now we’ve got this:
  3. Next, let’s add another root Calculated field, filter the list by $Odd = true and make a list with only the odd records:
    WHERE('$AllRecordsEnumerated', '$AllRecordsEnumerated'.'$Odd')
  4. Finally, attach an ‘even’ record to every ‘odd’ one by placing another Calculated field with a lookup inside of the $OddRecord: FIRSTORNULL(WHERE('$AllRecordsEnumerated', '$AllRecordsEnumerated'.Number=@.Number+1)). Here is the result, a JOIN to itself:

Bingo!