web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

Community site session details

Community site session details

Session Id :
Business Central forum

Can we create invoice in Dynamics 365/CRM and have replication in Dynamics for Financials automatically ?

(0) ShareShare
ReportReport
Posted on by 141

Hello

Can we create invoice in Dynamics 365/CRM and have replication in Dynamics for Financials automatically ?

thanks. 

I have the same question (0)
  • Suggested answer
    Qaqa Profile Picture
    141 on at

    Hi Decio,

    Here is the code snippet:

    //The InputParameters collection contains all the data passed in the message request.
                   if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is EntityReference)
                   {
                       //Obtain the target entity from the input parameters.
                       EntityReference invoice = (EntityReference)context.InputParameters["Target"];
                       if (invoice.LogicalName == "invoice")
                       {
                           //Call invoice details
                           QueryExpression invoiceDetails = new QueryExpression("invoicedetail");
                           invoiceDetails.ColumnSet.AddColumns("quantity", "invoiceispricelocked", "priceperunit", "productid", "description");
                           invoiceDetails.Criteria.AddCondition("invoiceid", ConditionOperator.Equal, invoice.Id);
                           EntityCollection invoiceLines = service.RetrieveMultiple(invoiceDetails);
                           //EntityReference prodRef = (EntityReference)item.Attributes["productid"];
                           //productName = service.Retrieve("product", prodRef.Id, new Microsoft.Xrm.Sdk.Query.ColumnSet("name"));
                           //Check if invoice has lines else throw error
                           if (invoiceLines.Entities.Count > 0)
                           {
                               //send for invoice creation
                               ohc.invsol.invGenD365F ig = new ohc.invsol.invGenD365F();
                               bool result = ig.sendInvoiceInFinancials(invoice, invoiceLines, service);
                               if (result == true)
                               {
                                   try
                                   {
                                       //Get inovice entity
                                       Entity invToDelete = service.Retrieve(invoice.LogicalName, invoice.Id, new ColumnSet("invoicenumber"));
                                       service.Delete(invoice.LogicalName, invToDelete.Id);
                                   }
                                   catch (Exception ex)
                                   {
                                       throw new InvalidPluginExecutionException
                                       (
                                           @"Result: Success\n
                                           1. Invoice sent to Dynamics 365 for Financials.\n
                                           2. Org. Dynammics 365 Invoice record Not Deleted. \n" + ex.Message //+ ex.Message + productName.Attributes["name"].ToString()
                                       );
                                   }
                               }
                               throw new InvalidPluginExecutionException
                               (
                                   @"Result: Success\n
                                   1. Invoice sent to DYNAMICS 365 FOR FINANCIALS.
                                   2. Org. Dynammics 365 Invoice record Deleted." //+ productName.Attributes["name"].ToString()
                               );
                           }
                           else
                           {
                               throw new InvalidPluginExecutionException
                               (
                                   @"Oh snap!\n
                                   1. There are no invoice lines to send in Dynamics 365 Financials."
                               );
                           }
                       }
                   }

    Then for Dynamics 365 for Financials use the following:

    //Call web service for financials
               NAV dynamicsFinancials = new NAV(new Uri("yourfinancialsinstance/.../Company('My%20Company')"));
               dynamicsFinancials.Credentials = new NetworkCredential("APIUsernameYouSetupDuringIntegration", "APIKEYGeneratedByFinancialsXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
    //Create invoice first
               SalesInvoice salesInvoice = new SalesInvoice();
               salesInvoice.Document_Type = "Invoice";
               salesInvoice.Sell_to_Customer_Name = ""; //Coupled in both systems            
               salesInvoice.No = ""; //Must use these ""
               dynamicsFinancials.AddObject("SalesInvoice", salesInvoice);
    //Get response
               var invoiceNo = string.Empty;
               try
               {
                   var result = dynamicsFinancials.SaveChanges();
                   //Evaluate invoice lines
                   if (result != null)
                   {
                       foreach (var response in result)
                       {
                           var invoiceItem = response.Headers.Values.Where(x => x.Contains("No=")).FirstOrDefault();
                           if (invoiceItem != null)
                           {
                               try
                               {
                                   //Get invoice number
                                   Regex regex = new Regex("No='(.*)'");
                                   var v = regex.Match(invoiceItem);
                                   invoiceNo = v.Groups[1].ToString();
                                   Entity productName = null;
                                   //Get lines
                                   foreach (Entity line in invoiceLinesCollection.Entities)
                                   {
                                       //Get product desc
                                       EntityReference prodRef = (EntityReference)line.Attributes["productid"];
                                       productName = service.Retrieve("product", prodRef.Id, new Microsoft.Xrm.Sdk.Query.ColumnSet("name"));
                                       //Price per unit
                                       //decimal unit_price = Convert.ToDecimal(line.Attributes["priceperunit"]);
                                       //Quantity
                                       //decimal Quantity = Convert.ToDecimal(line.Attributes["quantity"]);
                                       //Add each invoice line
                                       SalesInvoiceSalesLines invoiceLines = new SalesInvoiceSalesLines()
                                       {
                                           Type = "item",
                                           Unit_Price = 30,
                                           Quantity = 1,
                                           Document_No = invoiceNo,
                                           Document_Type = "Invoice",
                                           Description = "Product name exactly same (coupled between CRM/Financials)"
                                       };
                                       dynamicsFinancials.AddObject("SalesInvoiceSalesLines", invoiceLines);
                                   }
                                   dynamicsFinancials.SaveChanges();
                               }
                               catch (Exception ex)
                               {
                                   throw new InvalidPluginExecutionException
                                  (
                                      @"<img height='16px' src='emojione.com/.../1f644.svg&;> <strong>Oh snap!</strong>
                                      Failed: invoice posted to Dynamics 365 Financials -----------> " + ex.InnerException.Message
                                  );
                               }
                           }
                       }
                   }
               }
               catch (Exception ex)
               {
                   throw new InvalidPluginExecutionException
                   (
                       @"<img height='16px' src='emojione.com/.../1f644.svg&;> <strong>Oh snap!</strong>
                       Failed: invoice posted to Dynamics 365 Financials -----------> " + ex.InnerException.Message
                   );
               }


    regards,

    Qaqa

  • Community Member Profile Picture
    on at

    Hi Qaqa

    If you could paste code that would be greatly appreciated

    Thank you

    Decio

  • Qaqa Profile Picture
    141 on at

    Hi Deciofigueira's,

    We had requirement to create invoices in Dynamics 365 for sales and send in Financials. 

    As you are probably aware that OOB integration options do not offer above. 

    After initial setup (i.e. currency, products etc) Dynamics 365 for financial's price list governs prices and products/items in Dynamics 365 for Sales.

    So I wrote a plugin that is based on Invoice and Invoice Lines Entity. 

    I added a custom button in invoice section> which triggers custom action > which invokes plugin. 

    For each/individual invoice plugin calls invoice header and collates lines (items) with appropriate prices, discount etc. 

    I included Dynamics 365 for Financials webservice in my solution which created NAV classes/functions, and using that I am posting invoices into Financials. The calculation of figures etc is also fine. 

    Note: that I delete original invoice created in Dynamics 365 for Sales as that's just used as a shell to gather invoice data and send to Financials. Once generated invoice is Posted in Financials it sends/creates a copy of the invoice in Dynamics 365 for Sales (is what you want to keep/maintain). 

    Let me know if you want me paste code snippet here. 

  • Community Member Profile Picture
    on at

    Hi Qaqa

    I was researching for a solution to a problem similar to yours and was wondering if your custom plugin resolved your problem, and if it records correctly VAT. i.e. when you sync invoices from CRM does it do it at item level or just the total amounts?

    Decio

  • Verified answer
    Qaqa Profile Picture
    141 on at

    Thanks Ivan.

    I wrote a custom plugin, which works with the invoice header/lines created in D365 for Sales and then using web service send invoice creation request in Dynamics 365 for Financials.  

  • Suggested answer
    ikoletic Profile Picture
    2,202 on at

    Hi Qaqa

    As Chris says there's no build in sync. First I'd like to understand the business scenario on why you'd like to replicate invoices created in D365/CRM to Financials as you won't be able to get accounting/tax part behind the invoices in D365/CRM. Financials is natural place for invoices to be created and synched from as we do it, as it provides you whole accounting/tax/audit details needed for them. 

    If there really is a need to do this, I'd suggest doing a customization on Financials where you'd create an external table (TableType=CRM) that would give you a view of the invoices in CRM. 

    If you're trying to import opening balances for customers from CRM system I'd suggest to use Prepare Journal action on General Journal in Financials to bring in open balances of customers from CRM or some other software. 

    As last thing, as this is a feature suggestion you can also post this on https://ideas.dynamics.com

    Regards

    Ivan

  • Qaqa Profile Picture
    141 on at

    Hi Chris,

    Thanks for your answer.

    I think we probably looking at a bespoke solution for this.

    Could you please advise if its possible to couple two records in D365 for Sales and D365 for Financials? i.e. through ODATA or SOAP web service etc?

    Thanks.

  • Chris Bulson Profile Picture
    on at

    Hello,

    Not with the built-in sync.

    Sales Order

    From CRM to Financials; orders may originate in CRM. These are written across to Financials.

    Posted Sales Invoice

    From Financials to CRM; orders that originated in CRM may be invoiced and posted in Financials. That will update the order status in CRM as well as send the historical (posted) invoice across from Financials to CRM.

    Take a look at the following for more info:

    blogs.msdn.microsoft.com/.../dynamics-365-crm-initial-setup-and-synchronization-with-dynamics-365-for-financials

    Thanks,

    Chris

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

News and Announcements

Season of Giving Solutions is Here!

Quick Links

November Spotlight Star - Khushbu Rajvi

Congratulations to a top community star!

Forum Structure Changes Coming on 11/8!

In our never-ending quest to help the Dynamics 365 Community members get answers faster …

Dynamics 365 Community Platform update – Oct 28

Welcome to the next edition of the Community Platform Update. This is a status …

Leaderboard > Business Central

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans