11.14 设置和使用电子文档
E-documents overview
应用场景:这个应用(Microsoft Dynamics 365 Business Central 中的 E-Document 应用)的核心场景是帮助企业在数字化环境中高效管理电子文档(如发票、收据等),确保符合当地法规,并简化与交易伙伴的文档交互流程。以下是具体例子:
1. 跨国贸易中的电子发票合规(以德国企业为例)
一家德国制造企业向法国客户销售设备,需要开具符合德国当地法规的电子发票。根据德国本地化要求,电子发票需支持 Peppol BIS 3、XRechnung(UBL 格式) 等标准。
企业通过 E-Document 应用,在系统中自动生成符合上述格式的销售电子发票,无需手动调整格式。应用通过 “外部端点连接器” 功能,直接将电子发票发送至法国客户的电子文档接收系统(如客户使用的 Peppol 网络接入点),避免邮件传输的繁琐和合规风险。系统实时跟踪发票状态(已发送、已接收、已确认),并在 “文档状态消息” 中同步客户的确认信息,减少沟通成本。
2. 澳大利亚与新西兰的跨境交易(基于 Peppol 标准)
一家澳大利亚零售商从新西兰供应商采购商品,双方需通过 Peppol PINT A-NZ 格式交换电子发票和订单。
新西兰供应商通过 E-Document 应用生成符合 Peppol PINT A-NZ 标准的电子采购发票,发送至澳大利亚零售商的 Dynamics 365 系统。零售商的系统通过 “电子数据交换框架” 自动解析发票数据,匹配采购订单信息(可借助 Copilot 预览功能快速映射发票与订单行项目),无需人工录入。应用根据澳大利亚本地化规则,自动存档电子发票(符合当地 retention policies 留存政策),便于税务审计。
3. 法国企业的未来合规准备(2026 年法国电子发票强制要求)
法国计划在 2026 年强制要求企业使用合规电子发票。一家法国批发企业提前部署 E-Document 应用:
先通过应用的 “销售电子文档” 功能,在系统中测试电子发票的生成、发送流程(如模拟向本地客户发送符合未来法国标准的发票)。配置 “外部端点参数”,提前对接法国税务部门指定的电子文档接收平台,确保 2026 年法规生效后可直接启用,避免业务中断。
4. 中小企业借助第三方本地化扩展(非微软支持地区)
一家西班牙的小型物流公司需要向西班牙政府提交符合 Factura-E 格式 的电子发票,但自身技术能力有限。
企业通过 E-Document 应用的基础功能搭建电子文档管理框架,再从 AppSource 下载西班牙本地化扩展(非微软官方支持的第三方应用),快速适配 Factura-E 格式要求。系统自动将物流服务的订单数据转换为合规电子发票,通过连接器发送至客户和税务部门,降低手动处理的错误率。
这些例子均围绕 “电子文档的合规生成、高效传输、状态跟踪” 展开,体现了该应用在不同国家 / 地区、不同规模企业中的核心价值 —— 通过标准化工具简化复杂的电子文档管理流程,同时满足本地化法规要求。
Electronic documents (e-documents) are the backbone of modern business transactions. They encompass vital documents, such as invoices and receipts in both directions (delivery and receipt). They also add capabilities for document status–related messaging between access points.
Our commitment to enhancing your business processes led to the development of a groundbreaking app that focuses on e-documents in Microsoft Dynamics 365 Business Central. This app serves as a robust platform for efficient e-document management.
Note
To use these capabilities, install the E-Document Core app in your environment.
The E-Document app can be used in countries/regions where companies require specialized e-document handling to comply with local regulations. The app provides a solid foundation that can be easily extended to meet specific local or industry requirements.
The documentation explains e-documents in detail. It shows the capabilities of the app and demonstrates how it seamlessly adapts to cater to your organization's unique needs. To get started with e-documents, see the following articles.
Article |
Description |
Set up e-documents |
Learn how to set up e-documents functionality, including services, workflow, sending profiles, and retention policies. |
Use e-documents in sales |
Learn how to use e-documents functionality for sales invoices, their statuses, logs, and action messages. |
Use e-documents in purchase |
Learn how to use e-documents functionality for purchase invoices and orders, their statuses, logs, and action messages. |
Extending e-documents functionality |
Learn how to extend e-documents functionality with specific local or industry requirements by creating more apps on top of this one. |
Set the e-documents connector with external endpoints |
Learn how to use external access points for automation in delivering and receiving your e-documents. |
Parameters for setting the e-documents connector with external endpoints |
Learn how to set up parameters and credentials for e-documents with specific external endpoints. |
Exchanging Data Electronically |
Learn how to use the Data Exchange Framework to manage the exchange of data in business documents such as bank files and currency exchange rates. |
Map e-documents to purchase order lines with Copilot (preview) |
Learn how to use Copilot to improve your efficiency when working with e-documents. |
FAQ |
Frequent Questions and Answers about E-Documents. |
Localizations
Microsoft currently supports the following localizations:
Article |
Description |
Australian E-Invoicing |
Peppol PINT A-NZ format. |
Danish E-Invoicing |
Supported both Peppol BIS 3 and OIOUBL formats. |
French E-Invoicing |
To be supported in 2026. |
German E-Invoicing |
Supported Peppol BIS 3, XRechnung (UBL only), and ZUGFeRD formats. |
Indian E-Invoicing |
Using new E-Documents framework – TBD |
Italian E-Invoicing |
Using new E-Documents framework – TBD |
Mexican E-Invoicing |
Using new E-Documents framework – TBD |
New Zealand E-Invoicing |
Peppol PINT A-NZ format. |
Norway E-Invoicing |
Supported Peppol BIS 3 format. |
Spanish E-Invoicing |
Supported Factura-E format. |
Note
For non-Microsoft localizations, visit the AppSource.
Set up E-documents
Important
The E-Documents core module is a framework. By default, there's no Service Integration field. If you find the Document Format options by default, remember that they're offered as examples. Localization apps must provide format detail because they're specific to local requirements.
Note
A standard PEPPOL document format is a global format in the Document Format field. Keep in mind that you probably can't use this format as is. It's a W1 format that Microsoft provides to show how to use this feature. We recommend that you test the existing PEPPOL format before you start to use this format.
The first step to configure electronic documents (e-documents) is to set up the E-Documents Service for e-document communication.
Set up an e-document service
To set up an e-document service, follow these steps.
Select the
icon, enter E-Document Services, and then select the related link.Select New, and then, on the E-Document Service page, on the General FastTab, configure the fields as described in the following table.
Field |
Description |
Code |
Select the electronic export setup code. |
Description |
Enter a brief description of the electronic export setup. |
Document Format |
The export format of the electronic export setup. By default, there are two options in this field. You can select PEPPOL BIS 3 as a generic code-based format or Data Exchange when you must set up predocuments of specific formats on the Data Exchange Definition FastTab. |
Service Integration |
Select the integration code for the electronic export setup. Currently, the only option is No integration. |
On the Importing FastTab, configure the fields as described in the following table.
Field |
Description |
Automatic Import |
Specify whether documents should be automatically imported from the service. |
Automatic processing |
Specify whether Business Central uses your e-document setup to automatically create a purchase document based on the received e-document. If you choose No, Business Central creates the e-document, but you must review its details before you create the purchase document. |
Validate Receiving Company |
Specify whether the receiving company information must be validated during import. |
Resolve Unit Of Measure |
Specify whether to resolve the unit of measure during import. |
Lookup Item Reference |
Specify whether to search for items by item reference during import. |
Lookup Item GTIN |
Specify whether to search for items by Global Trade Item Number (GTIN) during import. |
Lookup Account Mapping |
Specify whether to search for accounts in Account Mapping by the incoming text during import. |
Validate Line Discount |
Specify whether to validate a line discount during import. |
Apply Invoice Discount |
Specify whether to apply an invoice discount during import. |
Verify Totals |
Specify whether to verify invoice totals during import. |
Create Journal Lines |
Specify whether a journal line must be created instead of a purchase document. Select this option when you want to use journals as a destination for your invoices. |
General Journal Template Name |
Specify the name of the general journal template that's used for journal line creation. This field is applicable when you want to use journals as a destination for your invoices. |
General Journal Batch Name |
Specify the name of the general journal batch that's used for journal line creation. This field is applicable when you want to use journals as a destination for your invoices. |
Batch Start Time |
Specify the start time for import jobs. |
Minutes between runs |
Specify the number of minutes between import job runs. |
If you selected Data Exchange in the Document Format field on the General FastTab, on the Data Exchange Definition FastTab, fill in the fields as described in the following table.
Field |
Description |
Document Type |
Specify the document type that uses data exchange to import and export the data. Examples include Sales Invoice, Sales Credit memo, and Purchase Invoice. |
Import Data Exchange Def. Code |
Specify the data exchange code that's used to import the data. Use this field only to receive a document in the purchase process. |
Export Data Exchange Def. Code |
Specify the data exchange code that's used to export the data. Use this field only to deliver documents in the sales process. |
Note
There are data exchange definitions for the PEPPOL format that are related to sales and purchase documents. However, you likely can't use these definitions as is. They're all W1 formats that are provided to show how to use this feature. We recommend that you test the existing PEPPOL format before you start to use them. It's possible that using a specific localization reveals more formats, as some can be country/region-specific.
If you configured the Data Exchange Definition format in your localization, you can add a line for the document types that you need. Add lines that match the default data exchange example for the W1 PEPPOL format. However, first select the Document Type option for each line that you need. For each data type, select the Import Data Exchange Def. Code or Export Data Exchange Def. Code value that you want to use.
If you don't use the Data Exchange Definition format, you can create and configure formats by using the interface. Adjust the information on the Export Mapping and Import Mapping lines, where you can find the tables and fields to configure transformation rules. In this case, you must add a new option for your format in the Document Format field.
On the Exporting FastTab, fill in the fields as described in the following table:
Field |
Description |
Batch Exporting |
Specify whether the service uses batch processing to export e-documents. |
Embed document PDF to export |
Specify whether to embed a PDF version of the e-document in the e-document file when you export. |
NoteThe Embed document PDF to export option can make life a little easier. When you post a document, Business Central creates a PDF file and embeds it as a PDF attachment in the e-document. The PDF is a human-readable version that's easier to understand than the full XML of the PEPPOL format.
Supported document types
Support for document types is based on the Document Format. To check which document types are supported, on the E-Document Services page, choose the Supported Document Types action. The E-Document Service Supported Source Document Types opens. In the Source Document Type column, you can choose different document types for the format you're planning to use. Only use the document type if that document is selected.
Set up a document sending profile
You need to set up a preferred method of sending sales documents for each customer. On the Document Sending Profiles page, you can set up sending profiles and then select the one to use in the Document Sending Profile field on a customer card. You can select the Default checkbox to specify that a document sending profile is the profile for all customers for which a profile isn't specified in the Document Sending Profile field.
This feature is used to set up electronic invoicing automation. If you're using legacy e-invoices before enabling the E-Document framework, the process is slightly different. When you choose Post and Send on a sales document, the Post and Send Confirmation dialog shows the sending profile in use. The profile is either the profile set up for the customer or the default profile for all customers.
However, to enable the new E-Document framework, you need to configure the Document Sending Profile accordingly. To set up a document sending profile, follow these steps.
Select the
icon, enter Document Sending Profile, and then select the related link.On the Document Sending Profiles page, select New.On the General FastTab, fill in the required fields.On the Sending Options FastTab, set the Printer, Email, and Disk fields to No. Enabling any of these options prevent you from using the E-Document framework, limiting you to the legacy e-invoicing functionality instead.On the same FastTab fill in the fields as described in the following table.
Field |
Description |
Set up options |
Electronic Document |
Specify whether the document is sent as an e-document that the customer can import into their system. This option must be set to the Extended E-Document Service Flow to use E-Document framework. To use this option, you must also set the Format or Electronic Document Service Flow Code field. Alternatively, you can save the file to your computer. |
Must choose Extended E-Document Service Flow. |
Format |
Specify the format to use to send an e-document. This field is required if you select Through Document Exchange in the Electronic Document field. |
Don't use this setup for E-Document framework because it's part of legacy e-invoicing. |
Electronic Document Service Flow Code |
Specify the electronic service flow that's used to send documents. This field is required if you select Extended E-Document Service Flow in the Electronic Document field. |
You must set up it if you selected the Extended E-Document Service Flow option. |
NoteIf you select Extended E-Document Service Flow in the Electronic Document field, you must already have the workflow configured for your e-documents. ImportantThe legacy e-invoicing system is still in use, which allows users to configure the Electronic Document field as Through Document Exchange Service. In this setup, the Printer, Email, and Disk fields are applicable and typically enabled. However, this configuration isn't supported in any of Microsoft’s e-invoicing localizations and is planned for deprecation.To use the new E-Document framework, you must configure the Electronic Document field as Extended E-Document Service Flow and specify a value in the Electronic Document Service Flow Code field.
Set up the workflow
To set up a workflow for e-documents, follow these steps.
Select the
icon, enter Workflow Templates, and then select the related link.If you can't find E-Document Workflow Templates on the Workflow Templates page, select Reset Microsoft Templates. E-Document Workflow Templates should then appear. Close the page.Select the
icon, enter Workflows, and then select the related link.Choose the New Workflow from Template action to select a template for the e-documents process. The available templates are Send to one service and Send to multiple services.Select OK to finish the workflow setup.In the Then Response field, select Send E-Document using setup to configure the workflow responses.Select the E-Document Service that you created as an option, choose OK, and then enable the workflow.
Note
You can create your own workflow for e-documents without using predefined workflow templates. If you have more services, you can use different workflows.
To use more workflows, configure them through the document sending profiles for different customers. When you set up the workflow, specify the document sending profile in the On Condition column on the Workflow Steps FastTab, because you can't have two services that use the same document sending profile in workflows.
When you configure your workflow on the Workflows page, point to the On Condition field on the Workflow Steps FastTab. On the Event Conditions page, in the Filter field, select the document sending profile that you want to use.
Set up a retention policy for e-documents
E-documents can be subject to local legislation that specifies the period for which you must keep e-documents. To manage that, administrators can define retention policies that control how often Business Central deletes records. To learn more about retention policies, go to Define Retention Policies.
To set up retention policies for e-documents, follow these steps.
On the E-Document Services page, choose the Retention Policy action.When the action is completed, select one of the following retention policies to set up:
E-Document LogE-Document Integration LogE-Document Mapping LogE-Document Data Storage
E-Documents demo data
Note
From Business Central version 24.0, you can set up demo data for E-Documents.
To provide easier ways to test and demonstrate e-documents, Microsoft offers a demo module. To enable the module, follow these steps:
Select the
icon, enter Contoso Demo Tool, and then select the related link.Before you enable the E-Document Contoso Module, you must first enable the Common Module and Warehouse Module.After you enable the modules, select the E-Documents Contoso Module, and then choose the Generate action.Follow the steps.Close the page.
After you enable the module, you have demo items, six electronic documents (based on Peppol BIS 3), and configured E-Document Services with created workflows.
Use E-documents in sales
第一步:E-documents service设置好导入和导出的格式参数
第二步:在E-document 上载
第三步:在posted sales invoice查看e-document
第四步:日志
You can use configured electronic documents (e-documents) with the following sales documents:
Sales invoicesSales ordersSales credit memosService invoicesService credit memosFinance charge memosReminders
E-documents in sales
To create and send an e-invoice to a customer, you must create and post the sales invoice. To learn more about the standard process, go to Invoice Sales.
Before posting, you can choose to add the attachment to the invoice if you want to embed it in the Peppol file format.
After you post the sales document, open the Posted Sales Invoices page to access the related E-Documents page.
View e-documents
To view existing e-documents, follow these steps.
On the Posted Sales Invoices page, select E-Document, and then select Open E-Document.On the E-Documents page, on the header, you can view basic information about the posted invoice.The Record field shows the document number of the posted sales invoice. Select the link to open the document.In the Electronic Document Status field, you can view the real-time status of the document and its location in the process. If the document is posted, the status is Processed.
E-document statuses and logs
For details about the service status level of your e-document, check the E-Document Service Status FastTab. On the lines, the system shows one or more services that the document used. In the most common scenario, each document uses only one service. However, a document can use multiple services.
Check the E-Document Service Code field to determine which service was used.Check the E-Document Status field to determine the current service status for this document.If you want more details, select the Logs field for the service on the E-Document Logs page. A chronological overview of the different statuses for the document is shown.Check the Entry No. and Created At fields, and other information on the E-Document Logs page. In the E-Document Status field, the first status is Exported, which indicates that the e-document file has been created. The next status is Sent, which indicates that document was sent to the service provider, if configured.
For more insights, select the entry that has the Exported status, and then run one of the following actions:
Open Mapping Logs – Get an overview of all exported fields from the sourced tables in the Original Value field. If you used transformation rules in the export process, you can also get the final value in the New Value field.Export File – Export the XML file for manual review.
To view the communication between yourself and the service that you're sending your document to, use the Communication Logs field. Open the E-Document Communication Logs page to view details about the request and reasons message with that service.
If there's an issue with the service provider, and the document can't be sent, look for the following indicators on the E-Documents page:
The Electronic Document Status field on the header shows the Error status.The E-Document Status field on the E-Document Service Status FastTab shows the Sending Error status.The Error and Warnings FastTab contains one or more messages that provide the cause of the issue.
After the issue is fixed, manually run the Send Document actions. If you need different actions, such as Recreated Document, Cancel Document, or Get Approval, you can run them.
Manually create e-documents when they weren't created automatically
Using e-documents requires some configuration, and sometimes people get that wrong. If there was a problem with your setup when you posted sales documents, Business Central might not automatically create e-documents for them. If that happens, after you fix your setup, you can generate new e-documents from the posted documents.
To check whether Business Central created an e-document, open the Posted Sales Invoice page and select the Open E-Document action. If Business Central doesn't find a related e-document, a message displays. Review your settings for your e-documents and correct any mistakes. To learn more about the setup, go to Set up e-documents.
When you're ready, you can run the Create New E-Document action to generate an e-document based on the workflow rules.
Overview of e-document statuses
To get a better overview of all e-documents in the company, you can select the Accountant role center where e-document statuses exist. There, you can find e-document activities that have the following statuses:
Outgoing e-documents:
ProcessedIn ProgressError
Use E-documents in purchases
You can use configured electronic documents (e-documents) with the following purchase documents:
Purchase invoicesPurchase ordersPurchase credit memosGeneral journals
Note
When you receive an e-document from a specific vendor, Business Central matches the e-document with the vendor by verifying the following information in this order:
GLN (from the Vendor card)VAT Registration No. (from the Vendor card)Participation Identifier from the Service Participant page (using the E-Document Service Participation field from the Vendor card)Name and Address (from the Vendor card)
E-documents in purchases
You can receive purchase e-documents manually, or by using the Receive batch job.
Set up vendors to work with different purchase documents
Follow these steps to configure vendors for incoming electronic invoices:
Select the
icon, enter Vendors, and then select the related link.Choose the vendor you want to configure.On the Receiving FastTab, in the Receive E-Document To field, specify the default purchase document you want to generate from the received e-document.
Note
In the Receive E-Document To field, you can either select a Purchase Invoice or Purchase Order based on what you want to create from the received e-invoice. This selection doesn't affect the creation of corrective documents. In both scenarios, Business Central generates a credit memo.If you choose the Purchase Order option in the Receive E-Document To field, Business Central tries to update one of the existing purchase orders. However, if the purchase order for a vendor in the received e-document doesn't exist, Business Central creates a new purchase order, using the same approach as creating a new purchase invoice explained in this article later. Choose one of the options you want to use for the selected vendor.Close the page.
Work with purchase invoices
Run the batch job
Note
This batch job automates the process of collecting your incoming invoices. It works only in countries or regions where the functionality is available.
Every time a Job Queue runs, if the external service has incoming invoices from your vendor, Business Central collects and imports those invoices. To complete the process, follow these steps:
After the batch job finishes running, the imported invoices are listed on the E-Documents page with their basic details.To view more details, open a specific e-document.Depending on whether your e-document setup automatically processes invoices, or requires that you review and confirm the details before processing, follow these steps. Learn more in Set up e-documents for information about how to require confirmation.
Automatic processing
If you automatically process invoices, and there are no errors or issues in the e-document, the Record field maps the document number of the purchase invoice if a number series is specified on the Vendor Card page. To open the document, select the link.
Note
This Business Central-created document isn't the posted document.
To go directly to the purchase document, select the Record field. After you open the Purchase Invoice page, check the document. If everything is correct, post the document.When you post the purchase document, the Record field on the E-Document updates from Invoice to Purchase Invoice, and the number of the posted purchase document is available. You can select the number to open it. Details about logs are the same as they are in the sales process for e-documents.
Review and confirm before processing
If you must review and confirm the details before processing the invoice, open the document.On the E-Document page, choose the View extracted data action.On the Received purchase document data page, review the details. If things look good, choose OK.To process the invoice, follow the steps described for Automatic processing.
Tip
When you receive an incoming e-document, it's typically in XML or similar format that can be difficult, if not impossible, to read. For example, if you aren't technical and don't understand the XML format, it might be hard to review an invoice before you process it. To make it easier for everyone to review incoming e-documents, invoices and credit memos have an E-invoice Lines FastTab that displays details from the imported file, such as line and header information, in a way that's easy to understand.
The preview feature is only available for invoice and credit memo types of incoming e-documents.
Handle errors and warnings
Errors in the sales process are mostly related to the availability of the service. The incoming document can contain multiple reasons for errors. The most common reason is that Business Central can't recognize the lines on an e-document from your vendor and can't enter lines in your purchase invoice.
There are two common errors:
If you want to use a specific line from your vendor invoice that was directly posted to the general ledger (G/L) account, you must correctly configure the Mapping Text value. To bypass this error when using G/L accounts, select the Map Text to Account to create a specific mapping of the Mapping Text value with the Debit Acc. No.. Learn more about account mapping.If you want to track the inventory and use lines from your vendor invoice to fill in the items on your document lines, you must correctly configure the Item Reference No. value. To bypass this error, map external items with your item numbers by using the item reference list. Learn more in use item references.
After you fix the errors and warnings, you can manually specify when to create a purchase invoice based on your setup by selecting Create Document.
Recreate a deleted purchase invoice or credit memo
Mistakes happen, so it's important to be able to fix them quickly. If you accidentally delete a purchase invoice or credit memo and can't link the incoming e-document to the correct one, you can now recreate a new purchase document based on details in the e-document. Problem solved, and you can go take care of other business.
If you accidentally delete a purchase invoice or credit memo, you can't proceed with the e-document connection with the regular purchase document in Business Central. To get yourself unstuck, you can run the Recreate Document action from the e-document. The action creates an unposted purchase invoice or credit memo based on the type of incoming document, its information, and the G/L mapping or item references used.
Note
The action works only with unposted purchase invoices and credit memos. It doesn't work for purchase orders.
Map text on an e-document to a specific vendor account
To map lines with expenses for E-Documents, you need to map descriptions with G/L Account. Then, use the Map Text to Account action to link specific text on a vendor invoice from the E-Document Service to a vendor account. Any part of the E-document description that exists as a mapping text means that the Vendor No. field on the resulting document or journal lines of type G/L Account are filled with the vendor in question.
In addition to mapping text to a vendor account or G/L accounts, you can also map text to a bank account for electronic documents related to paid expenses. This option creates a general journal line that is ready to post to a bank account.
Select the relevant E-Document line with the displayed error message and then choose Map Text to Account action. The Text-to-Account Mapping page displays.In the Mapping Text field, enter any text that appears on vendor invoices for which you want to create purchase documents or journal lines. You can enter up to 50 characters.In the Vendor No. field, enter the vendor that the resulting purchase document or journal line will be created for.In the Debit Acc. No. field, enter the debit-type G/L account that is inserted on resulting purchase document or journal line of type G/L Account.
Note
Don't use the Credit Acc. No., Bal. Source Type, and Bal. Source No. fields with E-documents.
Repeat steps 2 through 5 for all error messages on E-documents that you want to automatically create G/L Accounts and documents for.
Manually import one or more invoices
To manually import one or more external e-documents, follow these steps:
Select the
icon, enter E-Document Service, and then select the related link.On the E-Document Service page, select the active service.Select Receive, and upload the e-document file that you got from the vendor.If an error message occurs, open the e-document to fix the issues.When you finish fixing the issues, in the Import Manually group, select Create Document.After you create the document in Business Central, using a batch job doesn't change the way you view it.
Work with attachments
Peppol and similar e-invoicing files are machine-readable formats that aren't easy for people to read. To improve reading, Peppol made it possible to embed a PDF file into the Peppol BIS 3 format as a binary object. If your incoming Peppol BIS 3 file has an embedded PDF, Business Central automatically processes it and adds the PDF as an attachment to the purchase document after creating it.
E-documents with purchase orders
Link purchase orders with the received e-documents
If your Vendor configured the Received E-Document To field to work with Purchase Orders, once an electronic document is created in Business Central (manually or from external end point), Business Central does the following steps:
If the Purchase Order for this particular vendor exists and there's a purchase order number in the receive E-Document file, Business Central automatically links this E-Document with the mentioned Purchase Order, and the Document Status of this E-Document is set to In Progress, and the E-Document Status in the Service Status subpage is set to Order linked. This link is visible in the Document field on this specific E-Document. If you need to change the Purchase Order linked automatically, you can do it using the Update Purchase Order Link action and manually select one of the existing purchase orders for this vendor. You can only do it before matching the lines between E-Document and Purchase Order.If the Purchase Order for this particular vendor exists but there's no purchase order number in the received E-Document file, Business Central offers the possibility to choose one of the existing purchase orders when and if you uploaded this document manually. This condition opens the Purchase Orders list with orders only for the vendor from whom you received the E-Document. You need to select the Purchase Order you want and then select OK. If you failed to select the correct Purchase Order, or obtained the E-Document automatically from an external endpoint using the Job Queue, a new E-Document isn't linked to any purchase document. The Document Status then shows Error, and the E-Document Status in the Service Status subpage also shows Imported document processing error. To finish linking with the Purchase Order, select the Update Purchase Order Link action and choose one of the existing purchase orders for this vendor.If the Purchase Order for this particular vendor doesn't exist when a new E-Document is created, Business Central creates a new Purchase Order, using the same model of creation that already exists for new Purchase Invoices. The Document Status of this E-Document is set to Processed, and the E-Document Status in the Service Status subpage is set to Imported document created. After which, this link is visible in the Document field on this specific E-Document.
Match lines from received e-document with purchase order
You can match your received electronic documents with purchase orders' lines from two different places: from the E-Document page or from the Purchase Order page. The easiest way to locate the already linked Purchase Orders is to use the Linked Purchase Orders tile as a part of E-Document Activities. All nonlinked documents can be found using the tile Waiting Purchase E-Invoices where you have a list of E-Documents that you need to review. The E-Document Activities with these two tiles can be found in the following Role Centers: Business Manager Evaluation, Business Manager, Accountant, Inventory Manager, and Shipping and Receiving.
Tip
There are two ways to match lines. One way is to do it manually, as described in the article. The other way is to use the E-document matching assistance with Copilot. The E-document matching assistance feature helps you match received electronic invoices with existing purchase order lines by using large language modules (LLM) model. Learn more about [using Copilot]Map e-documents to purchase order lines with Copilot.
Note
If the VAT percentage differs between the incoming document and the company's VAT percentage, matching documents can't be used in a multi-country environment.
Match lines from purchase order
You can match the lines from the Purchase Orders list or from one of the opened Purchase Orders. To begin the process, use the following steps:
Select the Linked Purchase Orders tile on your Role Center if there's a number.Choose one of the two options for matching:
If you want to match the lines from the Purchase Orders list, select the Purchase Order line that you want to match and select the Map E-Document Lines action.If you want to first open the Purchase Order, open the document and then select the Map E-Document Lines action. Because both options have the same process, the Purchase Order Matching page opens with the following content:
In the header, you can find the following information, which can help you to map the lines easier:
Field name |
Description |
Vendor Name |
Specifies the vendor’s name of the electronic document. |
E-Document No. |
Specifies the linked electronic document number. |
E-Document Date |
Specifies the linked electronic document date. |
E-Document Amount |
Specifies the linked e-document total amount including VAT. |
In the lines, you can find the lines imported from the E-Document file on the left side and the lines from the existing Purchase Order on the right.All lines on both sides have item numbers and descriptions, together with the Direct Unit Cost and Line Discount %.On the Imported Lines side, you can also locate the Quantity field as a total quantity from e-invoice and the Matched Quantity field specifying the quantity that is already matched to the purchase order lines.On the Purchase Orders Lines side, you can also find the Available Quantity as the quantity that can be matched to this line (received, but not invoiced quantity) and Qty. to Invoice, specifying the quantity that is already matched to this linTo match lines, select the lines on both sides that you want to match and select the Match Manually action. The matched lines are marked in green.It's possible to match one to one, but it's also possible to match many to one or one to many, by selecting more lines on one side or the other before you choose the Match Manually action.You can also select the Match Automatically action to automatically match all lines with the same Type, No., Unit Price, Discount, and Unit of Measure.If you make a mistake, you can select the Remove Match action to remove the matched lines on the purchase order side or select the Reset Matching action to reset all matches.If your E-Document has many lines, you can select the Show Pending Lines action during the matching process to remove all the e-document lines if they're already matched. If you need to view all the lines, you can always select the Show All Lines action. After you finish the matching, select the Apply To Purchase Order action.After you apply the matching to the purchase order, Business Central updates the following fields:
The Vendor Invoice No. and Document Date fields on the document header update with values from the electronic document that you received and linked.The Qty. to Invoice field on the lines update with the values from the Qty. to Invoice column from the Purchase Order Matching page based on the match.Now you can post the document by choosing the Post action.After you post the document, the value in the Document field on the E-Document page changes to relate to the Posted Purchase Invoice.Close the pag
Important
By default, you can match only the lines that have the same total amount in both documents. That means Direct Unit Cost together with the applied Line Discount % must be the same, because in one document you can have an amount without discount and in another with discount.
If you want to add tolerance and allow the difference between lines in e-invoice and purchase order, follow these steps:
Select the
icon, enter Purchases & Payables Setup, and then select the related link.Allow tolerance in the E-Document Matching Difference % field by specifying the maximum percentage of cost difference to allow when matching an incoming e-document line with a purchase order line.This setup applies to all the matching lines, but considers the tolerance for the total amount, as for Direct Unit Cost together with applied Line Discount %.Close the page.
Other options
If your inbound electronic invoice has lines that aren't on your purchase order, Business Central prevents you from posting the document because you can't partially post an incoming invoice. Therefore, you must ensure that you all invoice lines are correctly mapped to the purchase order. If you experience this issue, follow these steps to resolve it:
On the Imported Lines FastTab on the Purchase Order Matching page, choose the line that doesn't exist on the purchase order. Now choose the
button, and choose the Create Purchase Order Line action.On the E-Doc. Create Purch Order Line page, in the Type field, choose the type of line you want to create in your purchase order. You can choose any of type.Based on the line type, you can choose the No. to specify what you received. For example, an item, general ledger account, resource, and so on.The unit of measure, quantity, amount, discount, and other values are copied from the inbound invoice line.You can select the Learn matching rule field to specify whether to create a matching rule. This feature works only for items and G/L accounts. Item references are created for items and text to account mappings are created for G/L accounts.Select OK.A purchase order line is created on the purchase order, and you can map it on the Purchase Order Lines FastTab on the Purchase Order Matching page.
Note
If you change the quantity, the unit amount recalculates to the same total amount as the original invoice line.
Matching lines from e-document
You can match the lines on the E-Document page. To begin, use the following steps:
Select the
icon, enter E-Documents, and then select the related link.Select the E-Document that you want to match.Choose the Match Purchase Order action to open the Purchase Order Matching page.Repeat the same steps that you used when you started matching from purchase orders.
Overview of e-document statuses
To get a better overview of all e-documents in the company, you can select the Accountant Role Center where e-document statuses exist. There, you can find e-document activities that have the following statuses:
Incoming e-documents:
ProcessedIn ProgressError
Set the E-documents connector with external endpoint
This article explains how to set up E-Documents functionality when connected to external endpoints.
Before you use the functionality that this article describes, you must install the E-Document Core app and one of the E-Documents connectors with external endpoints apps. You can use these apps for default integration with the external, non-Microsoft, access points to automate the e-document flow. Because these apps represent only some of the selected connectors, you aren't limited to existing integrations.
Install an E-Documents connector
To install an E-Documents connector, follow these steps:
Select the
icon, enter E-Document Services, and then select the related link.Choose the Install E-Documents integration from AppSource action to open the Microsoft AppSource apps page.Choose the connector you want, and then select the View on AppSource action.Install the app from the AppSource.
Set up the connection
To begin your setup, follow the steps in E-document core app. After you complete those steps, return to this article and complete the following steps:
Select the
icon, enter E-Document Services, and then select the related link.In the Service Integration field, select one of the integration codes that are offered for the endpoint service setup.Select Setup Service Integration.
Based on the endpoint service provider, the next steps might be different. You can find details about set up parameters for all available service providers here.
Set up company information
Before you start using e-documents, update your Company Information page by completing the following steps:
Select the
icon, enter Company Information, and then select the related link.In addition to filling in the usual fields, you must also fill in the following fields:
Field name |
Description |
SWIFT Code |
Specifies the SWIFT code (international bank identifier code) of your primary bank. |
Bank Branch No. |
Specifies the bank's four-digit branch number. |
VAT Registration No. |
Specifies the company's value-added tax (VAT) registration number. |
GLN |
Specifies your company in connection with electronic document exchange. |
Use GLN in Electronic Document |
Specifies whether the GLN is used in electronic documents as a party identification number. |
Close the page.
Set up customers to receive e-documents
To enable customers to receive your e-documents, complete the following steps:
Select the
icon, enter Customers, and then select the related link.Open the Customer card.In addition to filling in the usual fields, in the GLN field, specify the customer you send electronic documents to.Turn on the Use GLN in Electronic Documents toggle to indicate whether to use the global location number (GLN) as an identification number in electronic documents.Close the page.
Other setup
Before you start to work with e-documents, set up the e-document workflows and document sending profiles to use your workflows. After the service connection is established, you can start to use your e-document solution.
Available service providers
Microsoft wants to encourage access point providers to add their connectors on top of our E-Document Core app.
The following list of access point providers are covered by default:
AvalaraB2BRouterContiniaLogiqPageroSignUp
Microsoft has no contractual obligations with these providers. Therefore, you must make a contract with them to get the necessary credentials. The services might require extra licensing or payments for their services.
Parameter for setting the E-documents connector with external endpoint
To begin your setup, follow the steps in E-document core app. After you complete those steps, return to this article and complete the following steps:
Select the
icon, enter E-Document Services, and then select the related link.In the Service Integration field, select one of the integration codes that are offered for the endpoint service setup.Select Setup Service Integration.
You can use E-Documents in Business Central to send and receive electronic documents with your business partners. To receive documents, you need to connect E-Documents to an external access point that handles the communication and validation of the documents.
Note
These connections require communication with external service providers who might require other payments and contracts. To get the credentials you need, contact the service providers.
The steps to connect E-Documents to an external access point depend on the type of connector you choose.
Available service providers
Business Central supports Pagero, Avalara, Logiq, SignUp, and B2BRouter access points for e-documents. If we add more connectors, we'll update this article with the parameters when they're ready. You can also find more connectors on AppSource.
Note
This article doesn't explain how to connect with local service providers. You can learn more about the local service providers that Business Central supports in the country-specific documentation.
Microsoft doesn't have a contractual obligation with Pagero and Avalara. You must have a contract with them if you want to use their connectors.
Pagero service
On the E-Document Service page, change the Service Integration to Pagero.On the E-Document Service page, select the Setup Service Integration action.On the E-Document External Connection Setup page, select the Open OAuth 2.0 setup action to open the OAuth 2.0 Setup page.On the OAuth 2.0 setup page, select the Request Authorization Code action. You're redirected to the external service authorization webpage and prompted to sign-in.Copy the authorization code into the Enter Authorization Code field.Select Refresh Access Token to make sure that you can refresh the token.On the E-Document External Connection Setup page, fill in the following fields:
Field name |
Description |
FileAPI URL |
Specify the file API URL. |
Fileparts URL |
Specify the fileparts URL. |
DocumentAPI URL |
Specify the document API URL. |
Company ID |
Specify the company ID. |
Send Mode |
Specify the send mode. You can select Production, Test, or Certification. |
Continue with the nonservice provider setup steps.
Avalara service
On the E-Document Service page, change the Service Integration to Avalara.On the E-Document Service page, select the Setup Service Integration action.On the Avalara Connection Setup page, enter the Client ID and Client Secret fields. In the Send Mode field, choose the Production, Test, or Certification option, based on your plans.Select the Select Avalara Company Id action, and choose the company. Make sure you fill in the Company Name and Company ID fields.Select the Select Avalara Mandate action, and select the right E-Document Service, and then choose the Country Mandate code on the Avalara Mandate List page.Return to the E-Document Service page, and validate that the Avalara Mandate field on the Avalara FastTab is set with the value you chose.Continue with the nonservice provider setup steps.
Logiq service
On the E-Document Service page, change the Service Integration to Logiq.On the E-Document Service page, select the Setup Service Integration action.On the Logiq Connection Setup page, enter tokens to the Client ID and Client Secret fields, and then choose the Environment as Pilot or Production.Run the User Setup action and enter your credentials. Choose the API Engine (Engine 1 or Engine 3) based on the instructions from the provider.Select the Get Tokens to access tokens for the current user.Continue with the nonservice provider setup steps.
SignUp service (ExFlow)
On the E-Document Service page, change the Service Integration to ExFlow E-Invoicing.On the E-Document Service page, select the Setup Service Integration action.On the Logiq Connection Setup page, enter the Client ID and Client Secret fields and the Authentication URL to specify the URL to connect to Microsoft Entra.Fill in the Service URL field with the URL you got from your provider. In the Environment Type field, specify whether you want to use it for test or production.Run the Open Onboarding action to start the onboarding process with your provider in a new browser window.Continue with the nonservice provider setup steps.
B2BRouter service
On the E-Document Service page, change the Service Integration to B2BRouter.On the E-Document Service page, select the Setup Service Integration action.On the B2BRouter Connection Setup page, enter the API-KEY to specify the key you'll use for your B2BRouter environment and the ProjectID field to specify the project name for the B2BRouter environment.If you want to use this connector in sandbox mode, select the Staging Mode field.Continue with the nonservice provider setup steps.
Extending E-documents functionality
The E-Document Core module is created as an extension and built as a framework. Therefore, by default, there are just a few Document Formats, which are based on the localization you're using. This detail, and others, are mostly components of localization apps, which cater to specific local requirements. This framework is intended to cover most requirements for the process of communication with electronic documents (e-documents). However, some parts are left for localization apps. The information in this article helps you add value to this module and use it for your own localization.
Additionally, when you explore the Service Integration option, you find several choices available. However, if there's a need to add your own service, whether it's a local connector or another global or regional connector, you can extend this app by adding new services based on your requirements. This can be done as part of localization or as a new ISV app.
Note
The updated interface will be available from Business Central 2025 release wave 1 (v26.0).
Develop an e-documents extension
In order to implement your localization or other extension on top of the E-Document Core application, you should perform the following procedures.
Create and set up a new extension
Create a new extension and add a dependency to the E-Document Core application in your app.json file:
JSONCopy
“dependencies”: [
{
“id”: “e1d97edc-c239-46b4-8d84-6368bdf67c8b”,
“name”: “E-Document Core”,
“publisher”: “Microsoft”,
“version”: “23.0.0.0”
}
]
Implement the document interface
The e-document interface comprises a collection of methods designed to streamline the export of Business Central documents (such as sales invoices) into e-document blobs based on the predefined format specifications. Furthermore, it facilitates the reverse process by enabling the import of documents from blobs back into Business Central.
First, you must extend the enum and associate it with your implementation codeunit:
ALCopy
enumextension 50100 “EDocument Format Ext” extends “E-Document Format”
{
value(50100; “PEPPOL 3.x”)
{
Implementation = “E-Document” = “PEPPOL EDocument”;
}
}
The document interface has been divided into two sections:
Create an e-document from a Business Central document that can be sent to a designated endpoint: Check, Create, CreateBatch.Receive a document from the endpoint: GetBasicInfo, PrepareDocument.
Here's an example of how you could implement each of the methods within the interface:
Check: Use it to run a check on the release/post action of a document to make sure all necessary fields to submit the document are available.
ALCopy
procedure Check(var SourceDocumentHeader: RecordRef; EDocumentService: Record “E-Document Service”; EDocumentProcessingPhase: Enum “E-Document Processing Phase”)
var
SalesHeader: Record “Sales Header”;
begin
case SourceDocumentHeader.Number of
Database::”Sales Header”:
begin
SourceDocumentHeader.Field(SalesHeader.FieldNo(“Customer Posting Group”)).TestField();
SourceDocumentHeader.Field(SalesHeader.FieldNo(“Posting Date”)).TestField();
end;
end;
You also have the option to perform distinct checks depending on the document processing phase.
ALCopy
procedure Check(var SourceDocumentHeader: RecordRef; EDocumentService: Record “E-Document Service”; EDocumentProcessingPhase: Enum “E-Document Processing Phase”)
var
SalesHeader: Record “Sales Header”;
begin
case SourceDocumentHeader.Number of
Database::”Sales Header”:
case EDocumentProcessingPhase of
EDocumentProcessingPhase::Release:
begin
SourceDocumentHeader.Field(SalesHeader.FieldNo(“Customer Posting Group”)).TestField();
SourceDocumentHeader.Field(SalesHeader.FieldNo(“Posting Date”)).TestField();
end;
EDocumentProcessingPhase::Post:
begin
SourceDocumentHeader.Field(SalesHeader.FieldNo(“Customer Posting Group”)).TestField();
SourceDocumentHeader.Field(SalesHeader.FieldNo(“Posting Date”)).TestField();
SourceDocumentHeader.Field(SalesHeader.FieldNo(“Bill-to Name”)).TestField();
end;
end;
end;
end;
Create: Use it to create a blob that represents the posted document. At this point, the core extension has created an e-document record with initial information like the document type, and automatically determined the type of the document, that you can find in the Document Type field.
Note
The document type is automatically identified by the core extension based on the source document. In case you have introduced your custom document type, you must extend the E-Document Type enum and populate the E-Document Type field accordingly.
ALCopy
procedure Create(EDocumentService: Record “E-Document Service”; var EDocument: Record “E-Document”; var SourceDocumentHeader: RecordRef; var SourceDocumentLines: RecordRef; var TempBlob: Codeunit “Temp Blob”)
var
OutStr: OutStream;
begin
TempBlob.CreateOutStream(OutStr);
case EDocument.”Document Type” of
EDocument.”Document Type”::”Sales Invoice”:
GenerateInvoiceXMLFile(SourceDocumentHeader, OutStr);
EDocument.”Document Type”::”Sales Credit Memo”:
GenerateCrMemoXMLFile(SourceDocumentHeader, OutStr);
end;
end;
CreateBatch: Use it to create a blob that represents a batch of posted documents. Similar to the create method, this functionality permits you to iterate through a collection of e-documents and generate a singular blob that collectively represents them.
ALCopy
procedure CreateBatch(EDocumentService: Record “E-Document Service”; var EDocuments: Record “E-Document”; var SourceDocumentHeaders: RecordRef; var SourceDocumentsLines: RecordRef; var TempBlob: Codeunit “Temp Blob”)
var
OutStr: OutStream;
begin
TempBlob.CreateOutStream(OutStr);
if EDocuments.FindSet() then
repeat
OutStr.WriteText(EDocuments.”Document No.”);
until EDocuments.Next() = 0;
end;
GetBasicInfo: Use it to get the basic information of an e-document from a received blob.
ALCopy
procedure GetBasicInfo(var EDocument: Record “E-Document”; var TempBlob: Codeunit “Temp Blob”)
var
XmlDoc: XmlDocument;
DocInstr: InStream;
NamespaceManager: XmlNamespaceManager;
begin
// Create an XML document from the blob
TempBlob.CreateInStream(DocInstr);
XmlDocument.ReadFrom(DocInstr, XmlDoc);
// Parse the document to fill EDocument information
EDocument.”Bill-to/Pay-to No.” := CopyStr(GetPEPPOLNode('//cac:InvoiceLine/cbc:ID', XmlDoc, NamespaceManager), 1, 20);
EDocument.”Bill-to/Pay-to Name” := CopyStr(GetPEPPOLNode('//cac:AccountingCustomerParty/cac:Party/cac:PartyName/cbc:Name', XmlDoc, NamespaceManager), 1, 20);
Evaluate(EDocument.”Document Date”, GetPEPPOLNode('//cbc:IssueDate', XmlDoc, NamespaceManager));
EDocument.”Document Type” := EDocument.”Document Type”::”Purchase Invoice”;
end;
PrepareDocument: Use it to create a document from an imported blob.
ALCopy
procedure PrepareDocument(var EDocument: Record “E-Document”; var CreatedDocumentHeader: RecordRef; var CreatedDocumentLines: RecordRef; var TempBlob: Codeunit “Temp Blob”)
begin
end;
Note
The Create and CreateBatch methods will generate a blob, which is stored in the log table. When a user exports it, the E-Document Core will export it without a predefined file extension. If you want to specify the file extension, you can use the following event subscriber:
ALCopy
[EventSubscriber(ObjectType::Table, Database::”E-Document Log”, 'OnBeforeExportDataStorage', '', false, false)]
local procedure MyProcedure()
begin
end;
Implement the integration interface
The e-document integration interface comprises a collection of methods designed to streamline the process of integrating with endpoints for submitting electronic documents.
First, you must extend the enum and associate it with your implementation codeunit:
ALCopy
enumextension 50100 Integration extends “Service Integration”
{
value(50100; “Avalara”)
{
Implementation = IDocumentSender = “Integration Impl.”, IDocumentReceiver = “Integration Impl.”;
}
}
Sending
Here's an example of how you could implement each of the methods within the IDocumentSender interface:
The IDocumentSender interface defines methods for sending e-documents to an external service. By implementing this interface, you enable integration between an application and external e-document services. This interface is part of the Microsoft.eServices.EDocument.Integration.Interfaces namespace and facilitates asynchronous and batch operations while ensuring proper logging of communication details.
Key features of the IDocumentSender interface
Async Sending: Supports asynchronous sending of e-documents.Batch Processing: Enables sending multiple e-documents using filters.Automatic Logging: Automatically logs HTTP request content and headers when provided in SendContext.
How to implement the IDocumentSender interface
To implement the IDocumentSender interface, you need to provide logic for the Send procedure, which handles sending e-documents. Below is a detailed guide and example implementations.
Send method
The Send method is responsible for sending an e-document to an external service. It takes three parameters:
EDocument: The record representing the e-document to be sent.EDocumentService: The record containing service configuration details such as the URL and access tokens.SendContext: A codeunit that provides context and resources for the send operation.
Example implementation of the Send method
Here's an example implementation of the Send method:
ALCopy
procedure Send(var EDocument: Record “E-Document”; var EDocumentService: Record “E-Document Service”; SendContext: Codeunit SendContext)
var
MyServiceSetup: Record MyServiceSetup;
TempBlob: Codeunit “Temp Blob”;
HttpClient: HttpClient;
HttpRequest: HttpRequestMessage;
HttpResponse: HttpResponseMessage;
begin
// Retrieve the TempBlob from SendContext
SendContext.GetTempBlob(TempBlob);
// Prepare the HTTP request using the TempBlob content
HttpRequest := SendContext.Http().GetHttpRequestMessage();
HttpRequest.Method := 'POST';
HttpRequest.SetRequestUri(MyServiceSetup.”Service URL”);
SetContent(HttpRequest, TempBlob); // Some method to do that
// Add authorization headers
HttpRequest.Headers.Add('Authorization', 'Bearer ' + MyServiceSetup.”Access Token”);
// Send the request and capture the response
HttpClient.Send(HttpRequest, HttpResponse);
// Handle the response
if HttpResponse.IsSuccessStatusCode() then
Message('E-Document sent successfully.');
else
Error('Failed to send E-Document: %1', HttpResponse.ReasonPhrase);
end;
Notes for the implementation
When implementing the IDocumentSender interface, consider the following best practices:
Asynchronous sending: To support asynchronous sending, ensure that the implementation also includes the IDocumentResponseHandler interface. This enables the processing of responses for async requests.Batch support: When handling multiple e-documents in batch operations, the EDocument record is populated using filters.Error handling: Properly handle HTTP response errors and log necessary details for debugging and monitoring.Logging: Use the SendContext to log HTTP request details for traceability.
Sending async
The IDocumentResponseHandler interface provides a standardized method for retrieving responses from external e-document services for asynchronously sent e-documents. If the service is handling documents async, implement this interface on the same codeunit that implements IDocumentSender.
The primary purpose of the IDocumentResponseHandler is to retrieve the status of a previously sent E-Document from the external service and appropriately update the E-Document Service Status based on the response. It also logs relevant HTTP response details automatically for better traceability.
Key features of the IDocumentResponseHandler interface
Asynchronous Response Handling: Supports retrieving responses for asynchronously sent E-Documents.Status Updates: Automatically updates the E-Document status based on the external service's response.Error Management: Handles errors gracefully, including logging error details.Automatic Logging: Automatically logs HTTP request and response details when using SendContext.
How to implement the IDocumentResponseHandler interface
To implement the IDocumentResponseHandler interface, you need to provide logic for the GetResponse procedure, which handles retrieving the status of an e-document. Below is a detailed guide and example implementation.
GetResponse method
The GetResponse method retrieves the response from the external service for an asynchronously sent e-document. It takes three parameters:
EDocument: The record representing the e-document for which the response is being retrieved.EDocumentService: The record containing service configuration details such as the URL and access tokens.SendContext: A codeunit that provides context and resources for the get-response operation.
Example implementation of the GetResponse method
Here's an example implementation of the GetResponse method:
ALCopy
procedure GetResponse(
var EDocument: Record “E-Document”;
var EDocumentService: Record “E-Document Service”;
SendContext: Codeunit SendContext
): Boolean
var
MyServiceSetup: Record MyServiceSetup;
HttpClient: HttpClient;
HttpRequest: HttpRequestMessage;
HttpResponse: HttpResponseMessage;
begin
// Prepare the HTTP request to check the status of the E-Document
HttpRequest := SendContext.Http().GetHttpRequestMessage();
HttpRequest.Method := 'GET';
HttpRequest.SetRequestUri(MyServiceSetup.”Service URL” + '/status/' + EDocument.”Document ID”);
HttpRequest.Headers.Add('Authorization', 'Bearer ' + MyServiceSetup.”Access Token”);
// Send the HTTP request
HttpClient.Send(HttpRequest, HttpResponse);
// Set the response in SendContext for automatic logging
SendContext.Http().SetHttpResponseMessage(HttpResponse);
// Handle the response based on the HTTP status code
if HttpResponse.IsSuccessStatusCode() then
exit(true); // The document was successfully processed
else if HttpResponse.HttpStatusCode() = 202 then
exit(false); // The document is still being processed
else begin
// Log the error and set the status to “Sending Error”
EDocumentErrorHelper.LogSimpleErrorMessage(EDocument, 'Error retrieving response: ' + Format(HttpResponse.HttpStatusCode()));
exit(false);
end;
end;
Receiving
The IDocumentReceiver interface provides a standardized method for receiving and downloading electronic documents (e-documents) from external API services. If your system requires integration with an e-document service, implement this interface to handle document retrieval and data download operations efficiently.
Key features of the IDocumentReceiver interface
Document Retrieval: Fetch one or more e-documents from an external API and store their metadata in temporary blobs for processing.Content Download: Download the specific content (for example, XML, PDF) of a document using its metadata.Error Handling: Log and handle errors gracefully during the retrieval and download processes.Context Management: Use ReceiveContext for managing HTTP requests and responses.
How to implement the IDocumentReceiver interface
To implement the IDocumentReceiver interface, you need to provide logic for the ReceiveDocuments and DownloadDocument methods. Below are detailed explanations and example implementations.
ReceiveDocuments method
The ReceiveDocuments method retrieves one or more documents from the external API and stores their metadata in temporary blobs for further processing.
Parameters of the ReceiveDocuments method
EDocumentService: Record representing the e-document service configuration, including the API endpoint.DocumentsMetadata: Temporary blob list for storing retrieved document metadata.ReceiveContext: A codeunit providing context and resources for the receive operation.
Example implementation of the ReceiveDocuments method
ALCopy
procedure ReceiveDocuments(var EDocumentService: Record “E-Document Service”; DocumentsMetadata: Codeunit “Temp Blob List”; ReceiveContext: Codeunit ReceiveContext)
var
HttpRequest: HttpRequestMessage;
JsonResponse: JsonArray;
DocumentBlob: Codeunit “Temp Blob”;
JsonObject: JsonObject;
OutStream: OutStream;
begin
// Prepare the HTTP request
HttpRequest := ReceiveContext.Http().GetHttpRequestMessage();
HttpRequest.Method := 'GET';
HttpRequest.SetRequestUri(EDocumentService.”Service URL” + '/documents');
// Send the HTTP request
HttpClient.Send(HttpRequest, ReceiveContext.Http().GetHttpResponseMessage());
// Parse the JSON response
JsonResponse.ReadFrom(HttpResponse.ContentAsText());
// Iterate over each object in the JSON array and add a temp blob to the DocumentsMetadata list
foreach JsonObject in JsonResponse do begin
DocumentBlob.CreateOutStream(OutStream);
JsonObject.WriteTo(OutStream);
DocumentsMetadata.Add(DocumentBlob);
end;
end;
DownloadDocument method
The DownloadDocument method downloads the content of a specific document (for example, XML, PDF) using the document metadata.
Parameters of the DownloadDocument method
EDocument: Record representing the specific e-document.EDocumentService: Record containing service configuration details such as the URL and authentication tokens.DocumentMetadata: Temporary blob containing the metadata for the document.ReceiveContext: A codeunit providing context and resources for the download operation.
Example implementation of the DownloadDocument method
ALCopy
procedure DownloadDocument(var EDocument: Record “E-Document”; var EDocumentService: Record “E-Document Service”; DocumentMetadata: Codeunit “Temp Blob”; ReceiveContext: Codeunit ReceiveContext)
var
Request: Codeunit Requests;
HttpExecutor: Codeunit “Http Executor”;
ResponseContent: Text;
InStream: InStream;
DocumentId: Text;
OutStream: OutStream;
begin
// Read the document ID from the DocumentMetadata
DocumentMetadata.CreateInStream(InStream, TextEncoding::UTF8);
InStream.ReadText(DocumentId);
if DocumentId = '' then begin
EDocumentErrorHelper.LogSimpleErrorMessage(EDocument, DocumentIdNotFoundErr);
exit;
end;
// Update the document record with the document ID
EDocument.”Document Id” := CopyStr(DocumentId, 1, MaxStrLen(EDocument.”Document Id”));
EDocument.Modify();
// Prepare the HTTP request
Request.Init();
Request.Authenticate().CreateDownloadRequest(DocumentId);
ReceiveContext.Http().SetHttpRequestMessage(Request.GetRequest());
// Execute the HTTP request
ResponseContent := HttpExecutor.ExecuteHttpRequest(Request, ReceiveContext.Http().GetHttpResponseMessage());
// Store the response in the ReceiveContext
ReceiveContext.GetTempBlob().CreateOutStream(OutStream, TextEncoding::UTF8);
OutStream.WriteText(ResponseContent);
end;
Sent document actions
The ISentDocumentActions interface provides a set of default actions for managing outgoing e-documents through integration with external APIs. This interface simplifies the process of communicating with external services to manage document statuses effectively. Developers can use the provided methods to handle approval and cancellation processes seamlessly, ensuring accurate status updates within the system.
Key features of the ISentDocumentActions interface
These actions allow you to:
Check approval status: Verify whether a sent e-document has been approved by the external service.Check cancellation status: Determine whether a sent e-document has been successfully canceled by the external service.Streamline integration: Standardize HTTP request handling for approval and cancellation workflows.
How to implement the ISentDocumentActions interface
To use the ISentDocumentActions interface, you need to implement the GetApprovalStatus and GetCancellationStatus methods. Each method interacts with the external API to manage the status of e-documents.
GetApprovalStatus method
Parameters of the GetApprovalStatus method
EDocument: Record of type “E-Document” representing the document to be approved.EDocumentService: Record of type “E-Document Service” for interacting with the external API.ActionContext: Codeunit ActionContext for managing HTTP requests and responses.
Example implementation of the GetApprovalStatus method
ALCopy
procedure GetApprovalStatus(var EDocument: Record “E-Document”; var EDocumentService: Record “E-Document Service”; ActionContext: Codeunit ActionContext): Boolean
var
Request: Codeunit Requests;
HttpExecutor: Codeunit “Http Executor”;
ResponseContent: Text;
begin
// Prepare the HTTP request
Request.Init();
Request.Authenticate().CreateApprovalRequest(EDocument.”Document ID”);
ActionContext.Http().SetHttpRequestMessage(Request.GetRequest());
// Execute the HTTP request
ResponseContent := HttpExecutor.ExecuteHttpRequest(Request, ActionContext.Http().GetHttpResponseMessage());
// Process the response to determine the approval status
if ResponseContent.Contains('approved') then begin
ActionContext.SetStatus(ActionContext.GetStatus().”Approved”);
exit(true);
end else if ResponseContent.Contains('rejected') then begin
ActionContext.SetStatus(ActionContext.GetStatus().”Rejected”);
exit(true);
end;
exit(false);
end;
GetCancellationStatus method
Parameters of the GetCancellationStatus method
EDocument: Record of type “E-Document” representing the document to be canceled.EDocumentService: Record of type “E-Document Service” for interacting with the external API.ActionContext: Codeunit ActionContext for managing HTTP requests and responses.
Example implementation of the GetCancellationStatus method
ALCopy
procedure GetCancellationStatus(var EDocument: Record “E-Document”; var EDocumentService: Record “E-Document Service”; ActionContext: Codeunit ActionContext): Boolean
var
Request: Codeunit Requests;
HttpExecutor: Codeunit “Http Executor”;
ResponseContent: Text;
begin
// Prepare the HTTP request
Request.Init();
Request.Authenticate().CreateCancellationRequest(EDocument.”Document ID”);
ActionContext.Http().SetHttpRequestMessage(Request.GetRequest());
// Execute the HTTP request
ResponseContent := HttpExecutor.ExecuteHttpRequest(Request, ActionContext.Http().GetHttpResponseMessage());
// Process the response to determine the cancellation status
if ResponseContent.Contains('canceled') then begin
ActionContext.SetStatus(ActionContext.GetStatus().”Canceled”);
exit(true);
end;
exit(false);
end;
Document action
Key features of the IDocumentAction interface
The IDocumentAction interface defines a general-purpose method for performing various actions on e-documents. It allows developers to:
Perform custom actions: Execute specified actions, such as resetting or updating the status of an e-document.Flexibly integrate: Use this interface to handle API requests and responses tailored to the specific action type.Streamline workflows: Centralize action execution logic for consistent and maintainable integration.Get logging and error handling: When using an action using the interface, you get all the logging and error handling for free, all built directly in the framework.
How to implement the IDocumentAction interface
To use the IDocumentAction interface, implement the InvokeAction method. This method executes a specified action by interacting with the external API and updates the e-document status accordingly. Then extend the action's enum and call the procedure InvokeAction(var EDocument: Record “E-Document”; var EDocumentService: Record “E-Document Service”; ActionType: Enum “Integration Action Type”; ActionContext: Codeunit ActionContext) in the Integration Management codeunit to run the action. You can call this from your own action.
InvokeAction method
Parameters of the InvokeAction method
EDocument: Record of type “E-Document” representing the document on which the action is performed.EDocumentService: Record of type “E-Document Service” for interacting with the external API.ActionContext: Codeunit ActionContext for managing HTTP requests and responses.
Example implementation of the InvokeAction method
ALCopy
procedure InvokeAction(var EDocument: Record “E-Document”; var EDocumentService: Record “E-Document Service”; ActionContext: Codeunit ActionContext): Boolean
var
HttpClient: HttpClient;
HttpRequestMessage: HttpRequestMessage;
HttpResponseMessage: HttpResponseMessage;
begin
// Initialize the HTTP request
HttpRequestMessage.Method := 'POST';
HttpRequestMessage.SetRequestUri('https://api.example.com/documents/reset');
HttpRequestMessage.Content.WriteFromText('{“documentId”: “' + EDocument.”Document ID” + '”}');
// Send the HTTP request and receive the response
HttpClient.Send(HttpRequestMessage, HttpResponseMessage);
// Process the response and set status
if HttpResponseMessage.IsSuccessStatusCode() then begin
ActionContext.SetStatus(Enum::”E-Document Service Status”::”MyStatus”);
exit(true);
end;
exit(false);
end;
Helper procedures
The E-Document Helper codeunit consists of a collection of utility methods that are highly recommended for building your localization app. These methods can assist you in various tasks, such as effortlessly logging any encountered error messages.
Codeunit list:
“E-Document Helper””E-Document Error Helper””E-Document Import Helper”
ALCopy
procedure Create(EDocumentService: Record “E-Document Service”; var EDocument: Record “E-Document”; var SourceDocumentHeader: RecordRef; var SourceDocumentLines: RecordRef; var TempBlob: Codeunit “Temp Blob”)
var
EDocumentHelper: Codeunit “E-Document Helper”;
OutStr: OutStream;
begin
TempBlob.CreateOutStream(OutStr);
case EDocument.”Document Type” of
EDocument.”Document Type”::”Sales Invoice”:
if not GenerateInvoiceXMLFile(SourceDocumentHeader, OutStr) then
EDocumeneHelper.LogSimpleErrorMessage(EDocument, 'Error <> happened while creating this document');
EDocument.”Document Type”::”Sales Credit Memo”:
if not GenerateCrMemoXMLFile(SourceDocumentHeader, OutStr) then
EDocumeneHelper.LogSimpleErrorMessage(EDocument, 'Error <> happened while creating this document');
end;
end;
Missing a feature?
If you think there are any essential features that could enhance the ease of developing an e-document solution, let us know by generating an issue in this repository titled “E-document: < details >” or start the article on aka.ms/BCYammer, and we'll get back to you.
Extending error messages with recommendations
Improving error handling and error messages reduces friction for users and highly impacts the user experience. Being able to resolve an error message by following a clear, informative error message helps users understand what went wrong and how to correct it, which reduces frustration, and improves user satisfaction.
In Business Central, the user can use the actionable error messages displayed on the Error Messages page to resolve issues and continue working. The Error Messages page serves as a centralized location for all error notifications, making it easier to manage and resolve multiple issues efficiently.
This article shows how to raise actionable error messages from the ErrorMessageManagement codeunit using the Error Messages with Recommendations app.
Technical implementation details
In the following sections, you find more details on how the Error messages with recommendations extension can be used to raise actionable errors.
Base Application
Codeunit ErrorMessageManagement
In the Base Application you can find the ErrorMessageManagement codeunit. This codeunit can be used to add sub-contextual information and the implementation for the error message action to the last-logged error message, which triggers the OnAddSubContextToLastErrorMessage event.
In the Base Application on the ErrorMessageManagement codeunit, you find the AddSubContextToLastErrorMessage procedure.
ALCopy
procedure AddSubContextToLastErrorMessage(Tag: Text; VariantRec: Variant)
This procedure is used in the DimensionManagement codeunit to log SameCodeWrongDimErr and NoCodeFilledDimErr by passing the sub-contextual information. Dimension Set Entry is the sub-contextual information for these error messages.
Use Tag to identify the error message in the subscriber. VariantRec can be used to pass the sub-contextual information. TempErrorMessage is the error message record under consideration.
Error messages with recommendations
Codeunit (ID 7900) ErrorMessagesActionHandler
This codeunit handles the drill-down operation and the Accept recommended action on the Error Messages page.
It handles drill-down to the recommended action of an error message to run it with a confirmation dialog box. When the user confirms the action, the error message fix implementation is run for the selected error message:
ALCopy
procedure OnActionDrillDown(var ErrorMessage: Record “Error Message”)
It executes recommended actions for all the selected error messages on the page. Selected error messages are passed from the page and all the error message fix implementations are executed for the selected error messages. The procedure doesn't stop if there's an error in applying fix. Instead, it updates the error message status and continues to apply remaining recommendations for the remaining error messages:
ALCopy
procedure ExecuteActions(var ErrorMessages: Record “Error Message” temporary)
Codeunit (ID 7901) “Execute Error Action”
This codeunit is internally used to execute the error message fix implementation with ErrorBehavior::Collect. This allows us to continue applying recommendations for all the selected error messages even if there is an error.
Note
Commits are ignored inside the implementation of ErrorMessageFix interface.
The ErrorMessageFix interface
Implement the ErrorMessageFix interface and extend the “Error Msg. Fix Implementation” enum.
Implement the ErrorMessageFix interface
Begin by creating a codeunit that implements the ErrorMessageFix interface. This interface defines the methods required to provide a fix for specific errors. By implementing this interface, you can define the logic needed to resolve the errors programmatically.Extend the enum (ID 7901) “Error Msg. Fix Implementation”
Extend the enum (ID 7901) named “Error Msg. Fix Implementation” to include the implemented codeunit. This enum is used to map specific error messages to their corresponding fix implementations.
Example usage to fix an error raised from the Base Application
The ErrorMessagesWithRecommendations extension is available in the ALAppExtensions open source repo. Here you can see an example of how the error messages with recommendations framework is implemented and how error messages raised from the Base Application are fixed. The next sections explain the details of the implementation.
Codeunit (ID 7903) “Dimension Code Same Error” and codeunit (ID 7904) “Dimension Code Must Be Blank”
Subscribes to the event OnAddSubContextToLastErrorMessage and updates the error message record based on the Tag. Sets the TempErrorMessage.”Error Msg. Fix Implementation” to use the enum value from enum (ID 7901) “Error Msg. Fix Implementation”, which has the implementation for the error message action.