Category Archives: D365 Business Central
Designing a Controlled Purchase Approval Workflow in Microsoft Dynamics 365 Business Central
In a recent implementation, we were asked to redesign the purchase process for a client who needed tighter financial control. The requirement was not just about adding approvals. It was about enforcing structure, visibility, and responsibility at every stage of the purchase lifecycle. The client wanted: To achieve this, we implemented a structured workflow in Microsoft Dynamics 365 Business Central, supported by document stage flags and user-based permission control. The Core Challenge Standard approval workflows can handle basic approval logic. However, they do not always provide: We needed a solution that was both technically controlled and functionally transparent. Our Approach We structured the solution around three pillars: 1. Multi-Level Purchase Order Workflow We divided the Purchase Order process into distinct stages: Each stage had a different approver and responsibility. Roles configured: This ensured segregation of duties throughout the process. 2. Stage Identification Using Flags One important improvement we implemented was the use of stage flags on the document. We introduced boolean fields such as: These flags helped us clearly identify: Instead of relying only on the document Status (Open, Released, Pending Approval), we created logical control using these flags. Why was this important? Because standard document status alone cannot differentiate between: By using flags, we achieved: The system logic checked these flags before allowing the Post action. If the required flags were not set, posting was blocked. 3. Restricting Approval Actions via User Setup Another major requirement was controlling who can: To implement this, we extended the User Setup configuration. We added permission indicators such as: In our page action logic, we validated User Setup before enabling the action. If the logged-in user did not have the required permission flag, the action was either: This ensured that only authorized users could trigger workflow transitions. For example: This removed ambiguity and prevented unauthorized workflow manipulation. Handling Rejections and Cancellations We carefully handled rejection scenarios. When a request was: We did not reset the document to Open status. Instead: This design prevented document inconsistency and ensured clean reprocessing. Direct Purchase Invoice Workflow For direct Purchase Invoices (without PO), we implemented the same structure: This ensured that direct invoices did not bypass financial control. How This Resolved the Clientās Concerns Before implementation, the client faced: After implementing: The system now enforces: Most importantly, the solution aligned system behavior with real business hierarchy. Key Takeaways A strong approval workflow is not just about enabling the Approval feature in Business Central. It requires: By combining workflow configuration, document flags, and user-based permission validation, we created a robust and audit-ready purchase control mechanism. Final Thoughts When designing approval workflows, always think beyond basic approval entries. Consider: A well-designed workflow does not slow down operations. It protects them. If you are working on a similar purchase control requirement in Business Central, implementing stage flags along with User Setup-based access control can significantly strengthen your solution. I hope you found this blog useful, and if you would like to discuss anything, you can reach out to us at transform@cloudfronts.com.
Share Story :
If Business Central Has a Project Module, Why Do Companies Still Use Project Operations?
Summary Many project-based organizations evaluating Microsoft solutions often ask the same question: If Microsoft Dynamics 365 Business Central already includes a project module, why do companies also use Microsoft Dynamics 365 Project Operations? This article explains the difference between the two systems, why both exist in the Microsoft ecosystem, and how integrating Project Operations with Business Central helps organizations manage project delivery and financial performance more effectively. Table of Contents 1. Why This Question Comes Up 2. Business Central: Built for Project Accounting 3. Project Operations: Built for Project Delivery 4. Why Companies Use Both 5. The Value of Integration The Outcome Why This Question Comes Up Many organizations assume Microsoft Dynamics 365 Business Central can manage all aspects of project operations because it includes the Jobs module. The Jobs module supports project budgeting, costing, and invoicing, which works well for organizations focused mainly on financial tracking. However, as projects grow more complex, involving multiple resources, time tracking, delivery planning, and client reporting, companies begin to experience limitations. This is when the difference between project accounting and project delivery becomes important. One system manages project finances. The other manages how projects are executed. Business Central: Built for Project Accounting Microsoft Dynamics 365 Business Central is an ERP system designed primarily for financial management. Its Jobs module helps finance teams track the financial performance of projects. Using Business Central, organizations can: Track project budgets and costs Manage purchase orders and project expenses Generate project invoices Monitor project profitability Handle revenue recognition and financial reporting For finance teams, this provides strong control over costs, billing, and compliance. However, financial visibility alone does not guarantee successful project delivery. Project Operations: Built for Project Delivery Microsoft Dynamics 365 Project Operations focuses on how projects are planned and executed. It provides tools specifically designed for project managers and delivery teams. Project Operations enables organizations to: Plan projects and manage tasks Schedule resources and manage capacity Track time and expenses Monitor project progress Collaborate across teams These capabilities help project managers manage people, timelines, and delivery commitments. However, Project Operations is not designed to replace an ERP system for financial management. Why Companies Use Both In most project-based organizations, different teams depend on different systems. Team Focus System Project Managers Planning and project delivery Project Operations Finance Teams Cost control, billing, accounting Business Central Trying to manage everything in a single system often creates operational friction. Project teams struggle with financial processes, while finance teams lack visibility into project execution. The Value of Integration When Microsoft Dynamics 365 Project Operations integrates with Microsoft Dynamics 365 Business Central, organizations gain the best of both systems. A typical workflow looks like this: Opportunities and project quotes are created Projects are planned and executed in Project Operations Time, expenses, and resource usage are captured Billing data flows to Business Central Finance manages invoicing and accounting This integration connects project execution with financial performance. Project managers gain operational visibility, while finance teams maintain control over billing and reporting. The Outcome Projects are delivered more efficiently Financial reporting remains accurate and compliant Manual work and duplicate data entry are reduced Project managers and finance teams work from connected data This creates a unified platform where project delivery and financial performance remain aligned. Final Thought The question is not whether Business Central can manage projects ā it can. The real question is whether one system should manage both delivery and financial operations. For many organizations, combining Microsoft Dynamics 365 Project Operations with Microsoft Dynamics 365 Business Central provides the ideal balance between operational execution and financial governance. At CloudFronts Technologies, we help organizations connect Project Operations with Business Central through our PO-BC integration solution. For more information: PO-BC Integration Solution on Microsoft AppSource If you would like to discuss how this integration can support your organization, feel free to reach out to us at transform@cloudfronts.com.
Share Story :
How Pharmaceutical Companies Can Move ERPs to the Cloud – Without Risk
Summary ERP migration in the pharmaceutical industry is not just a technology upgrade – it is a compliance and quality decision. For highly regulated manufacturers, cloud migration must ensure that regulatory processes, audit trails, and product quality controls remain intact. This article explains why pharmaceutical ERP migrations feel risky, how modern cloud platforms such as Microsoft Dynamics 365 Business Central can strengthen compliance controls, and how a compliance-first migration approach helps pharmaceutical organizations modernize safely. Table of Contents 1. ERP Migration in Pharma Is a Strategic Decision 2. Why Cloud Migrations Feel Risky in Pharma 3. Cloud Does Not Mean Less Control 4. How CloudFronts Approaches Pharma ERP Migration 5. Real-World Example The Outcome ERP Migration in Pharma Is a Strategic Decision In pharmaceuticals, ERP migration is never just an IT upgrade. It is a compliance decision, a quality decision, and often a decision that senior leadership and QA teams will remain accountable for long after the system goes live. When pharmaceutical organizations evaluate cloud ERP adoption, the biggest concern is rarely performance or cost. The real question is: āHow do we move to the cloud without putting compliance, audits, or product quality at risk?ā The answer lies in one core principle: Compliance-First Migration. Why Cloud Migrations Feel Risky in Pharma Pharmaceutical ERP systems support highly regulated manufacturing processes such as: Batch manufacturing Quality control and approvals Quarantine and release processes Expiry and retesting End-to-end product traceability Because of these requirements, a generic ālift-and-shiftā cloud migration approach rarely works in pharmaceutical environments. In pharma operations: A missed QC step is not just a process gap – it becomes a compliance issue. A broken batch trail is not just an inconvenience – it becomes an audit finding. This is why many ERP migrations in the pharmaceutical industry stall or exceed expected timelines. The issue is rarely technology. It is usually the absence of compliance as the foundation of the migration strategy. Cloud Does Not Mean Less Control In pharmaceutical organizations, cloud ERP adoption is sometimes perceived as a loss of control. In reality, modern cloud ERP platforms such as Microsoft Dynamics 365 Business Central can provide stronger compliance capabilities than many legacy on-premise systems when implemented correctly. Cloud ERP systems enable: System-driven audit trails Role-based approvals Enforced quality and release controls End-to-end batch and lot traceability Cloud technology enables compliance – but it does not automatically guarantee it. Compliance ultimately depends on how processes are designed and enforced within the ERP system. Real-World Example One of our customers – an EU-GMP and TGA-approved pharmaceutical company specializing in advanced solutions for pellets, granules, tablets, and capsule manufacturing – modernized its ERP landscape by migrating from Microsoft Dynamics NAV to Microsoft Dynamics 365 Business Central in the cloud. The migration strengthened quality processes, improved operational efficiency, and enhanced regulatory compliance across manufacturing operations. Read the full customer success story here: EU-GMP & TGA Approved Pharmaceutical Company – Dynamics 365 Business Central Case Study The Outcome A compliance-first ERP migration approach builds confidence across the organization. Quality assurance teams trust the system. Operational risks are significantly reduced. Regulatory audits become more predictable and easier to manage. When compliance becomes the foundation of the migration strategy, the cloud stops feeling risky – and starts becoming a reliable platform for growth. Final Thought Pharmaceutical companies do not struggle with cloud ERP migrations because the cloud is unsafe. They struggle when compliance is treated as a phase instead of a foundation. A compliance-first migration does not slow digital transformation – it protects the organization while allowing the cloud to deliver its full value. We hope you found this blog useful. If you would like to discuss ERP modernization for pharmaceutical manufacturing, you can reach out to us at transform@cloudfronts.com.
Share Story :
How to Generate and Use SSL Certificates in Microsoft Dynamics 365 Business Central
Security is a critical aspect of any ERP implementation. When integrating Microsoft Dynamics 365 Business Central with external systems such as APIs, payment gateways, banks, IRIS, VAT systems, or third-party services, SSL/TLS certificates play a key role in securing communication. A common misconception is that Business Central itself generates SSL certificates. In reality, Business Central only consumes certificates-the generation and management are handled externally. In this blog, we will cover: What Is an SSL Certificate in Business Central? An SSL (Secure Sockets Layer) / TLS certificate is used to:\Hook: In Business Central, certificates are commonly used for: Important: Business Central does not create SSL certificatesāit only stores and uses them. Steps to Generate an SSL Certificate (Self-Signed) This approach is typically used for development or on-premises environments. Step 1: Create a SelfāSigned Certificate in IIS Step 2: Provide Certificate Details Step 3: Copy the Certificate Thumbprint This thumbprint will be required in the next step. Step 4: Configure Certificate Using PowerShell Step 5: Verify Required Properties Ensure all required certificate properties are set to True, including: Step 6: Bind the Certificate in IIS Step 7: Add Certificate Using MMC Step 8: Verify Certificate Installation The certificate should now be visible under: Step 9: Grant Permissions to Business Central Service This ensures the Business Central service can access the certificate. To conclude, SSL certificates are a core security component in Business Central integrations. While Business Central does not generate certificates, it provides robust mechanisms to store and consume certificates securely in both cloud and onāprem environments. Understanding the generation, configuration, and usage flow ensures secure, compliant, and reliable integrations. We hope you found this blog useful, and if you would like to discuss anything, you can reach out to us at transform@cloudfronts.com
Share Story :
Finding the Right Events in Business Central: Payment Journals & Purchase Orders
When working with Payment Journals in Microsoft Dynamics 365 Business Central, one of the most common customization requirements is to trigger custom logic immediately after the user selects the Applies-to Doc. No.. In one of my recent client projects, the requirement was very specific: As soon as a payment journal line is applied to an invoice (via Applies-to Doc. No. lookup), the system should automatically calculate amounts and create additional retained lines (VAT and IRIS). Sounds simple, right? The real challenge was finding the correct event that fires after the lookup completes and after Business Central internally updates the journal line fields. This blog documents: Problem Statement The client wanted the following behavior in Payment Journal: The logic must run right after the lookup, not during posting and not on page validation. Why Page Events Were Not Enough Initially, it is natural to look for: However, in this case: So even though the value was visible, the amounts were not reliable yet. Using Event Recorder to Find the Right Event This is where Event Recorder becomes extremely powerful. Steps I Followed The recorder captured a detailed list of: After analyzing the sequence, one event stood out. The Key Event That Solved the Problem The event that fulfilled the exact requirement was: [EventSubscriber( ObjectType::Table, Database::”Gen. Journal Line”, ‘OnLookupAppliestoDocNoOnAfterSetJournalLineFieldsFromApplication’, ”, false, false)]local procedure OnAfterLookupAppliesToDocNo(var GenJournalLine: Record “Gen. Journal Line”) Why This Event Is Perfect This is exactly the moment where custom business logic should run. Implementing the Business Logic Below is the simplified version of the logic implemented inside the subscriber: local procedure OnAfterLookupAppliesToDocNo(var GenJournalLine: Record “Gen. Journal Line”)begin GenJournalLine.GetUpdatedAmount(); if GenJournalLine.”Applies-to Doc. No.” <> ” then begin GenJournalLine.GetUpdatedAmount_(GenJournalLine); AppliestoDocNo := GenJournalLine.”Applies-to Doc. No.”; GenJournalLine.CreateRetainedVATLine(GenJournalLine, AppliestoDocNo); GenJournalLine.CreateRetainedIRISLine(GenJournalLine, AppliestoDocNo); end;end; What This Code Does All of this happens immediately after the lookup, without waiting for posting. Important Design Notes Key Takeaway Finding the right event is often harder than writing the logic itself. In scenarios where: This table event: OnLookupAppliestoDocNoOnAfterSetJournalLineFieldsFromApplication is a hidden gem for Payment Journal customizations involving Applies-to logic. Another Real-World Case: Invoice Discount Recalculation on Purchase Orders In the same project, we faced another tricky requirement related to Invoice Discounts on Purchase Orders. The Problem did not fire reliably when invoice discounts were recalculated by the system This became an issue because the client wanted custom tax and withholding logic (IR, IS, Withheld VAT, Excise) to be recalculated immediately after invoice discount recalculation. Why Page and Line Events Failed Again Business Central recalculates invoice discounts using an internal codeunit: Purch – Calc Disc. By Type This logic: So once again, page-level and line-level events were too early or never triggered. Finding the Right Event (Again) Using Event Recorder Using Event Recorder, I traced the execution when: This led to the discovery of another perfectly-timed system event. The Key Event for Invoice Discount Scenarios [EventSubscriber( ObjectType::Codeunit, Codeunit::”Purch – Calc Disc. By Type”, ‘OnAfterResetRecalculateInvoiceDisc’, ”, false, false)]local procedure OnAfterResetRecalculateInvoiceDisc(var PurchaseHeader: Record “Purchase Header”) Why This Event Works Applying Custom Logic on Purchase Lines local procedure OnAfterResetRecalculateInvoiceDisc(var PurchaseHeader: Record “Purchase Header”)var PurchLine: Record “Purchase Line”;begin PurchLine.SetRange(“Document Type”, PurchaseHeader.”Document Type”); PurchLine.SetRange(“Document No.”, PurchaseHeader.”No.”); if PurchLine.FindSet() then repeat PurchLine.UpdateIRandIS(); PurchLine.CalculateWithHeldVAT(); PurchLine.CalculateIR(); PurchLine.CalculateIS(); PurchLine.CalculateExcise(); PurchLine.Modify(); until PurchLine.Next() = 0;end; What Happens Here All of this happens automatically, without relying on UI triggers. Key Lessons from Both Scenarios Final Thoughts Both of these scenarios reinforce one important principle in Business Central development: Finding the right event matters more than writing the logic itself. Whether it is: The solution lies in understanding where Business Central actually performs the work – and subscribing after that point. We hope you found this blog useful, and if you would like to discuss anything, you can reach out to us at transform@cloudfronts.com
Share Story :
SMTP with OAuth 2.0 in Business Central: A Modern Email Setup
Email remains one of the most critical communication tools in Business Central. Whether youāre sending invoices, notifications, or workflow approvals, the reliability and security of your email integration matter. With Microsoft officially retiring Basic Authentication in Exchange Online, Business Central users must now embrace OAuth 2.0 for SMTP connections. Letās explore what this means and how to configure it. Why the Shift to OAuth 2.0? Setting Up SMTP with OAuth 2.0 in Business Central The process is simpler than many expect. Hereās the streamlined approach: To conclude, switching to SMTP with OAuth 2.0 in Business Central is not just a technical requirement itās a strategic move toward secure, modern communication. The setup is straightforward, but the payoff is significant: stronger security, smoother compliance, and reliable email delivery.
Share Story :
Filtering data in Business Central API
Business Central is its ability to integrate with other systems through APIs, allowing developers to retrieve and manipulate data programmatically. However, when dealing with large datasets or complex queries, retrieving only the relevant information efficiently becomes crucial. This is where API filtering comes in, and source table views can play a vital role in optimizing these operations. In this blog, we’ll explore how to implement API filtering using source table views within Microsoft Dynamics 365 Business Central. We’ll cover the benefits, best practices, and a step-by-step guide to making the most out of your API integrations. We’ll take one example, instead of fetching all sales orders, you might want to retrieve only those created within the last month or orders from a specific customer. Business Central APIs allow you to apply filters using OData queries, but in more complex scenarios, leveraging source table views can simplify the process and improve performance. What Are Source Table Views in Business Central? In Business Central, source table views are virtual tables created from SQL queries that extract and present data from one or more underlying tables. Views allow you to define complex data relationships and filters at the database level, which can then be consumed by your APIs. Advantage using Source Table View First, we have to create custom API using AL in Visual Studio Code Steps to achieve the goal: Using SourceTableView helps you to filter the data in your API itself without using filter work in your postman. Create an API page and added Source table View property where I have added filters only Sales order and Approved Orders data should be shown whenever this API is used. To conclude, API filtering using source table views in Business Central is a powerful way to optimize data retrieval and improve the performance of your integrations. By centralizing your filtering logic within the database, you can reduce the complexity of your APIs, improve security, and ensure consistent data access across your applications. We hope you found this blog useful, and if you would like to discuss anything, you can reach out to us at transform@cloudfronts.com
Share Story :
Monitoring Job Queues: Setting Up Failure Notifications using Power Automate
A job queue lets users set up and manage background tasks that run automatically. These tasks can be scheduled to run on a recurring schedule. For a long time, users had a common problem in Business Central when a job queue failed, there was no alert or warning. Youād only notice something was wrong when a regular task didnāt run for a few days. Some people tried to fix this by setting up another job queue to watch and restart failed ones.But that didnāt always work, especially if an update happened at the same time. Now, Microsoft has finally added a built-in way to get alerts when a job queue fails. You can get notified either inside Business Central or by using Business Events. In this blog, we’ll see the process of leveraging the Business Events to set up notifications on job queue statuses. Configuration Search for “Assisted Setup” in Business Central’s global search. Scroll down till “Set up Job Queue notifications”. Click on Next. Add the additional users who need to be notified when the job queue fails along with the job creator (if required). Choose whether you want the notification to be in-product or using Business Events (and Power Automate). I’m choosing Business Events this time and then Next. Click on Finish. Then search for Job Queue Entries and from that list page open the Job Queue Entry card. If you are using Power Automate for the first time, then it will ask you for your consent. As an Administrator, if you want to give the consent for all of the Users at once or revoke the consent for all the Users then you can do so via the Privacy Notice statuses page. Then, go back to the Job Queue Entry card and click on Power Automate again.This time, you’ll get the option to create an automated flow. In the pop up screen, you’ll get the template for a job queue entry failure notification flow. Once you click on it, it’ll ask you to sign into Business Central as well as the outlook account that’ll be used to send the emails (if different from the current user). In the next screen, you can add additional users that need to be copied on the notifications. Click on “Create Flow” and you are done! Ideally, the setup should have worked at this pointābut it didnāt. After some digging, I found out that the Power Automate flow was missing some key pieces. One of the actions didnāt have the environment configured, and another action (GetUrlV3) isnāt even available in the current (v25) version of Business Central. I came across two forum thread (1) (2) about this issue, but they had no clear solution. So, as a workaround, I created a Web Service based on the Job Queue Entries Log page and used the GetRecord action in Power Automate to fetch the required data. It wasnāt too hard for me since I knew what to look for; but for a new user, this wouldāve been very confusing. Also, I noticed something odd: the action that picks the email address of the person to notify was pulling it from the Contact Email field on the User Card, instead of using User Setup, which wouldāve made more sense. Anyway, after all that, hereās what the final solution looks like! To conclude, setting up job queue failure alerts with Business Events is a helpful new feature in Business Central. It lets you know when background tasks fail, so you donāt have to keep checking them manually. But as we saw, the setup doesnāt always work perfectly. Some parts were missing, and a few things didnāt make sense like where it pulls the email from. If you’re familiar with Power Automate, you can fix these issues with a few extra steps. For someone new, though, it might be a bit confusing. Hopefully, Microsoft will improve the setup in future updates. Until then, this blog should help you get the alerts working without too much trouble. If you need further assistance or have specific questions about your ERP setup, feel free to reach out for personalized guidance. We hope you found this blog useful, and if you would like to discuss anything, you can reach out to us at transform@cloudfonts.com.
Share Story :
Bank & Payment Reconciliation in Microsoft Dynamics 365 Business Central
In any organization, reconciling bank and payment data is critical to maintaining accurate financial records and cash visibility. Microsoft Dynamics 365 Business Central offers robust tools for Bank Reconciliation and Payment Reconciliation Journals, helping businesses match bank statements with ledger entries, identify discrepancies, and streamline financial audits. In this article, I outline how I learned to perform these reconciliations efficiently using Business Central. Bank Reconciliation ensures that transactions recorded in the bank ledger match those on the actual bank statement. Steps: Benefits: Reconciled statements are stored and can be printed or exported for documentation. Set Up Payment Reconciliation Journals The Payment Reconciliation Journal is used to match customer/vendor payments against open invoices or entries. It supports automatic suggestions and match rules for fast processing. Configuration Steps: Setup ensures the journal is ready to load incoming payments and suggest matches automatically. Use the Payment Reconciliation Journal Once the setup is done, you can use the journal to reconcile incoming payments against customer/vendor invoices. Daily Workflow: Features: Business Value Feature Value Speed Auto-matching reduces reconciliation time Accuracy Eliminates manual errors and duplicate entries Audit Ready Clear audit trail for external and internal auditors Cash Flow Clarity Real-time visibility into paid/unpaid invoices We hope you found this blog useful, and if you would like to discuss anything, you can reach out to us at transform@cloudfronts.com
Share Story :
Automating Prepayment Handling in Business Central ā Part 2
In Part 1, we explored the core logic of handling prepayment invoices in Business Central using AL. In this part, we will dive deeper into the practical implementation, focusing on how prepayments are applied, invoices are generated, and item charges are assigned. This blog will break down the logic in a simplified, yet complete way. Why Automate Prepayments? In real-world business scenarios, companies often pay vendors before the invoice is fully posted. Handling these prepayments manually is tedious and error-prone: Our AL code automates this process: it creates purchase invoices, handles prepayment lines, applies payments, and ensures that item charges are correctly assigned. 1. Event Subscriber: Trigger After Posting Purchase Document The automation starts with an event subscriber that triggers after a purchase document is posted: [EventSubscriber(ObjectType::Codeunit, Codeunit::”Purch.-Post”, ‘OnAfterPostPurchaseDoc’, ”, false, false)]procedure OnAfterPostPurchaseDocHandler(var PurchaseHeader: Record “Purchase Header”)var Rec_PreppaymentLines: Record PrepaymentLinesandPayment; PurchInvoiceHeader: Record “Purchase Header”; VendorInvoiceMap: Dictionary of [Code[20], Code[20]]; VendorNo: Code[20];begin // Collect unique vendors Rec_PreppaymentLines.SetRange(“Purchase Order No.”, PurchaseHeader.”No.”); Clear(VendorList); if Rec_PreppaymentLines.FindSet() then repeat if not VendorList.Contains(Rec_PreppaymentLines.”Vendor No.”) then VendorList.Add(Rec_PreppaymentLines.”Vendor No.”); until Rec_PreppaymentLines.Next() = 0; // Process each vendor foreach VendorNo in VendorList do begin // Create or reuse invoice if VendorInvoiceMap.ContainsKey(VendorNo) then PurchInvoiceHeader.Get(PurchInvoiceHeader.”Document Type”::Invoice, VendorInvoiceMap.Get(VendorNo)) else begin PurchInvoiceHeader := CreatePurchaseInvoiceHeader(VendorNo); VendorInvoiceMap.Add(VendorNo, PurchInvoiceHeader.”No.”); end; // Handle prepayment lines Rec_PreppaymentLines.SetRange(“Purchase Order No.”, PurchaseHeader.”No.”); Rec_PreppaymentLines.SetRange(“Vendor No.”, VendorNo); if Rec_PreppaymentLines.FindSet() then repeat HandlePrepaymentLine(Rec_PreppaymentLines, PurchInvoiceHeader); until Rec_PreppaymentLines.Next() = 0; end;end; Key Takeaways: 2. Handling Prepayment Lines The HandlePrepaymentLine procedure ensures each prepayment is processed correctly: procedure HandlePrepaymentLine(var PrepaymentLine: Record PrepaymentLinesandPayment; var PurchHeader: Record “Purchase Header”)var PaymentEntryNo: Integer;begin // Unapply previous payments if any PaymentEntryNo := UnapplyPaymentFromPrepayInvoice(PrepaymentLine.”Prepayment Invoice”); if PaymentEntryNo = 0 then Error(‘Failed to unapply Vendor Ledger Entry for Document No. %1’, PrepaymentLine.”Prepayment Invoice”); // Create credit memo and invoice line CreateCreditMemoLine(PrepaymentLine, PrepaymentLine.”Prepayment Invoice”); CreatePurchaseInvoiceLine(PurchHeader, PrepaymentLine); // Assign item charges and post AssignItemChargeToReceiptAndPost(PrepaymentLine, PurchHeader.”No.”, PrepaymentLine.”Purchase Order No.”);end; Highlights: 3. Applying Payments to Invoice The ApplyPaymentToInvoice procedure ensures the invoice is linked with the correct prepayment: procedure ApplyPaymentToInvoice(InvoiceNo: Code[20]; PaymentEntryNo: Integer)var InvoiceEntry, VendLedEntry: Record “Vendor Ledger Entry”; ApplyPostedEntries: Codeunit “VendEntry-Apply Posted Entries”; ApplyUnapplyParameters: Record “Apply Unapply Parameters”;begin InvoiceEntry.SetRange(“Document No.”, InvoiceNo); InvoiceEntry.SetRange(Open, true); if InvoiceEntry.FindFirst() then begin VendLedEntry.SetRange(“Entry No.”, PaymentEntryNo); if VendLedEntry.FindFirst() then begin InvoiceEntry.Validate(“Amount to Apply”, InvoiceEntry.”Remaining Amount”); VendLedEntry.Validate(“Amount to Apply”, -InvoiceEntry.”Remaining Amount”); ApplyUnapplyParameters.”Document No.” := VendLedEntry.”Document No.”; ApplyPostedEntries.Apply(InvoiceEntry, ApplyUnapplyParameters); end; end;end; Benefits: 4. Assigning Item Charges Item charges from receipts are automatically assigned to invoices: procedure AssignItemChargeToReceiptAndPost(var PrepaymentLine: Record PrepaymentLinesandPayment; PurchInvoiceNo: Code[20]; PurchaseOrderNo: Code[20])var PurchRcptLine: Record “Purch. Rcpt. Line”; ItemChargeAssign: Record “Item Charge Assignment (Purch)”;begin PurchRcptLine.SetRange(“Order No.”, PrepaymentLine.”Purchase Order No.”); PurchRcptLine.SetFilter(Quantity, ‘>0’); PurchRcptLine.SetRange(“No.”, PrepaymentLine.”Item No.”); if PurchRcptLine.FindSet() then repeat ItemChargeAssign.Init(); ItemChargeAssign.”Document No.” := PurchInvoiceNo; ItemChargeAssign.”Applies-to Doc. No.” := PurchRcptLine.”Document No.”; ItemChargeAssign.”Item Charge No.” := PrepaymentLine.”Item Charge”; ItemChargeAssign.”Qty. to Assign” := 1; ItemChargeAssign.”Amount to Assign” := PrepaymentLine.Amount; ItemChargeAssign.Insert(true); until PurchRcptLine.Next() = 0;end; Outcome: To conclude, by implementing this automation: This code can save significant time for finance teams while keeping processes accurate and transparent. We hope you found this blog useful, and if you would like to discuss anything, you can reach out to us at transform@cloudfronts.com