<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rimond on Medium]]></title>
        <description><![CDATA[Stories by Rimond on Medium]]></description>
        <link>https://medium.com/@rimond436?source=rss-8575d20eea92------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*wBWceRKWbFyI3q8Q</url>
            <title>Stories by Rimond on Medium</title>
            <link>https://medium.com/@rimond436?source=rss-8575d20eea92------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 00:03:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rimond436/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[SAP ABAP: Building a Custom Rebate Engine in SAP SD Using VOFM Pricing Routine]]></title>
            <link>https://medium.com/sap-innovation-hub/sap-abap-building-a-custom-rebate-engine-in-sap-sd-using-vofm-pricing-routine-984c17a9f47e?source=rss-8575d20eea92------2</link>
            <guid isPermaLink="false">https://medium.com/p/984c17a9f47e</guid>
            <category><![CDATA[sap-abap]]></category>
            <category><![CDATA[pricing-routine]]></category>
            <category><![CDATA[abap]]></category>
            <category><![CDATA[vofm]]></category>
            <category><![CDATA[sap-sd]]></category>
            <dc:creator><![CDATA[Rimond]]></dc:creator>
            <pubDate>Sun, 21 Jun 2026 09:30:14 GMT</pubDate>
            <atom:updated>2026-07-08T06:55:49.197Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>How I created a <strong>header-level discount </strong>engine from scratch for a pharmaceutical client, including a Z table, a <strong>VOFM procedure</strong>, a billing workaround, and a clean return flow.</blockquote><h3>The Problem I Was Solving</h3><p>A pharmaceutical distributor in Bangladesh wants to reward their loyal customers. The criterion is straightforward: a customer will automatically receive a discount on their subsequent order if they spent BDT 15,000 or more last month. No discounts. No manual involvement. It just occurs.</p><p>Basic rule, intricate execution.</p><p>Because when you attempt to wire this into SAP SD properly, you encounter a series of actual decisions:</p><ol><li>Where is the discount kept?</li><li>When is the calculation done?</li><li>At what point does the order amount hit the discount?</li><li>Is it at the item level or the header level?</li><li>What takes place throughout the billing process?</li><li>What about returning the product?</li><li>so on….</li></ol><p>This post tells the whole tale of how I solved it, including every step and trick, and is written in a way that even a novice can follow.</p><p><strong>Phase 1 — The Z table; Vault of Discounts</strong></p><p>Think of the custom Z table I made as a little, private database table inside SAP that is solely related to my project. It stores one record per eligible customer and looks something like this:</p><figure><img alt="A database table to store discount amounts for each customer." src="https://cdn-images-1.medium.com/max/547/1*zhf267KipwXbGwHsi_Fr0g.png" /><figcaption><strong>Where Does the Discount Live?</strong></figcaption></figure><p>A driver program operates as a <strong>scheduled</strong> batch operation each night. It goes through each customer’s past month’s purchase history, determines which ones <strong>exceeded BDT 15,000</strong>, computes the discount they received, and enters that information into the Z database.</p><p><strong>The Nightly Batch Job</strong></p><pre>## SNIPPET OF A CODE<br><br>LOOP AT lt_raw_items INTO ls_raw_item.<br>  CLEAR ls_item.<br>  MOVE-CORRESPONDING ls_raw_item TO ls_item.<br><br>  READ TABLE lt_cust_totals INTO ls_cust_total<br>    WITH KEY customer = ls_raw_item-customer<br>             mmonth   = ls_raw_item-mmonth<br>             yyear    = ls_raw_item-yyear.<br><br>  IF sy-subrc = 0 AND ls_cust_total-invoice_value &gt;= 15000.<br>      ls_item-rebate =  round( val = ls_item-invoice_value * &#39;0.02&#39; dec = 0 ) .<br>  ELSE.<br>    ls_item-rebate = 0.<br>  ENDIF.<br><br>  APPEND ls_item TO lt_items.<br>ENDLOOP.<br><br>##SNIPPET OF A CODE</pre><p>This design’s crisp distinction is what makes it so beautiful. The question “Is this customer eligible and by how much?” is handled by the batch job. The “show it on the order” pricing process handles the query. They never complete each other’s tasks.</p><p><strong>Phase 2 — “How Does the Discount Appear on the Order?”</strong></p><p>Things start to become intriguing at this point. SAP’s pricing engine launches when a user creates a sales order via the <strong>cockpit (or VA01)</strong> and assesses each condition type in your pricing process, top to bottom. It calls your <strong><em>VOFM</em></strong> procedure when it reaches the ZREB line.<br>Let’s start from scratch with this setup.</p><blockquote><strong>Step 1: Create the VOFM Routine 700</strong></blockquote><p><strong>Prerequisite</strong>: <a href="https://www.techbloat.com/how-to-create-vofm-routines-in-sap-abap.html"><em>How to Create VOFM Routines in SAP ABAP — TechBloat</em></a></p><p>I use <strong>Transaction VOFM</strong> to create the logic. Create a routine 700 and name it ZREB. This is the ABAP subroutine that SAP calls every time the pricing engine hits the ZREB step.</p><p><strong>Path</strong>:VOFM → Formulas → Condition Value → Create routine 700(ZREB).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*2sNHewc_E-wGrHOClvVaJQ.png" /><figcaption><strong>VOFM Transaction code</strong></figcaption></figure><blockquote><strong>Step 2: Configuring the Condition Type (V/06)</strong></blockquote><p>If the condition type isn’t set up for the header, the routine won’t function even with the greatest code.<br>A. <strong>Transaction V/06</strong>: Choose <strong>ZREB</strong> as your condition.</p><p>B. <strong>Control Data</strong>:<br><strong>Class of Condition</strong>: A (Discount).<br><strong>Type of Calculation</strong>: B (Fixed Amount).<br><strong>Header Condition</strong>: ✅ <strong>Check this</strong>. This allows the condition to sit at the top of the order.</p><p>C. <strong>Important</strong>: Remove the <strong>Access Sequence. </strong>Because we aren’t using standard condition records</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*g3P3RC18_9Psxnv-4rE4pA.png" /><figcaption><strong>V/06 transaction with header details</strong></figcaption></figure><blockquote><strong>Step 3: Placing it in the Pricing Procedure (V/08)</strong></blockquote><p>Now, tell SAP to use your routine.</p><ol><li><strong>Transaction V/08:</strong> Go to your Pricing Procedure.</li><li><strong>Add ZREB:</strong> Place it toward the end of the procedure.</li><li><strong>AltCty (Alternative Calculation Type):</strong> Enter your routine number 700.</li></ol><p>Since this is where most novices get lost, let’s take a closer look at the routine.<br><strong>Inside the Routine: What Information Can We Access:</strong><br>SAP provides you with access to multiple <strong>global structures</strong> when your routine fires. They are already in scope; you don’t need to announce them. What each one has and when to utilize it are as follows:</p><p><strong>KOMK</strong>-&gt;<em>Header Communication [KUNNR-&gt;Customer Number, KDATU-&gt;Document date, etc.] is stable across the entire order, and it is used for the unique customer no.</em></p><p><strong>XKOMV</strong>-&gt;<em>Current condition work area [KWART-&gt;Base value (Read-Only)</em>, <strong>XKWERT</strong>-&gt;<em>Condition value (Write here), KINAK-&gt;SET ‘X’ to deactivate] is the main target for read and write condition value (ZREB).</em></p><p><strong>KOMP</strong>-&gt;<em>Item Structure [fields are the same as KOMK but hold only the LAST item when the header routine fires]. We should consider </em><strong><em>KPOSN</em></strong><em> field for each item.</em></p><p><strong>The most important distinction in the whole routine</strong></p><p><strong>XKOMV-KWART: </strong>SAP fills this <strong>BEFORE</strong> calling your routine. It is basically the base value of each order. Never write to it.</p><p><strong>XKWERT: </strong>This is your output. Whatever you write here becomes the condition value on the document. Our ZREB condition value will have to be written here.</p><blockquote><strong>Step 3: The Logic Inside Routine 700</strong></blockquote><p>Suppose you have four items in an open order; then SAP runs the ZREB routine for item 10, then 20, then 30, then 40. If you use debugging in the routine, you will find multiple executions of the routine, even more than the number of items. And once in a while, it hits item 000, the header where all item summations are stored in <strong>xkomv-kwart</strong>. Lastly, we need to pass the discount or condition value of ZREB to the <strong>XKWERT</strong> field.</p><ul><li>If you don’t check for 000000, the system will try to pull the discount for every single line!</li><li>We use xkomv-kawrt (the base value) to ensure we have a valid order total before assigning the discount, as we checked the header condition in V/06.</li><li>Move that value to xkwert (the condition value).</li></ul><pre>## SNIPPET OF A CODE<br><br>SELECT SINGLE * FROM zsls_prv_datak<br>      INTO ls_zsls_datak<br>      WHERE customer = lv_kunnr<br>        AND mmonth   = lv_month<br>        AND yyear    = lv_year. <br>IF komp-kposn = &#39;000000&#39;.<br>       lv_net_value = xkomv-kawrt.<br>       IF lv_net_value &gt; 0.<br>          IF ls_zsls_datak-remain_rebate &gt;= lv_net_value.<br>             lv_kwert = lv_net_value * -1.<br>           ELSE.<br>             lv_kwert = ls_zsls_datak-remain_rebate * -1.<br>           ENDIF.<br>             xkwert = lv_kwert.<br>             EXPORT lv_kwert TO MEMORY ID &#39;ZREB_VAL&#39;.<br><br>        ENDIF.<br>     ENDIF.<br>  ENDIF.</pre><ul><li><strong>Routine Execution:</strong> Runs for items first (10, 20…), then the Header (000). <strong>Always</strong> target 000 header-only logic.</li><li><strong>XKWERT:</strong> This is the field that updates the actual currency value on the screen.</li></ul><p>If all the conditions apply, the condition value of ZREB or the discount value from the Z table will be shown:</p><blockquote>The base value is 1648.00 BDT; plus, there is some VAT and all. But you can see there is a row for ZREB condition, where the condition value is 1552.00 BDT negative, which was fetched from the Z table for that particular customer.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AUSLPdNInuQtCoNusDP1YQ.png" /><figcaption><strong>ZREB: Customer Rebate; Condition value (1552.00 BDT)</strong></figcaption></figure><p><strong>Phase 3 — Updating the Z table after calculation:</strong></p><p><em>“VOFM routines are intended for implementing additional checks or </em><strong><em>calculations</em></strong><em>. </em><strong><em>Never update</em></strong><em> your Z-table inside the VOFM routine. VOFM triggers every time you press “</em><strong><em>Enter</em></strong><em>. ”&quot;</em></p><p><strong>Why SAP says this:</strong></p><p>VOFM routines are executed <strong>inside the main SD transaction flow</strong> (pricing, copying control, billing). The <strong>commit</strong> is controlled by SAP’s framework—if you update a table here, you risk the following:</p><ul><li><strong>Partial updates</strong> if the main transaction fails later.</li><li><strong>Lock conflicts</strong> with other processes.</li><li><strong>Performance degradation</strong> if the routine is called frequently.</li></ul><p><strong>How to Safely Update Custom Z-Tables:</strong></p><p>When you have to update a custom Z-table during SAP SD operations, timing is crucial. Your update logic must only run once, at the very end of the transaction, after all standard validations have been completed and the document is assured to save, in order to avoid database failures and inconsistencies.</p><p>The typical procedure is simple if your client requests a condition (such as ZREB) be handled at the <strong>Sales Order (VA01)</strong> level. Within the include <strong>MV45AFZZ</strong>, you can put your database update inside the <strong><em>USEREXIT_SAVE_DOCUMENT</em></strong>. This user exit is very dependable since it only occurs once in the sales document process. <strong>The benefit is that all condition and discount information is automatically retained by standard sales order structures.</strong></p><p>But in my case, the client wanted the whole process at the billing (VF01) level, as they are using the cockpit for ordering the item. We must use <strong>USEREXIT_NUMBER_RANGE</strong> (utilizing a variable <strong>US_RANGE_INTERN</strong>) inside the include <strong>RV60AFZZ</strong>. This area is specifically dedicated to the billing save chain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*_d54c3aHv2i5Y5KgiuFeNQ.png" /><figcaption><strong>RV60AFZZ Program for billing user exit</strong></figcaption></figure><p><strong>Problem:</strong> Unlike MV45AFZZ in sales, RV60AFZZ range assignment does <strong>NOT</strong> recall or keep the discount values established during pricing. <strong>RV60AFZZ does not recognize or save the condition values in </strong><strong>xkomv</strong> at this stage of execution. <strong><em>Also, other user_exits don&#39;t hit at the end or hit multiple times during the billing process, which is not ideal for database updating.</em></strong> Because the standard structure won’t help us here, we need a technical workaround: capturing the value early and passing it to the exit using a temporary <strong>Memory ID</strong>.</p><p><strong>My Approach:</strong></p><blockquote>Step 1: Inside your VOFM routine, grab the calculated discount amount. Export this value to the SAP memory using a <strong>unique Memory ID</strong>.</blockquote><pre>EXPORT lv_kwert TO MEMORY ID &#39;ZREB_VAL&#39;.</pre><blockquote>Step 2: Now that the data is safely floating in the session memory, Go to USEREXIT_NUMBER_RANGE in include RV60AFZZ. Import the saved discount amount back from the memory ID.</blockquote><pre>IMPORT lv_kwert TO lv_total_rebate FROM MEMORY ID &#39;ZREB_VAL&#39;.</pre><blockquote>Step 3: Write your MODIFY or UPDATE statement to add the value to your custom Z-table after you have it. To maintain a clean session, remember to free the memory ID after each use.</blockquote><pre>## SNIPPET OF A CODE<br>      <br>      SELECT SINGLE * FROM zsls_prv_datak INTO ls_zsls_datak<br>             WHERE customer = vbrk-kunag<br>             AND mmonth   = lv_month<br>             AND yyear    = lv_year.<br>      IF sy-subrc = 0.<br>           ls_zsls_datak-remain_rebate = ls_zsls_datak-remain_rebate + lv_total_rebate.<br>           ls_zsls_datak-rebated_amount = ls_zsls_datak-rebated_amount + ( lv_total_rebate * -1 ) .<br>           MODIFY zsls_prv_datak FROM ls_zsls_datak.<br>      ENDIF.<br>      FREE MEMORY ID &#39;ZREB_VAL&#39;.<br>      DELETE FROM MEMORY ID &#39;ZREB_VAL&#39;.</pre><p>The entire cycle can be successfully finished by following this order:<br>1. Ordering the product ensures that the cycle runs smoothly.<br>2. At the billing stage, the discount is appropriately applied to that product for the consumer.<br>3. The remaining discount balance is tracked and reflected in the custom Z-table, which is updated safely and without any chance of data failure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*tZLdCQ7BiNRA-L0FUHc6iw.png" /><figcaption><strong>Rebate Amount and Rebated Amount</strong></figcaption></figure><p><strong>Phase 4 — What about returning the product? How to track back the discounted amount?</strong></p><p>When a customer successfully completes an order, the discount amount is automatically lowered and updated in the custom Z-table.</p><p>However, what occurs if the client chooses to return the complete order? How can we address this situation, manage the return receipt appropriately, and guarantee that the customer’s discounted amount is correctly paid back into the Z-table?</p><blockquote><strong>Step 1: Trace back and collect the discounted amount using VOFM</strong></blockquote><p>When a return process is triggered using a custom cockpit or BAPI, this time copy-control directs the execution to the Sales Order level. VOFM Routine is triggered for condition type <strong>ZREB</strong> under transaction <em>ZR_SALES_RETURN</em> to determine the precise reimbursement.</p><ul><li>Using <strong>knumv</strong>, it performs an aggregation (SUM) on the condition value (<strong>kwert</strong>) from the core pricing table <strong>PRCD_ELEMENTS</strong>.</li><li>The accumulated total is then passed back to the standard pricing interface via the condition value variable. <strong>xkwert</strong></li><li>The whole process needs to be at the header level ‘0000000’.</li></ul><pre># Code Snippet<br> <br>IF komp-kposn = &#39;000000&#39;.<br><br>      SELECT SINGLE knumv FROM vbrk INTO lv_ref_knumv WHERE vbeln = lv_ref_vbeln.<br><br>      IF sy-subrc = 0.<br><br>        SELECT SUM( kwert ) FROM prcd_elements INTO lv_zreb_total<br>          WHERE knumv = lv_ref_knumv AND kschl = &#39;ZREB&#39;.<br><br>          IF sy-subrc = 0.<br>             xkwert = lv_zreb_total.<br><br>          ENDIF.<br>      ENDIF.<br><br>       CLEAR:lv_ref_vbeln, lv_ref_knumv, lv_zreb_total.<br>    ENDIF.</pre><p>If this worked perfectly, you would see the discounted amount in the Return Sales Order in <strong>VA03</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ARUmjzW_rKm-Ty59zkm20Q.png" /></figure><blockquote><strong>Step 2: Reimburse Customer Balances at MV45AFZZ and Update Z-Table</strong></blockquote><p>Because the business logic relies on <strong><em>Sales Order </em></strong>processing, the final database staging is handled under include <strong>MV45AFZZ</strong> within <strong>USEREXIT_SAVE_DOCUMENT</strong>.</p><ul><li>We don&#39;t need to use MEMORY ID in this user exit because xkomv is recognized here and loops through the standard internal table <strong>xkomv</strong> to aggregate all applied condition values (<strong>ls_komv-kwert</strong>).</li></ul><pre>##Sum up all the ZREB conditions applied in this document<br>    LOOP AT xkomv INTO DATA(ls_komv) WHERE kschl = &#39;ZREB&#39;.<br>      lv_total_rebate = lv_total_rebate + ls_komv-kwert.<br>    ENDLOOP.</pre><p>The system updates the custom repository after determining the target customer <strong><em>(vbak-kunnr)</em></strong> and the resulting period data.<br>The tracking structure is given the newly created return document number <strong><em>(vbak-vbeln)</em></strong>.<br>Lastly, the custom Z-table (zsls_prv_datak) is safely updated in accordance with the usual SAP database commit sequence by executing an ABAP MODIFY command.</p><pre>      SELECT SINGLE * FROM zsls_prv_datak<br>        INTO ls_zsls_datak<br>        WHERE customer = vbak-kunnr<br>          AND mmonth   = lv_month<br>          AND yyear    = lv_year.<br><br>      IF sy-subrc = 0.<br>        &quot; Because lv_total_rebate is negative, adding it effectively subtracts it<br>        ls_zsls_datak-remain_rebate  = ls_zsls_datak-remain_rebate + ( lv_total_rebate * -1 ).<br>        ls_zsls_datak-rebated_amount = ls_zsls_datak-rebated_amount + lv_total_rebate.<br>        ls_zsls_datak-so             = vbak-vbeln. &quot; The BAPI has generated the order number by now!<br><br>        &quot; Perform the actual DB update during the true SAP Save event<br>        MODIFY zsls_prv_datak FROM ls_zsls_datak.<br>      ENDIF.</pre><p>You will see a reflection of the data in your table with the most recent <strong>returning document number (vbak-vbeln) </strong>and the reimbursed deduction amount of discount once the custom Z table has been successfully modified and the product has been returned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*hRFG8edINXFUflcxGNvJKQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=984c17a9f47e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sap-innovation-hub/sap-abap-building-a-custom-rebate-engine-in-sap-sd-using-vofm-pricing-routine-984c17a9f47e">SAP ABAP: Building a Custom Rebate Engine in SAP SD Using VOFM Pricing Routine</a> was originally published in <a href="https://medium.com/sap-innovation-hub">SAP Innovation Hub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>