SAP HR Guide: Compute Pay for a Partial Period and Gross-to-Net

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, SAP HCM or SAP Payroll and does not reproduce their screens.

You build a small model of one payroll calculation. An employee who is paid for only part of a month receives the basic pay multiplied by a partial period factor, a fraction made of working days. The model offers three of the methods that SAP documents for this factor: the PWS method (personal work schedule), the payment method and the deduction method. From the resulting gross pay it forms the net pay with two flat-rate statutory deductions, social contributions and income tax, and one voluntary deduction that is taken from the net pay. Every step is done in whole cents, with one stated rounding rule, and every amount on this page is checked by a test. You read the result as a payslip in a Fiori elements object page.

Fiori elements object page of the payslip of Ben Okoye with the tabs Calculation and Payslip: the calculation shows the period 2026-03, paid from Mar 1, 2026 to Mar 31, 2026, the method PWS, 22 planned days, 5 days not paid, the divisor 22, the numerator 17 and the partial period factor 0.7727; the table Payslip (9) runs from the basic pay 2,400.00 through the partial period adjustment of -545.45, the gross pay 1,854.55, the deductions 370.91, 222.55 and 25.00, and the net pay 1,261.09 to the payment 1,236.09, and ends with the employer contributions 389.46

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 CAP Domain Model and Custom Logic first. Model Employee Records with Validity Periods builds the records that this guide’s model reads (here reduced to one basic pay amount per employee).

  • Read Partial Periods and Retroactive Accounting, Wage Types and Payroll Results and HR and Payroll Basics. This guide computes the examples of those pages.

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

  • The example is the one of the HR pages: Example Trading Co., payroll area E1 "Monthly EX01", and the employees Ana Torres 00001234 (4,000.00 EUR a month) and Ben Okoye 00001235 (2,400.00 EUR a month). All codes, rates and amounts are invented example values, not values delivered by SAP. Dates in the model are written YYYY-MM-DD, as in code; the SAP screens of the reference pages show DD.MM.YYYY, so 16.03.2026 is 2026-03-16.

  • The rates are generic flat example rates and are not any country’s rules: employee social contributions 20.00 percent of gross pay, income tax 15.00 percent of gross pay minus the social contributions, and employer contributions 21.00 percent of gross pay. Ana’s March 2026 payslip with these rates is the one of the reference pages: gross 4,000.00, social contributions 800.00, tax 480.00, net 2,720.00 and employer contributions 840.00.

  • Ben’s five days of unpaid leave, Monday 16.03.2026 to Friday 20.03.2026, and the general period working time of 21 days are the example of Partial Periods and Retroactive Accounting; the 21 days are an invented average. The voluntary deduction, a canteen card of 25.00 EUR a month, is also invented, and so is the idea that Ben has it.

  • Taken from SAP pages that were read: the formula of the partial period factor, the three methods and their divisors (the SAP Help pages Partial Period Factor, PWS Method, Payment Method and Deduction Method) and the order from gross to net with deductions after net (Payroll Basics). The model’s own, not SAP’s: the tables and the action calculate, the rounding rule, the counting of working days (Monday to Friday, public holidays ignored, as on the reference page), the payslip line texts and the way a hire or a leaving inside the month is treated as days that are not paid. The hybrid and the all-or-nothing method are left out. A real SAP system applies the factor in a payroll schema, which this model does not imitate.

  • The figures are drawings of the editor, the terminal and the Fiori pages, not screenshots. A highlighted box with a number marks the file, the line or the page part of the step with the same number. A figure leaves out the blank lines of a log.

Steps

Create the project and model the payroll data

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

    cds init payroll-period --nodejs
    cd payroll-period
    npm install
  2. Create db/schema.cds. PayrollAreas holds the general period working time, the divisor of two of the methods. Employees holds the monthly basic pay, Rates the flat percentages (20.00 means 20 percent), Absences the unpaid leave of an employee and VoluntaryDeductions fixed amounts that are taken from the net pay. Payslips and PayslipLines store each calculated payslip as it was calculated, so a later change of a rate cannot rewrite an old payslip.

    namespace sap.guide.payroll;
    
    // A teaching model of one payroll calculation, not SAP S/4HANA, not SAP HCM and
    // not SAP Payroll. Names, rates, numbers and dates are invented example values.
    entity PayrollAreas {
      key Code           : String(2);
      Text               : String(40);
      GeneralWorkingDays : Integer; // the divisor of the payment and deduction methods
    }
    
    entity Employees {
      key PersonnelNumber : String(8);
      Name                : String(40);
      PayrollArea         : String(2);
      MonthlyBasicPay     : Decimal(9,2);
    }
    
    // Flat example rates, not the rules of any country. Percent 20.00 is 20 percent.
    entity Rates {
      key Code : String(10);
      Text     : String(40);
      Percent  : Decimal(5,2);
    }
    
    // Unpaid leave of an employee, from the first to the last day (both inclusive).
    entity Absences {
      key Employee  : Association to Employees;
      key BeginDate : Date;
      EndDate       : Date;
      Kind          : String(20);
    }
    
    // A fixed amount taken from the net pay each month. An invented example.
    entity VoluntaryDeductions {
      key Employee : Association to Employees;
      key Code     : String(10);
      Text         : String(40);
      Amount       : Decimal(9,2);
    }
    
    // One calculated payslip, a snapshot: the name and the numbers stay as they were.
    entity Payslips {
      key Number      : Integer;
      PersonnelNumber : String(8);
      EmployeeName    : String(40);
      Period         : String(7);   // YYYY-MM
      FromDate       : Date;        // first day paid inside the period
      ToDate         : Date;        // last day paid inside the period
      Method         : String(10);  // PWS, PAYMENT or DEDUCTION
      PlannedDays    : Integer;
      AbsentDays     : Integer;
      DivisorDays    : Integer;
      Numerator      : Integer;
      Factor         : Decimal(7,4);
      BasicPay       : Decimal(9,2);
      GrossPay       : Decimal(9,2);
      SocialEmployee : Decimal(9,2);
      IncomeTax      : Decimal(9,2);
      NetPay         : Decimal(9,2);
      Voluntary      : Decimal(9,2);
      Payment        : Decimal(9,2);
      SocialEmployer : Decimal(9,2);
      EmployerCost   : Decimal(9,2);
      Lines          : Composition of many PayslipLines on Lines.Payslip = $self;
    }
    
    entity PayslipLines {
      key Payslip : Association to Payslips;
      key Position : Integer;
      Text         : String(60);
      Basis        : String(60);
      Amount       : Decimal(9,2);
    }
    Visual Studio Code with the file db/schema.cds of the payroll-period project: an excerpt with the entity Rates, whose percent field holds 20.00 for 20 percent, and the entity Absences with the employee and the begin date as key and an end date; callout 2 marks the file in the explorer
  3. Create the five CSV files in db/data. They hold the payroll area E1 with 21 general working days, the two employees, the three rates, Ben’s unpaid leave from 2026-03-16 to 2026-03-20 and his canteen card:

    Code,Text,GeneralWorkingDays
    E1,Monthly EX01,21
    PersonnelNumber,Name,PayrollArea,MonthlyBasicPay
    00001234,Ana Torres,E1,4000.00
    00001235,Ben Okoye,E1,2400.00
    Code,Text,Percent
    SOCIAL_EE,Employee social contributions,20.00
    TAX,Income tax,15.00
    SOCIAL_ER,Employer contributions,21.00
    Employee_PersonnelNumber,BeginDate,EndDate,Kind
    00001235,2026-03-16,2026-03-20,Unpaid leave
    Employee_PersonnelNumber,Code,Text,Amount
    00001235,CANTEEN,Canteen card,25.00

Write the pay arithmetic

  1. Create srv/pay.js. It holds only arithmetic and has no CAP code, so it can be tested alone. Money is kept as whole cents and a rate as hundredths of a percent (20.00 percent is 2000), so no step uses floating point money. The rounding rule is stated once, in roundDiv: divide and round half up to the whole cent. The factor itself is never rounded; it is a fraction of two whole numbers, and the gross pay is the basic pay times that fraction, rounded once. partialPeriodFactor returns the numerator and the divisor for each method, in working days. Each percentage line of grossToNet is rounded to the cent on its own, and the lines that follow are formed from the rounded ones, so the payslip adds up to the cent.

    // Pay arithmetic of the teaching model. Money is whole cents (integers) and a
    // rate is in hundredths of a percent (20.00 percent is 2000), so no step of
    // the calculation uses floating point money.
    
    // The rounding rule: divide and round half up to the next whole cent.
    // Only values of zero or more are divided here.
    export const roundDiv = (numerator, divisor) =>
      (numerator - (numerator % divisor)) / divisor +
      (2 * (numerator % divisor) >= divisor ? 1 : 0)
    
    // A percentage of an amount in cents, rounded to the cent.
    export const percentOf = (cents, hundredths) => roundDiv(cents * hundredths, 10000)
    
    export const METHODS = ['PWS', 'PAYMENT', 'DEDUCTION']
    
    // The partial period factor as a fraction numerator / divisor, in working days.
    //   planned: working days of the period      absent: days not paid
    //   general: the general period working time of the payroll area
    export function partialPeriodFactor(method, planned, absent, general) {
      switch (method) {
        case 'PWS': return { numerator: planned - absent, divisor: planned }
        case 'PAYMENT': return { numerator: planned - absent, divisor: general }
        case 'DEDUCTION': return { numerator: general - absent, divisor: general }
      }
    }
    
    // Gross pay: the basic pay times the factor, rounded once, to the cent.
    export const grossPay = (basicCents, { numerator, divisor }) =>
      roundDiv(basicCents * numerator, divisor)
    
    // From gross to net. Every line is rounded to the cent on its own; the lines
    // that follow are formed from the rounded ones.
    export function grossToNet(gross, rates, voluntary) {
      const socialEmployee = percentOf(gross, rates.socialEmployee)
      const taxable = gross - socialEmployee
      const incomeTax = percentOf(taxable, rates.incomeTax)
      const netPay = taxable - incomeTax
      const payment = netPay - voluntary
      const socialEmployer = percentOf(gross, rates.socialEmployer)
      return { socialEmployee, taxable, incomeTax, netPay, payment, socialEmployer,
        employerCost: gross + socialEmployer }
    }
    
    // Dates are YYYY-MM-DD strings, handled in UTC so daylight saving time cannot
    // move a day.
    const toDate = (text) => new Date(`${text}T00:00:00Z`)
    export const addDays = (text, days) => {
      const d = toDate(text)
      d.setUTCDate(d.getUTCDate() + days)
      return d.toISOString().slice(0, 10)
    }
    
    // Monday to Friday between two dates, both included. Public holidays are
    // ignored, as on the reference page.
    export function workingDays(from, to) {
      let count = 0
      for (let day = from; day <= to; day = addDays(day, 1)) {
        const weekday = toDate(day).getUTCDay()
        if (weekday !== 0 && weekday !== 6) count++
      }
      return count
    }
    
    // First and last day of a period written YYYY-MM.
    export function periodBounds(period) {
      const [year, month] = period.split('-').map(Number)
      const last = new Date(Date.UTC(year, month, 0)).getUTCDate()
      const end = `${period}-${String(last).padStart(2, '0')}`
      return { begin: `${period}-01`, end }
    }
    
    // The amount of a number of cents as text, with a thousands separator.
    export const money = (cents) =>
      (cents / 100).toLocaleString('en-US', {
        minimumFractionDigits: 2, maximumFractionDigits: 2 })
    
    export const toCents = (amount) => Math.round(Number(amount) * 100)
    export const toAmount = (cents) => cents / 100

    In words, with the planned working days of the period, the days that are not paid and a divisor, the factor is

    and the three methods differ in the divisor and in what the first term is. The PWS method uses the planned days of the period as divisor, the payment method the general period working time, and the deduction method replaces the planned days by the general period working time as well, so that only the absence is deducted. The gross pay is the basic pay times the factor.

    Source: PWS Method, Payment Method and Deduction Method (SAP Help)

    Visual Studio Code with the file srv/pay.js: the excerpt lists the three methods PWS, PAYMENT and DEDUCTION, the function partialPeriodFactor that returns a numerator and a divisor in working days for each method, and the function grossPay that multiplies the basic pay by the fraction and rounds once; callout 4 marks the file in the explorer
  2. Create srv/payroll-service.cds. It exposes the tables read-only and one action, calculate, that takes the personnel number, the period YYYY-MM and the method, and optionally FromDate and ToDate, the days of the month on which the employee is paid:

    using { sap.guide.payroll as db } from '../db/schema';
    
    service PayrollService {
      @readonly entity PayrollAreas        as projection on db.PayrollAreas;
      @readonly entity Employees           as projection on db.Employees;
      @readonly entity Rates               as projection on db.Rates;
      @readonly entity Absences            as projection on db.Absences;
      @readonly entity VoluntaryDeductions as projection on db.VoluntaryDeductions;
      @readonly entity Payslips            as projection on db.Payslips;
      @readonly entity PayslipLines        as projection on db.PayslipLines;
    
      // Calculates one payslip and stores it. FromDate and ToDate are optional: the
      // days of the period in which the employee is paid (a hire or a leaving).
      action calculate(PersonnelNumber : String(8), Period : String(7),
                       Method : String(10), FromDate : Date, ToDate : Date)
        returns Payslips;
    }
  3. Create srv/payroll-service.js. The action first checks its input. It counts the planned working days of the period and the days that are not paid: the working days outside the window FromDate to ToDate (a hire or a leaving inside the month) plus the working days of unpaid leave inside it. It looks up the divisor of the payroll area, forms the fraction and refuses a negative one. It then calculates gross pay and the lines down to the payment in cents, writes the payslip lines (the basic pay, the partial period adjustment as the difference to the gross pay, the deductions and the employer contributions as a note) and stores the payslip under the next number.

    import cds from '@sap/cds'
    import { METHODS, addDays, grossPay, grossToNet, money, partialPeriodFactor,
      periodBounds, toAmount, toCents, workingDays } from './pay.js'
    
    const db = cds.entities('sap.guide.payroll')
    
    export default class PayrollService extends cds.ApplicationService {
      init() {
        this.on('calculate', async (req) => {
          const { PersonnelNumber, Method, Period } = req.data
          if (!METHODS.includes(Method)) {
            return req.error(400, `The method must be one of ${METHODS.join(', ')}`)
          }
          if (!/^\d{4}-(0[1-9]|1[0-2])$/.test(Period)) {
            return req.error(400, 'The period must be written YYYY-MM')
          }
          const employee = await SELECT.one.from(db.Employees)
            .where({ PersonnelNumber })
          if (!employee) return req.error(404, `Employee ${PersonnelNumber} not found`)
    
          const bounds = periodBounds(Period)
          const from = req.data.FromDate ?? bounds.begin
          const to = req.data.ToDate ?? bounds.end
          if (from < bounds.begin || to > bounds.end || from > to) {
            return req.error(400, `The dates must lie inside ${Period}, from before to`)
          }
    
          // Working days of the period, and the days that are not paid: those
          // outside the paid window and those of unpaid leave inside it.
          const planned = workingDays(bounds.begin, bounds.end)
          let absent = workingDays(bounds.begin, addDays(from, -1)) +
            workingDays(addDays(to, 1), bounds.end)
          const leaves = await SELECT.from(db.Absences)
            .where({ Employee_PersonnelNumber: PersonnelNumber })
          for (const leave of leaves) {
            absent += workingDays(
              leave.BeginDate > from ? leave.BeginDate : from,
              leave.EndDate < to ? leave.EndDate : to)
          }
    
          const area = await SELECT.one.from(db.PayrollAreas)
            .where({ Code: employee.PayrollArea })
          const { numerator, divisor } =
            partialPeriodFactor(Method, planned, absent, area.GeneralWorkingDays)
          if (numerator < 0) {
            return req.error(400, 'The partial period factor is negative')
          }
    
          const basic = toCents(employee.MonthlyBasicPay)
          const gross = grossPay(basic, { numerator, divisor })
          const rate = {}
          for (const r of await SELECT.from(db.Rates)) rate[r.Code] = toCents(r.Percent)
          const voluntaryLines = await SELECT.from(db.VoluntaryDeductions)
            .where({ Employee_PersonnelNumber: PersonnelNumber })
          const voluntary = voluntaryLines.reduce((s, v) => s + toCents(v.Amount), 0)
          const pay = grossToNet(gross,
            { socialEmployee: rate.SOCIAL_EE, incomeTax: rate.TAX,
              socialEmployer: rate.SOCIAL_ER }, voluntary)
    
          const factorText = (numerator / divisor).toFixed(4)
          const percent = (code) => `${(rate[code] / 100).toFixed(2)}%`
          const lines = [
            ['Basic pay (monthly)', `${money(basic)}`, basic],
            ['Partial period adjustment', `${numerator} / ${divisor} = ${factorText}`,
              gross - basic],
            ['Gross pay', '', gross],
            ['Employee social contributions',
              `${percent('SOCIAL_EE')} of ${money(gross)}`, -pay.socialEmployee],
            ['Income tax', `${percent('TAX')} of ${money(pay.taxable)}`,
              -pay.incomeTax],
            ['Net pay', '', pay.netPay],
            ...voluntaryLines.map((v) => [`Voluntary: ${v.Text}`, 'fixed per month',
              -toCents(v.Amount)]),
            ['Payment', '', pay.payment],
            ['Employer contributions (not on the payslip)',
              `${percent('SOCIAL_ER')} of ${money(gross)}`, pay.socialEmployer]
          ]
    
          const last = await SELECT.one.from(db.Payslips).columns('max(Number) as n')
          const Number = (last?.n ?? 0) + 1
          await INSERT.into(db.Payslips).entries({
            Number, PersonnelNumber, EmployeeName: employee.Name, Period,
            FromDate: from, ToDate: to, Method, PlannedDays: planned,
            AbsentDays: absent, DivisorDays: divisor, Numerator: numerator,
            Factor: factorText, BasicPay: toAmount(basic), GrossPay: toAmount(gross),
            SocialEmployee: toAmount(pay.socialEmployee),
            IncomeTax: toAmount(pay.incomeTax), NetPay: toAmount(pay.netPay),
            Voluntary: toAmount(voluntary), Payment: toAmount(pay.payment),
            SocialEmployer: toAmount(pay.socialEmployer),
            EmployerCost: toAmount(pay.employerCost),
            Lines: lines.map(([Text, Basis, cents], i) =>
              ({ Position: i + 1, Text, Basis, Amount: toAmount(cents) }))
          })
          return SELECT.one.from(db.Payslips).where({ Number })
        })
    
        return super.init()
      }
    }

    In the notation of the page Wage Types and Payroll Results, the social contributions and the income tax are statutory deductions , and the canteen card is taken after the net amount, so it is a deduction . This model has no deduction that is taken while the net amount is formed, so the third kind is zero:

  4. Check the arithmetic before you serve it. Install the test helper of CAP, add the script test and create test/payroll.test.js. It asserts every amount of this page, in whole cents, and checks that wrong input is rejected:

    npm install --save-dev @cap-js/cds-test
    npm pkg set scripts.test="node --test"
    import cds from '@sap/cds'
    import { test } from 'node:test'
    import assert from 'node:assert'
    import { percentOf, roundDiv, workingDays } from '../srv/pay.js'
    
    const { GET, POST } = cds.test(import.meta.dirname + '/..')
    const base = '/odata/v4/payroll'
    const ANA = '00001234'
    const BEN = '00001235'
    const post = (data) => POST(`${base}/calculate`, data)
    const calculate = async (PersonnelNumber, Method, extra = {}, Period = '2026-03') =>
      (await post({ PersonnelNumber, Period, Method, ...extra })).data
    const rejected = async (data) => {
      try { await post(data); assert.fail('should be rejected') } catch (e) {
        return e.response ?? e
      }
    }
    // Amounts are compared as whole cents, so no floating point error can hide.
    const cents = (amount) => Math.round(Number(amount) * 100)
    
    test('the rounding rule rounds half up to the cent', () => {
      assert.equal(roundDiv(10, 4), 3) // 2.5 rounds up to 3
      assert.equal(roundDiv(9, 4), 2) // 2.25 rounds down to 2
      assert.equal(roundDiv(12, 4), 3) // an exact result stays
      assert.equal(percentOf(10, 1500), 2) // 15.00% of 0.10 is 0.015, so 0.02
      assert.equal(percentOf(185455, 2000), 37091) // 20.00% of 1,854.55
      assert.equal(percentOf(148364, 1500), 22255) // 22,254.6 cents rounds up
    })
    
    test('working days are Monday to Friday, public holidays ignored', () => {
      assert.equal(workingDays('2026-03-01', '2026-03-31'), 22)
      assert.equal(workingDays('2026-02-01', '2026-02-28'), 20)
      assert.equal(workingDays('2025-01-15', '2025-01-31'), 13) // Chloe's first month
      assert.equal(workingDays('2026-03-16', '2026-03-20'), 5)
      assert.equal(workingDays('2026-03-16', '2026-03-15'), 0)
    })
    
    test('a full month gives Ana the payslip of the reference pages', async () => {
      const p = await calculate(ANA, 'PWS')
      assert.equal(p.Number, 1)
      assert.equal(p.PlannedDays, 22)
      assert.equal(p.AbsentDays, 0)
      assert.equal(Number(p.Factor), 1)
      assert.equal(cents(p.GrossPay), 400000)
      assert.equal(cents(p.SocialEmployee), 80000)
      assert.equal(cents(p.IncomeTax), 48000)
      assert.equal(cents(p.NetPay), 272000)
      assert.equal(cents(p.Voluntary), 0)
      assert.equal(cents(p.Payment), 272000)
      assert.equal(cents(p.SocialEmployer), 84000)
      assert.equal(cents(p.EmployerCost), 484000)
    })
    
    test('five unpaid days give three different gross amounts', async () => {
      const pws = await calculate(BEN, 'PWS')
      const payment = await calculate(BEN, 'PAYMENT')
      const deduction = await calculate(BEN, 'DEDUCTION')
      for (const p of [pws, payment, deduction]) {
        assert.equal(p.PlannedDays, 22)
        assert.equal(p.AbsentDays, 5)
        assert.equal(cents(p.BasicPay), 240000)
      }
      assert.deepEqual([pws.Numerator, pws.DivisorDays], [17, 22])
      assert.deepEqual([payment.Numerator, payment.DivisorDays], [17, 21])
      assert.deepEqual([deduction.Numerator, deduction.DivisorDays], [16, 21])
      assert.equal(pws.Factor, '0.7727')
      assert.equal(payment.Factor, '0.8095')
      assert.equal(deduction.Factor, '0.7619')
      assert.equal(cents(pws.GrossPay), 185455)
      assert.equal(cents(payment.GrossPay), 194286)
      assert.equal(cents(deduction.GrossPay), 182857)
    })
    
    test('gross to net for Ben with PWS and a voluntary deduction', async () => {
      const p = await calculate(BEN, 'PWS')
      assert.equal(cents(p.GrossPay), 185455)
      assert.equal(cents(p.SocialEmployee), 37091) // 20.00% of 1,854.55
      assert.equal(cents(p.IncomeTax), 22255) // 15.00% of 1,483.64 = 222.546
      assert.equal(cents(p.NetPay), 126109)
      assert.equal(cents(p.Voluntary), 2500)
      assert.equal(cents(p.Payment), 123609)
      assert.equal(cents(p.SocialEmployer), 38946) // 21.00% of 1,854.55 = 389.4555
      assert.equal(cents(p.EmployerCost), 224401)
    })
    
    test('the stored payslip lines add up from basic pay to payment', async () => {
      const p = await calculate(BEN, 'PWS')
      const url = `${base}/PayslipLines?$filter=Payslip_Number eq ${p.Number}`
      const lines = (await GET(`${url}&$orderby=Position`)).data.value
      assert.deepEqual(lines.map((l) => l.Text), [
        'Basic pay (monthly)', 'Partial period adjustment', 'Gross pay',
        'Employee social contributions', 'Income tax', 'Net pay',
        'Voluntary: Canteen card', 'Payment',
        'Employer contributions (not on the payslip)'])
      const amount = (i) => cents(lines[i].Amount)
      assert.equal(amount(0) + amount(1), amount(2)) // basic + adjustment = gross
      assert.equal(amount(2) + amount(3) + amount(4), amount(5)) // gross - deductions
      assert.equal(amount(5) + amount(6), amount(7)) // net - voluntary = payment
      assert.equal(lines[1].Basis, '17 / 22 = 0.7727')
      assert.equal(lines[3].Basis, '20.00% of 1,854.55')
      assert.equal(amount(1), -54545)
    })
    
    test('without absence the payment method pays above basic pay', async () => {
      const p = await calculate(BEN, 'PAYMENT', {}, '2026-04')
      assert.equal(p.PlannedDays, 22)
      assert.equal(p.AbsentDays, 0)
      assert.equal(cents(p.GrossPay), 251429) // 22 / 21 of 2,400.00
    })
    
    test('a month split in two partial periods adds up only with PWS', async () => {
      const first = { FromDate: '2026-03-01', ToDate: '2026-03-15' }
      const second = { FromDate: '2026-03-16', ToDate: '2026-03-31' }
      const pws = await calculate(BEN, 'PWS', first)
      assert.equal(pws.AbsentDays, 12)
      assert.equal(cents(pws.GrossPay), 109091)
      const payment = await calculate(BEN, 'PAYMENT', first)
      assert.equal(cents(payment.GrossPay), 114286)
      const deduction = await calculate(BEN, 'DEDUCTION', first)
      assert.equal(cents(deduction.GrossPay), 102857)
      const a = await calculate(ANA, 'PWS', first)
      const b = await calculate(ANA, 'PWS', second)
      assert.equal(cents(a.GrossPay), 181818)
      assert.equal(cents(b.GrossPay), 218182)
      assert.equal(cents(a.GrossPay) + cents(b.GrossPay), 400000)
    })
    
    test('wrong input is rejected with a message', async () => {
      const ok = { PersonnelNumber: ANA, Period: '2026-03', Method: 'PWS' }
      let r = await rejected({ ...ok, Method: 'HYBRID' })
      assert.equal(r.status, 400)
      assert.equal(r.data.error.message,
        'The method must be one of PWS, PAYMENT, DEDUCTION')
      r = await rejected({ ...ok, Period: '2026-13' })
      assert.equal(r.data.error.message, 'The period must be written YYYY-MM')
      r = await rejected({ ...ok, PersonnelNumber: '99999999' })
      assert.equal(r.status, 404)
      r = await rejected({ ...ok, ToDate: '2026-04-02' })
      assert.equal(r.data.error.message,
        'The dates must lie inside 2026-03, from before to')
      r = await rejected({ ...ok, Method: 'DEDUCTION',
        FromDate: '2026-03-01', ToDate: '2026-03-01' })
      assert.equal(r.data.error.message, 'The partial period factor is negative')
    })

    Run it. The nine tests pass. The times differ from run to run:

    npm test
    Terminal after npm test in the payroll-period project: the nine tests pass, among them the rounding rule, the working days, the full month of Ana, the three methods for Ben and the rejection of wrong input; the summary reads pass 9 and fail 0; callout 7 marks the command

Calculate payslips

  1. In the terminal, in the project folder, start the server. The log shows the five CSV files loaded and PayrollService served at /odata/v4/payroll with the implementation srv/payroll-service.js:

    cds watch
    Terminal after cds watch in the payroll-period project: the log lists the three model files, loads the five CSV files into an in-memory SQLite database, serves PayrollService at /odata/v4/payroll with the implementation srv/payroll-service.js and ends with server listening on http://localhost:4004; callout 8 marks the command
  2. Create the folder http and in it calc-ana.json, the request for Ana’s March 2026 payslip with the PWS method. Open a second terminal in the project folder and post it. The option --json sets the content type. The answer is the stored payslip. The factor is 1.0000 because Ana has no absence, and the amounts are those of the reference pages: gross 4000.00, social contributions 800.00, income tax 480.00, net 2720.00, payment 2720.00, employer contributions 840.00 and employer cost 4840.00, the gross pay plus the employer contributions:

    {
      "PersonnelNumber": "00001234",
      "Period": "2026-03",
      "Method": "PWS"
    }
    curl -s --json @http/calc-ana.json http://localhost:4004/odata/v4/payroll/calculate
  3. Create http/calc-ben-pws.json, the request for Ben with the same period and method, and post it. Five of the 22 working days of March are unpaid, so the numerator is 17 and the divisor 22:

    {
      "PersonnelNumber": "00001235",
      "Period": "2026-03",
      "Method": "PWS"
    }
    curl -s --json @http/calc-ben-pws.json http://localhost:4004/odata/v4/payroll/calculate

    The answer has AbsentDays 5, Numerator 17, DivisorDays 22 and Factor 0.7727. With the basic pay of 2,400.00 the gross pay is

    The social contributions are 20.00 percent of 1,854.55, which is 370.91. The income tax is 15.00 percent of 1,854.55 - 370.91 = 1,483.64, that is 222.546, which the rounding rule makes 222.55. The net pay is 1,483.64 - 222.55 = 1261.09, and after the canteen card of 25.00 the payment is 1236.09. The employer contributions are 21.00 percent of 1,854.55 = 389.4555, rounded to 389.46, so the employer cost is 2244.01.

    Terminal with two curl commands that calculate a payslip: the answer for Ana Torres has the factor 1.0000, gross 4000.00, net 2720.00 and employer cost 4840.00 (callout 9); the answer for Ben Okoye has 5 days not paid, the fraction 17 over 22, the factor 0.7727, gross 1854.55, net 1261.09, payment 1236.09 and employer cost 2244.01 (callout 10)
  4. Create http/calc-ben-payment.json and http/calc-ben-deduction.json: the same request with the method PAYMENT and with the method DEDUCTION. Post both. The option -o /dev/null hides the long answer and -w prints the status code instead:

    {
      "PersonnelNumber": "00001235",
      "Period": "2026-03",
      "Method": "PAYMENT"
    }
    {
      "PersonnelNumber": "00001235",
      "Period": "2026-03",
      "Method": "DEDUCTION"
    }
    curl -s -o /dev/null -w "HTTP %{http_code}\n" --json @http/calc-ben-payment.json http://localhost:4004/odata/v4/payroll/calculate
    curl -s -o /dev/null -w "HTTP %{http_code}\n" --json @http/calc-ben-deduction.json http://localhost:4004/odata/v4/payroll/calculate
  5. List the four stored payslips. The address is in single quotes, because the shell would otherwise replace $select and $orderby by nothing:

    curl -s 'http://localhost:4004/odata/v4/payroll/Payslips?$select=Number,EmployeeName,Method,Factor,GrossPay,NetPay,Payment&$orderby=Number'

    The same five unpaid days give three different gross amounts: 1854.55 (factor 0.7727, PWS), 1942.86 (0.8095, payment, 2,400.00 times 17 / 21) and 1828.57 (0.7619, deduction, 2,400.00 times 16 / 21). They are the values of the reference page Partial Periods and Retroactive Accounting. The methods differ by up to 114.29 EUR for the same five days, which is why a company agreement has to name the method.

    Terminal with two curl commands that calculate Ben payslips with the payment and the deduction method, each answered with HTTP 200 (callout 11), and a curl command that lists the four stored payslips: Ben gross pay is 1854.55 with PWS, 1942.86 with PAYMENT and 1828.57 with DEDUCTION, and the factors are 0.7727, 0.8095 and 0.7619 (callout 12)

Read the payslip in a Fiori elements page

  1. Create app/annotations.cds. The first part gives the fields their labels. The second builds a list report of payslips and an object page with a section for the calculation and a table with the lines of the payslip:

    using PayrollService as service from '../srv/payroll-service';
    
    annotate service.Payslips with {
      Number          @title : 'Payslip';
      PersonnelNumber @title : 'Personnel Number';
      EmployeeName    @title : 'Name';
      Period          @title : 'Period';
      FromDate        @title : 'Paid From';
      ToDate          @title : 'Paid To';
      Method          @title : 'Method';
      PlannedDays     @title : 'Planned Days';
      AbsentDays      @title : 'Days Not Paid';
      DivisorDays     @title : 'Divisor Days';
      Numerator       @title : 'Numerator';
      Factor          @title : 'Partial Period Factor';
      BasicPay        @title : 'Basic Pay';
      GrossPay        @title : 'Gross Pay';
      NetPay          @title : 'Net Pay';
      Payment         @title : 'Payment';
    };
    annotate service.PayslipLines with {
      Position @title : 'No.';
      Text     @title : 'Line';
      Basis    @title : 'Basis';
      Amount   @title : 'Amount (EUR)';
    };
    
    annotate service.Payslips with @(
      UI.LineItem : [
        { Value : Number }, { Value : EmployeeName }, { Value : Period },
        { Value : Method }, { Value : Factor, Label : 'Factor' }, { Value : GrossPay },
        { Value : NetPay }, { Value : Payment }
      ],
      UI.HeaderInfo : { TypeName : 'Payslip', TypeNamePlural : 'Payslips',
        Title : { Value : EmployeeName } },
      UI.Facets : [
        { $Type : 'UI.ReferenceFacet', Label : 'Calculation', Target : '@UI.FieldGroup#Calculation' },
        { $Type : 'UI.ReferenceFacet', Label : 'Payslip', Target : 'Lines/@UI.LineItem' }
      ],
      UI.FieldGroup #Calculation : { Data : [
        { Value : Period }, { Value : FromDate }, { Value : ToDate },
        { Value : Method }, { Value : PlannedDays }, { Value : AbsentDays },
        { Value : DivisorDays }, { Value : Numerator }, { Value : Factor }
      ] }
    );
    annotate service.PayslipLines with @(
      UI.LineItem : [
        { Value : Position }, { Value : Text }, { Value : Basis }, { Value : Amount }
      ]
    );
  2. Open http://localhost:4004/$fiori-preview/PayrollService/Payslips?sap-language=EN#preview-app. The list report Payslips (4) shows the four payslips with their factor, gross pay, net pay and payment. The entities are read-only, so there is no Create or Delete button.

  3. Click the first payslip of Ben Okoye, number 2. The object page shows the section Calculation (period, the days that were paid, the method, the planned days, the days that were not paid, the divisor, the numerator and the factor) and the table Payslip (9), the payslip of the result figure above. The preview prints the dates as Mar 1, 2026.

    Fiori elements list report Payslips (4) with the columns Payslip, Name, Period, Method, Factor, Gross Pay, Net Pay and Payment: the payslip of Ana Torres has the factor 1.0000 and Ben Okoye has three payslips with PWS, PAYMENT and DEDUCTION; callout 14 marks the table title and callout 15 the first payslip of Ben Okoye

Check the result

  • npm test reports pass 9 and fail 0.

  • Ana’s payslip has the factor 1.0000, gross 4000.00, net 2720.00 and employer cost 4840.00, as on the reference pages.

  • Ben’s three payslips for March 2026 have the gross pay 1854.55, 1942.86 and 1828.57.

  • Ben’s PWS payslip adds up in the table Payslip (9): 2,400.00 - 545.45 = 1,854.55; 1,854.55 - 370.91 - 222.55 = 1,261.09; 1,261.09 - 25.00 = 1,236.09.

Variations

  • Pay only the first half of the month. http/calc-ben-split.json asks for Ben’s payslip with the days from 2026-03-01 to 2026-03-15, as if he were reassigned on 16.03.2026 and the pay had to be split. The 12 working days outside the window count as not paid, so the numerator is 10 and the divisor 22:

    {
      "PersonnelNumber": "00001235",
      "Period": "2026-03",
      "Method": "PWS",
      "FromDate": "2026-03-01",
      "ToDate": "2026-03-15"
    }
    curl -s --json @http/calc-ben-split.json http://localhost:4004/odata/v4/payroll/calculate | grep -oE '"(Number|FromDate|ToDate|AbsentDays|DivisorDays|Numerator|Factor|GrossPay)":("[^"]*"|[0-9]+)'

    The answer lists Number 5, FromDate 2026-03-01, ToDate 2026-03-15, AbsentDays 12, DivisorDays 22, Numerator 10, Factor 0.4545 and GrossPay 1090.91. This is the first partial period of the reference page; with the methods PAYMENT and DEDUCTION the same window gives 1142.86 and 1028.57. Only the PWS method uses the real length of the month as divisor, so only it adds up to the agreed basic pay when both partial periods are paid. The test checks the second half of the month for Ana: 1,818.18 + 2,181.82 = 4,000.00.

  • Pay a long month with no absence under the payment method. http/calc-ben-april-payment.json asks for Ben, April 2026, PAYMENT:

    {
      "PersonnelNumber": "00001235",
      "Period": "2026-04",
      "Method": "PAYMENT"
    }
    curl -s --json @http/calc-ben-april-payment.json http://localhost:4004/odata/v4/payroll/calculate | grep -oE '"(Number|Period|PlannedDays|AbsentDays|Numerator|DivisorDays|Factor|GrossPay)":("[^"]*"|[0-9]+)'

    April 2026 has 22 working days and no absence, so the factor is 22 / 21, 1.0476, and the gross pay is 2514.29, more than the agreed 2,400.00. This is the long-month problem that SAP describes for the payment method.

What can go wrong

Symptom Cause Fix

The method must be one of PWS, PAYMENT, DEDUCTION and HTTP 400

The Method is spelled differently (the model has no HYBRID method) or is missing from the request file.

Use PWS, PAYMENT or DEDUCTION, in capital letters.

The period must be written YYYY-MM and HTTP 400

The Period is 2026-13 or another text that is not a year and a month.

Write the period as 2026-03.

Employee 99999999 not found and HTTP 404

The personnel number is not one of the two in db/data.

Use 00001234 or 00001235.

The dates must lie inside 2026-03, from before to and HTTP 400

FromDate or ToDate lies outside the period, or FromDate is after ToDate.

Give two days of the period, the first not after the second.

The partial period factor is negative and HTTP 400

With the DEDUCTION method the days that are not paid exceed the general period working time of 21 days, for example when the window holds a single Sunday.

Check the dates, or use the PWS or PAYMENT method.

Unsupported Media Type and HTTP 415

The request was sent with -d instead of --json, so curl sent it as a form.

Use --json @http/<file>.json.

Parsing URL failed at position 27 and a long list of expected tokens

The address of the list is in double quotes, so the shell replaced $select and $orderby by nothing.

Put the address in single quotes, as in step 12.

The list has more than four payslips and their numbers do not start at 1

Each calculate stores a new payslip, and the variations add more.

Stop cds watch and start it again: the database is in memory and begins with no payslip.

Clean up

Press Ctrl+C in the terminal that runs cds watch. The database lives only in memory, so the payslips are gone at the next start; the CSV files bring back the starting data.