SAP Finance Guide: Follow a Purchase and a Sale through the Ledger

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Checked on 2026-11-13 against CAP Node.js 10.2 (@sap/cds 10.2.2, @sap/cds-dk 10.2.1, @cap-js/cds-test 1.0.2), the Fiori elements preview of cds watch (SAPUI5 1.145.0), curl 8.7 and Node.js 24.21.

What you build

This is a teaching model built with CAP. It is not SAP S/4HANA or SAP SuccessFactors and does not reproduce their screens.

You build a small ledger for the company code EX01 of Example Trading Co. (euro, ledger 0L) with six actions, one for each business event of a purchase and a sale: a goods receipt, a supplier invoice, a payment to the supplier, a sale (the goods issue and the billing document), a payment from the customer, and the clearing of open items. No action receives a G/L account. Each one builds its lines from a transaction key such as BSX (stock) or WRX (GR/IR clearing), and a table of account determination turns the key into the account, the way Account Determination and Automatic Postings describes. You buy 50 pieces, receive them, get the invoice and pay it, sell 40 of them, get paid, clear the open items that add up to zero, and read the ledger as T-accounts.

Ten T-accounts of company code EX01 after six documents: bank debit 107.10, customers zero, stock of trading goods debit 75.00, price differences debit 35.00, input tax debit 77.90, suppliers zero, GR/IR clearing zero, output tax credit 95.00, cost of goods sold debit 300.00 and sales revenue credit 500.00

Before you start

  • No account is needed: the CAP tools and curl install without signing in. Installing @sap/cds-dk means accepting the SAP Developer License Agreement, version 3.2, which the lab README names.

  • Do the guides Your First CAP Service (it explains cds init, CDS files, CSV data and cds watch) and Post Balanced Journal Entries in a Teaching Ledger first. This guide uses the same sign convention: a debit is a positive amount and a credit a negative one.

  • Read the pages that the model copies: Accounts Payable (goods receipt, invoice, GR/IR clearing and payment), Accounts Receivable, Dunning and Credit Management (order to cash), Open Item Management and Clearing and Account Determination and Automatic Postings.

  • You need curl 7.82 or newer, which has the option --json. curl --version prints the version.

  • The names. CompanyCode, Ledger, GLAccount and AmountInCompanyCodeCurrency are element names of the SAP view I_JournalEntryItemBasic, as in the first finance guide. The transaction keys BSX, PRD, WRX and GBB and the account key ERL are the ones that the account determination page names from SAP pages. The keys INTAX, OUTTAX, VENDOR, CUSTOMER and BANK, the document type codes WE, RE, WA and RV (KZ and DZ are listed on Journal Entries, Document Types and Posting Keys), the entity names, the account numbers and the purchase order, material, supplier and customer codes are this model’s own. All codes and amounts are made up, and the tax rate of 19 percent is illustrative.

  • The figures are drawings of the editor, the terminal, the browser and the Fiori page, not screenshots. A highlighted box with a number marks the file, the command or the page part of the step with the same number.

Steps

Create the project and the model

  1. Create a CAP project named ledger-postings and install it, as in the first guide:

    cds init ledger-postings --nodejs
    cd ledger-postings
    npm install
  2. Create db/schema.cds. Documents and DocumentItems hold the postings: a document is the posting of one business event, and its lines have the keys Document and ItemNumber. Every line carries the transaction key it came from, the G/L account, and, for a supplier or customer line, the partner. ClearingDocument and ClearingDate stay empty until the line is cleared. GLAccounts says which accounts are managed with open items, and AccountDetermination is the table that turns a key into an account. Materials and PurchaseOrders are the master data of the purchase.

    namespace sap.guide.ledgerpostings;
    
    // A teaching model of postings that follow business events, not SAP S/4HANA.
    // CompanyCode, Ledger, GLAccount and AmountInCompanyCodeCurrency are element
    // names of the SAP view I_JournalEntryItemBasic; the other names are our own.
    entity GLAccounts {
      key Account     : String(10);
      Name            : String(40);
      OpenItemManaged : Boolean;
    }
    
    // Which G/L account a transaction key posts to. ValuationClass is '-' for a
    // key that does not depend on it (our own convention).
    entity AccountDetermination {
      key TransactionKey : String(10);
      key ValuationClass : String(4);
      GLAccount          : String(10);
    }
    
    entity Materials {
      key ID         : String(10);
      Name           : String(40);
      ValuationClass : String(4);
      StandardPrice  : Decimal(15,2);
      StockQuantity  : Integer default 0;
    }
    
    entity PurchaseOrders {
      key ID           : String(10);
      Supplier         : String(10);
      Material         : Association to Materials;
      Quantity         : Integer;
      Price            : Decimal(15,2);
      ReceivedQuantity : Integer default 0;
      InvoicedQuantity : Integer default 0;
    }
    
    // An accounting document: the posting of one business event.
    entity Documents {
      key DocumentNumber : String(10);
      DocumentType       : String(2);
      CompanyCode        : String(4) default 'EX01';
      Ledger             : String(2) default '0L';
      PostingDate        : Date;
      Description        : String(60);
      Items : Composition of many DocumentItems on Items.Document = $self;
    }
    
    // One line. A debit is a positive amount and a credit a negative amount.
    // A line of an open-item-managed account is open until it is cleared.
    entity DocumentItems {
      key Document                : Association to Documents;
      key ItemNumber              : Integer;
      TransactionKey              : String(10);
      GLAccount                   : String(10);
      ProfitCenter                : String(10);
      Partner                     : String(10);
      Reference                   : String(20);
      AmountInCompanyCodeCurrency : Decimal(15,2);
      ClearingDocument            : String(10);
      ClearingDate                : Date;
    }
  3. Create the four CSV files in db/data. The G/L accounts are the ten that the story uses. The accounts with true (customers, suppliers and GR/IR clearing) are managed with open items. In the determination table the keys BSX, PRD, WRX and GBB depend on the valuation class 3100 of the material, and the other keys do not (-). The material M-100 has a standard price of 7.50 EUR and no stock. The purchase order PO-1 orders 50 pieces from the supplier V-1000 at 8.00 EUR.

    Account,Name,OpenItemManaged
    113100,Bank,false
    121000,Customers,true
    140000,Stock of trading goods,false
    140900,Price differences,false
    154000,Input tax,false
    160000,Suppliers,true
    231000,GR/IR clearing,true
    260000,Output tax,false
    600000,Cost of goods sold,false
    800000,Sales revenue,false
    TransactionKey,ValuationClass,GLAccount
    BSX,3100,140000
    PRD,3100,140900
    WRX,3100,231000
    GBB,3100,600000
    INTAX,-,154000
    VENDOR,-,160000
    BANK,-,113100
    CUSTOMER,-,121000
    ERL,-,800000
    OUTTAX,-,260000
    ID,Name,ValuationClass,StandardPrice,StockQuantity
    M-100,Trading good,3100,7.50,0
    ID,Supplier,Material_ID,Quantity,Price,ReceivedQuantity,InvoicedQuantity
    PO-1,V-1000,M-100,50,8.00,0,0
    Visual Studio Code with the file db/schema.cds of the ledger-postings project: an excerpt with the entity Documents and its composition of Items and the entity DocumentItems with the keys Document and ItemNumber, the transaction key, the G/L account, the partner, the reference, the amount in company code currency and the clearing document; callout 2 marks the file in the explorer

Write the posting rules

  1. Create srv/ledger-postings-service.cds. The entities are read-only: documents come into being only through the actions. AccountBalances and OpenItems are views that add up the lines and list the open ones. The six actions take no G/L account.

    using { sap.guide.ledgerpostings as db } from '../db/schema';
    
    service LedgerPostingsService {
      @readonly entity Documents     as projection on db.Documents;
      @readonly @cds.redirection.target
      entity DocumentItems as projection on db.DocumentItems;
      @readonly entity GLAccounts    as projection on db.GLAccounts;
      @readonly entity Materials     as projection on db.Materials;
      @readonly entity PurchaseOrders as projection on db.PurchaseOrders;
      @readonly entity AccountDetermination
        as projection on db.AccountDetermination;
    
      // Debits, credits and balance of every account (a debit balance is positive).
      @readonly entity AccountBalances as select from db.DocumentItems {
        key GLAccount,
        sum(case when AmountInCompanyCodeCurrency > 0
            then AmountInCompanyCodeCurrency else 0 end) as Debits  : Decimal(15,2),
        sum(case when AmountInCompanyCodeCurrency < 0
            then -AmountInCompanyCodeCurrency else 0 end) as Credits : Decimal(15,2),
        sum(AmountInCompanyCodeCurrency) as Balance : Decimal(15,2)
      } group by GLAccount;
    
      // The lines of open-item-managed accounts that are not cleared yet.
      @readonly entity OpenItems as select from db.DocumentItems as i
        inner join db.GLAccounts as a on a.Account = i.GLAccount {
        key i.Document.DocumentNumber as DocumentNumber, key i.ItemNumber,
        i.GLAccount, i.Partner, i.Reference, i.AmountInCompanyCodeCurrency
      } where i.ClearingDocument is null and a.OpenItemManaged = true;
    
      type Cleared { ClearingDocument : String(10); ClearedItems : Integer; }
    
      action postGoodsReceipt(PurchaseOrder : String(10), Quantity : Integer,
        PostingDate : Date) returns Documents;
      action postInvoiceReceipt(PurchaseOrder : String(10), Quantity : Integer,
        InvoicePrice : Decimal(15,2), PostingDate : Date) returns Documents;
      action payVendor(Document : String(10), PostingDate : Date)
        returns Documents;
      action postSale(Material : String(10), Quantity : Integer,
        NetPrice : Decimal(15,2), Customer : String(10), PostingDate : Date,
        ProfitCenter : String(10)) returns Documents;
      action receiveCustomerPayment(Customer : String(10), Amount : Decimal(15,2),
        PostingDate : Date) returns Documents;
      action clearOpenItems(GLAccount : String(10), Partner : String(10),
        Reference : String(20), ClearingDate : Date) returns Cleared;
    }
  2. Create srv/posting-rules.js. One function per business event returns its lines as a key and an amount in cents, a debit positive and a credit negative, so that the sums are exact. The goods receipt values the stock line at the standard price and the offsetting line at the order price, and the difference goes to the price difference line. The invoice clears GR/IR at the order price and credits the supplier with the gross amount. The sale posts the goods issue (cost of goods sold against stock) and the billing document (customer against revenue and output tax).

    // The posting rules of the teaching ledger: one function per business event.
    // Each returns the lines of the document as { key, cents }, a debit positive
    // and a credit negative. The G/L account of a line is found later, from the
    // transaction key. Amounts are whole cents, so that the sums are exact.
    export const cents = (amount) => Math.round(Number(amount) * 100)
    export const money = (c) => (c / 100).toFixed(2)
    
    // An illustrative tax rate of 19 percent, the same for input and output tax.
    const tax = (net) => Math.round((net * 19) / 100)
    const nonZero = (lines) => lines.filter((line) => line.cents !== 0)
    
    // tag::goods-receipt[]
    // Stock at the standard price, the offsetting entry at the order price, and
    // the difference to the price difference account.
    export function goodsReceipt({ quantity, price, standardPrice }) {
      const stock = quantity * cents(standardPrice)
      const received = quantity * cents(price)
      return nonZero([
        { key: 'BSX', cents: stock },
        { key: 'PRD', cents: received - stock },
        { key: 'WRX', cents: -received },
      ])
    }
    // end::goods-receipt[]
    
    // The invoice clears GR/IR at the order price. A different invoice price goes
    // to the price difference account. The supplier is credited with the gross.
    export function invoiceReceipt({ quantity, price, invoicePrice }) {
      const net = quantity * cents(invoicePrice)
      const ordered = quantity * cents(price)
      const inputTax = tax(net)
      return nonZero([
        { key: 'WRX', cents: ordered },
        { key: 'PRD', cents: net - ordered },
        { key: 'INTAX', cents: inputTax },
        { key: 'VENDOR', cents: -(net + inputTax) },
      ])
    }
    
    export const vendorPayment = (amount) => [
      { key: 'VENDOR', cents: amount },
      { key: 'BANK', cents: -amount },
    ]
    
    export const customerPayment = (amount) => [
      { key: 'BANK', cents: amount },
      { key: 'CUSTOMER', cents: -amount },
    ]
    
    export const goodsIssue = ({ quantity, standardPrice }) => [
      { key: 'GBB', cents: quantity * cents(standardPrice) },
      { key: 'BSX', cents: -quantity * cents(standardPrice) },
    ]
    
    export function billing({ quantity, netPrice }) {
      const net = quantity * cents(netPrice)
      const outputTax = tax(net)
      return [
        { key: 'CUSTOMER', cents: net + outputTax },
        { key: 'ERL', cents: -net },
        { key: 'OUTTAX', cents: -outputTax },
      ]
    }
  3. Create srv/ledger-postings-service.js. CAP loads it next to the service of the same name, and this.on attaches a handler to each action. The function post is the heart of the model: it finds the account of every line in AccountDetermination, refuses a document that does not balance, numbers it and stores it with its lines. clearOpenItems marks open items of one account as cleared when they add up to zero, and gives them the number of the latest document that takes part as the clearing document.

    import cds from '@sap/cds'
    import * as rules from './posting-rules.js'
    
    const { cents, money } = rules
    const db = cds.entities('sap.guide.ledgerpostings')
    const { Documents, DocumentItems, AccountDetermination } = db
    const { Materials, PurchaseOrders } = db
    
    // These keys look their account up by the valuation class of the material.
    const BY_CLASS = ['BSX', 'PRD', 'WRX', 'GBB']
    
    export default class LedgerPostingsService extends cds.ApplicationService {
      init() {
        this.on('postGoodsReceipt', goodsReceipt)
        this.on('postInvoiceReceipt', invoiceReceipt)
        this.on('payVendor', payVendor)
        this.on('postSale', sale)
        this.on('receiveCustomerPayment', customerPayment)
        this.on('clearOpenItems', clearOpenItems)
        return super.init()
      }
    }
    
    async function goodsReceipt(req) {
      const { PurchaseOrder, Quantity, PostingDate } = req.data
      const { po, material } = await order(req, PurchaseOrder)
      const open = po.Quantity - po.ReceivedQuantity
      if (Quantity > open) {
        return req.reject(400, `${PurchaseOrder} has only ${open} pieces open`)
      }
      const lines = rules.goodsReceipt({
        quantity: Quantity,
        price: po.Price,
        standardPrice: material.StandardPrice,
      })
      await UPDATE(PurchaseOrders, PurchaseOrder).with({
        ReceivedQuantity: po.ReceivedQuantity + Quantity,
      })
      await UPDATE(Materials, material.ID).with({
        StockQuantity: material.StockQuantity + Quantity,
      })
      const text = `Goods receipt ${PurchaseOrder}`
      const refs = { Reference: PurchaseOrder, Class: material.ValuationClass }
      return post(req, 'WE', PostingDate, text, lines, refs)
    }
    
    async function invoiceReceipt(req) {
      const { PurchaseOrder, Quantity, InvoicePrice, PostingDate } = req.data
      const { po, material } = await order(req, PurchaseOrder)
      if (Quantity > po.Quantity - po.InvoicedQuantity) {
        return req.reject(400, `${PurchaseOrder} has fewer pieces left to invoice`)
      }
      const lines = rules.invoiceReceipt({
        quantity: Quantity,
        price: po.Price,
        invoicePrice: InvoicePrice,
      })
      await UPDATE(PurchaseOrders, PurchaseOrder).with({
        InvoicedQuantity: po.InvoicedQuantity + Quantity,
      })
      const text = `Invoice ${PurchaseOrder}`
      const refs = {
        Reference: PurchaseOrder,
        Partner: po.Supplier,
        Class: material.ValuationClass,
      }
      return post(req, 'RE', PostingDate, text, lines, refs)
    }
    
    async function payVendor(req) {
      const { Document, PostingDate } = req.data
      const item = await SELECT.one.from(DocumentItems).where({
        Document_DocumentNumber: Document,
        TransactionKey: 'VENDOR',
      })
      if (!item) return req.reject(404, `Document ${Document} has no supplier line`)
      const lines = rules.vendorPayment(-cents(item.AmountInCompanyCodeCurrency))
      const refs = { Reference: Document, Partner: item.Partner }
      return post(req, 'KZ', PostingDate, `Payment of ${Document}`, lines, refs)
    }
    
    async function sale(req) {
      const { Material, Quantity, NetPrice, Customer, PostingDate } = req.data
      const material = await SELECT.one.from(Materials, Material)
      if (!material) return req.reject(404, `Material ${Material} not found`)
      if (Quantity > material.StockQuantity) {
        const stock = `Stock of ${Material} is ${material.StockQuantity}`
        return req.reject(400, `${stock}, the sale needs ${Quantity}`)
      }
      await UPDATE(Materials, Material).with({
        StockQuantity: material.StockQuantity - Quantity,
      })
      const refs = {
        ProfitCenter: req.data.ProfitCenter ?? 'EX-RETAIL',
        Class: material.ValuationClass,
        Partner: Customer,
      }
      const issue = rules.goodsIssue({
        quantity: Quantity,
        standardPrice: material.StandardPrice,
      })
      await post(req, 'WA', PostingDate, `Goods issue ${Material}`, issue, refs)
      const bill = rules.billing({ quantity: Quantity, netPrice: NetPrice })
      return post(req, 'RV', PostingDate, `Billing ${Customer}`, bill, refs)
    }
    
    async function customerPayment(req) {
      const { Customer, Amount, PostingDate } = req.data
      const lines = rules.customerPayment(cents(Amount))
      const text = `Payment of ${Customer}`
      return post(req, 'DZ', PostingDate, text, lines, { Partner: Customer })
    }
    
    async function order(req, id) {
      const po = await SELECT.one.from(PurchaseOrders, id)
      if (!po) return req.reject(404, `Purchase order ${id} not found`)
      const material = await SELECT.one.from(Materials, po.Material_ID)
      return { po, material }
    }
    
    // tag::post[]
    // Finds the G/L account of every line from its transaction key, checks that
    // the document balances, numbers it and stores it with its lines.
    async function post(req, type, date, text, lines, refs) {
      const items = []
      for (const line of lines) {
        const ValuationClass = BY_CLASS.includes(line.key) ? refs.Class : '-'
        const found = await SELECT.one.from(AccountDetermination)
          .where({ TransactionKey: line.key, ValuationClass })
        if (!found) {
          return req.reject(400, `No account is determined for key ${line.key}`)
        }
        items.push({
          ItemNumber: items.length + 1,
          TransactionKey: line.key,
          GLAccount: found.GLAccount,
          ProfitCenter: ['GBB', 'ERL'].includes(line.key) ? refs.ProfitCenter : null,
          Partner: ['VENDOR', 'CUSTOMER'].includes(line.key) ? refs.Partner : null,
          Reference: refs.Reference ?? null,
          AmountInCompanyCodeCurrency: money(line.cents),
        })
      }
      const sum = lines.reduce((total, line) => total + line.cents, 0)
      if (sum !== 0) return req.reject(500, `Not balanced by ${money(sum)}`)
      const { count } = await SELECT.one`count(*) as count`.from(Documents)
      const DocumentNumber = String(100000001 + count)
      await INSERT.into(Documents).entries({
        DocumentNumber,
        DocumentType: type,
        PostingDate: date,
        Description: text,
        Items: items,
      })
      return SELECT.one.from(Documents, DocumentNumber)
    }
    // end::post[]
    
    // tag::clear[]
    // Clears the open items of one account that add up to zero. The clearing
    // document is the number of the latest document that takes part.
    async function clearOpenItems(req) {
      const { GLAccount, Partner, Reference, ClearingDate } = req.data
      const where = { GLAccount, ClearingDocument: null }
      if (Partner) where.Partner = Partner
      if (Reference) where.Reference = Reference
      const items = await SELECT.from(DocumentItems).where(where)
      const amounts = items.map((i) => cents(i.AmountInCompanyCodeCurrency))
      const debits = amounts.filter((c) => c > 0).reduce((t, c) => t + c, 0)
      const credits = -amounts.filter((c) => c < 0).reduce((t, c) => t + c, 0)
      if (items.length < 2 || debits !== credits) {
        const message = `debits ${money(debits)}, credits ${money(credits)}`
        return req.reject(400, `Items do not add up to zero: ${message}`)
      }
      const numbers = items.map((i) => i.Document_DocumentNumber)
      const ClearingDocument = numbers.sort().at(-1)
      await UPDATE(DocumentItems).set({ ClearingDocument, ClearingDate }).where(where)
      return { ClearingDocument, ClearedItems: items.length }
    }
    // end::clear[]
    Visual Studio Code with the file srv/posting-rules.js: the excerpt shows the function goodsReceipt, which values the stock line at the standard price and the clearing line at the order price and puts the difference on the price difference line; callout 5 marks the file in the explorer

Follow the purchase

  1. In the terminal, in the project folder, start the server. The log shows the four CSV files loaded and LedgerPostingsService served at /odata/v4/ledger-postings.

    cds watch
    Terminal after cds watch in the ledger-postings project: the log lists the model files, loads the CSV files for PurchaseOrders, Materials, GLAccounts and AccountDetermination into an in-memory SQLite database, serves LedgerPostingsService at /odata/v4/ledger-postings with the implementation srv/ledger-postings-service.js and ends with server listening on http://localhost:4004; callout 7 marks the command
  2. Create the folder http and in it goods-receipt.json. It receives all 50 pieces of PO-1.

    { "PurchaseOrder": "PO-1", "Quantity": 50, "PostingDate": "2026-03-03" }

    Open a second terminal in the project folder, set the address of the service once, and post the goods receipt. The option -w "\n" ends the answer with a line break. The answer is the header of the new document, number 100000001, type WE.

    export BASE=http://localhost:4004/odata/v4/ledger-postings
    curl -sw "\n" --json @http/goods-receipt.json $BASE/postGoodsReceipt
    Terminal with the command that sets BASE to the service address and the curl command that posts the goods receipt from http/goods-receipt.json to the action postGoodsReceipt; the answer is the document header with DocumentNumber 100000001 and DocumentType WE; callout 8 marks the curl command and its answer
  3. Read the lines of the document. Open http://localhost:4004/odata/v4/ledger-postings/DocumentItems?$select=TransactionKey,GLAccount,AmountInCompanyCodeCurrency in the browser. Three lines are there, and you typed no account: BSX found 140000, PRD found 140900 and WRX found 231000.

    Browser with the address localhost:4004/odata/v4/ledger-postings/DocumentItems?$select=TransactionKey,GLAccount,AmountInCompanyCodeCurrency, marked by callout 9: the JSON response lists the three lines of document 100000001, key BSX account 140000 amount 375.00, key PRD account 140900 amount 25.00 and key WRX account 231000 amount -400.00
  4. Create http/invoice-receipt.json, the supplier’s invoice for the 50 pieces at 8.20 EUR, and post it:

    {
      "PurchaseOrder": "PO-1",
      "Quantity": 50,
      "InvoicePrice": 8.20,
      "PostingDate": "2026-03-10"
    }
    curl -sw "\n" --json @http/invoice-receipt.json $BASE/postInvoiceReceipt

    The answer is document 100000002, type RE.

  5. Open http://localhost:4004/odata/v4/ledger-postings/OpenItems in the browser. The three open items are the GR/IR line of the goods receipt (-400.00), the GR/IR line of the invoice (400.00) and the supplier line of the invoice (-487.90). The stock, price difference and tax lines are on accounts that are not managed with open items, so they are not listed.

    Browser with the address localhost:4004/odata/v4/ledger-postings/OpenItems, marked by callout 11: the JSON response lists three open items, the GR/IR line of document 100000001 with -400.00, the GR/IR line of document 100000002 with 400.00 and the supplier line of document 100000002 with -487.90, all with the reference PO-1
  6. Create http/clear-gr-ir.json and clear the GR/IR items of PO-1. They add up to zero, so both are cleared, and the answer names the clearing document 100000002, the latest document that takes part, and 2 cleared items.

    {
      "GLAccount": "231000",
      "Reference": "PO-1",
      "ClearingDate": "2026-03-10"
    }
    curl -sw "\n" --json @http/clear-gr-ir.json $BASE/clearOpenItems
  7. Create http/pay-vendor.json and pay the invoice document 100000002. The payment is document 100000003, type KZ: a debit on the supplier account and a credit on the bank.

    { "Document": "100000002", "PostingDate": "2026-03-20" }
    curl -sw "\n" --json @http/pay-vendor.json $BASE/payVendor
  8. Create http/clear-suppliers.json and clear the supplier account of V-1000. The invoice item (-487.90) and the payment item (487.90) are cleared with the clearing document 100000003.

    { "GLAccount": "160000", "Partner": "V-1000", "ClearingDate": "2026-03-20" }
    curl -sw "\n" --json @http/clear-suppliers.json $BASE/clearOpenItems
    Terminal with four curl commands: the invoice receipt answered with the document header 100000002 of type RE (callout 10), clearing of the GR/IR account for PO-1 answered with clearing document 100000002 and 2 cleared items (callout 12), the vendor payment answered with document 100000003 of type KZ (callout 13) and clearing of the supplier account answered with clearing document 100000003 and 2 cleared items (callout 14); the long answers wrap onto a second line

Follow the sale

  1. Create http/sale.json and post the sale of 40 pieces at 12.50 EUR net to the customer C-2000. The action posts two documents: 100000004 for the goods issue (type WA) and 100000005 for the billing document (type RV). The answer is the header of the billing document.

    {
      "Material": "M-100",
      "Quantity": 40,
      "NetPrice": 12.50,
      "Customer": "C-2000",
      "PostingDate": "2026-03-25"
    }
    curl -sw "\n" --json @http/sale.json $BASE/postSale
  2. Create http/customer-payment.json, the customer’s payment of 595.00 EUR, and post it. It is document 100000006, type DZ: a debit on the bank and a credit on the customer account.

    { "Customer": "C-2000", "Amount": 595.00, "PostingDate": "2026-04-02" }
    curl -sw "\n" --json @http/customer-payment.json $BASE/receiveCustomerPayment
  3. Look at the open items again with curl -s $BASE/OpenItems. Two items remain, both on the customer account 121000: the invoice item of 595.00 and the payment item of -595.00. The payment did not clear the invoice by itself. Clearing is a step of its own, as the open items page describes.

  4. Create http/clear-customers.json and clear the customer account of C-2000. The answer names the clearing document 100000006 and 2 cleared items, and curl -s $BASE/OpenItems now answers with an empty list.

    { "GLAccount": "121000", "Partner": "C-2000", "ClearingDate": "2026-04-02" }
    curl -sw "\n" --json @http/clear-customers.json $BASE/clearOpenItems
    Terminal with three curl commands: the sale answered with the billing document 100000005 of type RV (callout 15), the customer payment answered with document 100000006 of type DZ (callout 16) and clearing of the customer account answered with clearing document 100000006 and 2 cleared items (callout 18); the long answers wrap onto a second line

Read the ledger

  1. Open http://localhost:4004/odata/v4/ledger-postings/AccountBalances in the browser. For each account the view gives the debits, the credits and the balance. The figure shows the first four of the ten accounts; the others are in the T-accounts of the result figure and in the table of the next section.

    Browser with the address localhost:4004/odata/v4/ledger-postings/AccountBalances, marked by callout 19: the JSON response shows the debits, credits and balance of the first four accounts, 113100 with 595.00, 487.90 and 107.10, 121000 with 595.00, 595.00 and 0.00, 140000 with 375.00, 300.00 and 75.00 and 140900 with 35.00, 0.00 and 35.00; the figure leaves out the other six accounts
  2. Create app/annotations.cds. The first part gives the fields their labels, the second builds the list report of the documents and the object page with the table of the lines.

    using LedgerPostingsService as service from '../srv/ledger-postings-service';
    
    annotate service.Documents with {
      DocumentNumber @title : 'Document Number';
      DocumentType   @title : 'Type';
      PostingDate    @title : 'Posting Date';
      Description    @title : 'Description';
      CompanyCode    @title : 'Company Code';
      Ledger         @title : 'Ledger';
    };
    annotate service.DocumentItems with {
      ItemNumber                  @title : 'Item';
      TransactionKey              @title : 'Key';
      GLAccount                   @title : 'G/L Account';
      ProfitCenter                @title : 'Profit Center';
      Partner                     @title : 'Partner';
      Reference                   @title : 'Reference';
      AmountInCompanyCodeCurrency @title : 'Amount in Company Code Currency';
      ClearingDocument            @title : 'Clearing Document';
    };
    
    annotate service.Documents with @(
      UI.LineItem : [
        { Value : DocumentNumber },
        { Value : DocumentType },
        { Value : PostingDate },
        { Value : Description },
        { Value : CompanyCode }
      ],
      UI.HeaderInfo : {
        TypeName : 'Document', TypeNamePlural : 'Documents',
        Title : { Value : Description }
      },
      UI.Facets : [
        { $Type : 'UI.ReferenceFacet', Label : 'General', Target : '@UI.FieldGroup#General' },
        { $Type : 'UI.ReferenceFacet', Label : 'Lines', Target : 'Items/@UI.LineItem' }
      ],
      UI.FieldGroup #General : {
        Data : [{ Value : DocumentNumber }, { Value : PostingDate },
                { Value : CompanyCode }, { Value : Ledger }]
      }
    );
    annotate service.DocumentItems with @(
      UI.LineItem : [
        { Value : ItemNumber }, { Value : TransactionKey }, { Value : GLAccount },
        { Value : AmountInCompanyCodeCurrency }, { Value : ClearingDocument }
      ]
    );
  3. Open http://localhost:4004/$fiori-preview/LedgerPostingsService/Documents?sap-language=EN#preview-app. The list report Documents (6) shows the six documents in the order of their numbers. Click a document to see its lines on the object page. The entities are read-only, so the page has no Create or Delete button.

    Fiori elements list report Documents (6) with the columns Document Number, Type, Posting Date, Description and Company Code: the six documents 100000001 to 100000006 of the types WE, RE, KZ, WA, RV and DZ; callout 21 marks the table

Check the result

The lines of every document are the ones the tests of the lab assert. All amounts are in EUR.

Document Type Line (key, account) Debit Credit

100000001, goods receipt

WE

BSX, 140000 stock

375.00

PRD, 140900 price differences

25.00

WRX, 231000 GR/IR clearing

400.00

100000002, supplier invoice

RE

WRX, 231000 GR/IR clearing

400.00

PRD, 140900 price differences

10.00

INTAX, 154000 input tax

77.90

VENDOR, 160000 suppliers

487.90

100000003, payment to the supplier

KZ

VENDOR, 160000 suppliers

487.90

BANK, 113100 bank

487.90

100000004, goods issue

WA

GBB, 600000 cost of goods sold

300.00

BSX, 140000 stock

300.00

100000005, billing document

RV

CUSTOMER, 121000 customers

595.00

ERL, 800000 sales revenue

500.00

OUTTAX, 260000 output tax

95.00

100000006, payment from the customer

DZ

BANK, 113100 bank

595.00

CUSTOMER, 121000 customers

595.00

The sums on this page are the amounts that the service answered and npm test asserts. The goods receipt values 50 pieces at the standard price of 7.50 and at the order price of 8.00:

The invoice is for net, the tax is and the supplier is credited with . GR/IR is cleared at the order value of 400.00, and the extra goes to the price difference line:

The sale of 40 pieces costs and bills net, with output tax , so the customer owes . Then:

  • GR/IR clearing has debits and credits of 400.00 each: the goods were received and invoiced, nothing is left.

  • The suppliers and customers accounts balance at zero, and OpenItems is empty: every open item was cleared.

  • The stock account is , which is the 10 pieces left at the standard price of 7.50, and curl -s $BASE/Materials shows StockQuantity 10.

  • The price difference account holds , which is the invoice net minus the stock value: .

  • The bank account is .

  • The whole ledger balances, as every posting does: all debits are and all credits are .

The goods receipt function is also checked against the worked example of the SAP Learning page Describing Automatic Account Determination. For 10 pieces with a standard price of 10 and an order price of 12, that page posts 100 to stock, 120 to GR/IR clearing and the difference of 20 to a price difference account, and the test sap-learning-example.test.js expects the same three lines. For an invoice of 110 against the goods receipt value of 120, the page clears the full 120 and posts the gap of 10 on another account. This model puts the gap on the price difference line too, so its account differs from the page’s example but the amount is the same.

Run the tests with npm test in a copy of the lab project ledger-postings. They post the story of this guide and the cases of the next sections, and they pass.

Variations

  • Invoice only part of the goods. Restart cds watch (the database is in memory), post the goods receipt again, and post an invoice for 30 pieces:

    curl -sw "\n" --json '{"PurchaseOrder":"PO-1","Quantity":30,"InvoicePrice":8.00,"PostingDate":"2026-03-10"}' $BASE/postInvoiceReceipt

    The invoice clears only of GR/IR. Clearing PO-1 answers Items do not add up to zero: debits 240.00, credits 400.00 with HTTP 400: the credit balance of 160.00 is goods received and not yet invoiced, 20 pieces at 8.00, as the accounts payable page explains.

  • Sell for the other profit center. After the goods receipt, post a sale of 10 pieces with ProfitCenter set:

    curl -sw "\n" --json '{"Material":"M-100","Quantity":10,"NetPrice":11.00,"Customer":"C-3000","PostingDate":"2026-03-26","ProfitCenter":"EX-WHOLE"}' $BASE/postSale

    The lines with the profit center EX-WHOLE are the cost of goods sold of 75.00 on 600000 and the revenue of -110.00 on 800000.

  • Take a key out of the determination table. In db/data/sap.guide.ledgerpostings-AccountDetermination.csv delete the line of WRX, save, and post the goods receipt. The answer is No account is determined for key WRX with HTTP 400, and nothing is stored: the received quantity of PO-1 and the stock of M-100 are still 0, because the request is rolled back. Put the line back to continue.

What can go wrong

Symptom Cause Fix

PO-1 has only 50 pieces open and HTTP 400

The goods receipt asks for more pieces than the purchase order has open (60 instead of 50).

Lower Quantity in the JSON file.

PO-1 has only 0 pieces open

The goods receipt was posted before in this run, so nothing is open.

Skip the step, or restart cds watch to get the initial data back.

Stock of M-100 is 10, the sale needs 40 and HTTP 400

The sale was posted a second time, or asks for more pieces than the stock.

Sell at most the stock, or post a goods receipt first.

Items do not add up to zero: debits 240.00, credits 400.00

The open items selected for clearing do not add up to zero, as after a partial invoice.

Post the missing document first, or select items that add up to zero.

Items do not add up to zero: debits 0.00, credits 0.00

Nothing is open for the account, the partner or the reference: the items are cleared already, or the document is not posted yet.

Check OpenItems, then post the missing document.

No account is determined for key WRX

The determination table has no row for the key and the valuation class of the material.

Add the row to the CSV file.

Clean up

Press Ctrl+C in the terminal that runs cds watch. The database lives only in memory, so the six documents are gone at the next start; the CSV files bring back the accounts, the material and the purchase order.