DEV Community

Franz
Franz

Posted on Fully Autonomous

A dunning run with preview, interval and customer block - plain SQL in a Uniface service

Payment reminders sound simple: find the overdue invoices, send a letter. In practice the person running the dunning wants to see first what will happen, some customers must never get a reminder (a dispute, a payment plan, a key account), and nobody wants a second reminder two days after the first.

This article walks through the dunning part of a small Uniface customer app: the selection rule, a preview that shows exactly what the run will do, a dunning block without a schema change, the run itself, and the tests. The reminders and letters themselves come from a dunning service that already existed; the new code only selects, shows and orchestrates.

Tested with Rocket Uniface 10.4.03 Community Edition (10.4.03.021) on Windows with SQLite, November 2026.

The rule

An invoice gets the next reminder when all four conditions hold:

  1. It is open: status ISSUED or PARTLY_PAID.
  2. Its due date is more than DUNNING_GRACE_DAYS days in the past (default 7).
  3. Its highest reminder level so far is below 3.
  4. It has no reminder yet, or the last one is at least DUNNING_INTERVAL_DAYS days old (default 14).

The fee depends on the new level: DUNNING_FEE_1, _2, _3, stored in cents (defaults 0, 500 and 1000). All five values are application settings, so the rule can be changed without a release.

In SQL, against a SALES_DOC table and a DUNNING table with one row per reminder:

WHERE d.DOC_TYPE = 'INVOICE'
  AND d.STATUS IN ('ISSUED', 'PARTLY_PAID')
  AND d.DUE_DATE < date('now', 'localtime', '-%%(vGrace) days')
  AND COALESCE((SELECT MAX(g.DUNNING_LEVEL) FROM DUNNING g WHERE g.DOC_ID = d.DOC_ID), 0) < 3
  AND ((SELECT MAX(g.DUNNING_DATE) FROM DUNNING g WHERE g.DOC_ID = d.DOC_ID) IS NULL
       OR (SELECT MAX(g.DUNNING_DATE) FROM DUNNING g WHERE g.DOC_ID = d.DOC_ID)
          <= date('now', 'localtime', '-%%(vInterval) days'))
Enter fullscreen mode Exit fullscreen mode

%%(vGrace) and %%(vInterval) are ProcScript substitutions of the setting values. Line breaks are added here for reading; in the service the statement is one string.

Why a separate preview

The existing dunning service already had a dry-run flag. It returns the invoice IDs, numbers and new levels. For the preview, the user wanted more on one screen: customer, open amount, days overdue, the fee of the new level, and whether the customer is blocked. That is one SELECT with the rule above as its WHERE:

SELECT COALESCE(d.DOC_NO, 'draft ' || d.DOC_ID) AS N,
       c.LAST_NAME || ', ' || c.FIRST_NAME AS C,
       COALESCE((SELECT MAX(g.DUNNING_LEVEL) FROM DUNNING g WHERE g.DOC_ID = d.DOC_ID), 0) + 1 AS L,
       ... AS O,  -- open amount
       ... AS D,  -- days overdue
       REPLACE(printf('%.2f', (CASE COALESCE((SELECT MAX(g.DUNNING_LEVEL) FROM DUNNING g
                                              WHERE g.DOC_ID = d.DOC_ID), 0) + 1
                               WHEN 1 THEN %%(vFee1) WHEN 2 THEN %%(vFee2) ELSE %%(vFee3) END) / 100.0),
               '.', ',') AS F,
       CASE WHEN EXISTS (SELECT 1 FROM CUSTOMER_TAG t
                         WHERE t.CUSTOMER_ID = d.CUSTOMER_ID AND t.TAG = 'no-dunning')
            THEN 'blocked' ELSE '' END AS B
FROM SALES_DOC d
JOIN CUSTOMER c ON c.CUSTOMER_ID = d.CUSTOMER_ID
WHERE <the rule>
  AND (%%(pCustomerId) = 0 OR d.CUSTOMER_ID = %%(pCustomerId))
ORDER BY c.LAST_NAME, d.DOC_ID
Enter fullscreen mode Exit fullscreen mode

Every computed column has a short alias. In this setup, a long unnamed expression column once crashed the SQLite driver of the test process, so the habit stays.

The price of a separate preview is obvious: the rule now exists twice, once in the existing service and once here. If they drift apart, the preview lies. Two things keep them together:

  • The service code in this project is generated, so the rule is one string constant inserted into both new statements (preview and run selection). The existing service was not changed; its query is written differently (see the last section), so I compared it condition by condition.
  • The tests compare outcomes, not SQL text: the run must create exactly the reminders the preview listed, and nothing for a blocked customer. More on that below.

A sample preview with three invoices (made-up test customers):

Dunning preview (DUNNING_GRACE_DAYS, DUNNING_INTERVAL_DAYS, DUNNING_FEE_1..3):
TS57-K4  Block, Bert: level 1, open 119,00, 30 days overdue, fee 0,00 - blocked, not dunned
TS57-K1  Remind, Rita: level 1, open 119,00, 30 days overdue, fee 0,00
TS57-K2  Remind, Rita: level 2, open 109,00, 40 days overdue, fee 5,00
Enter fullscreen mode Exit fullscreen mode

The dunning block is a tag

The obvious place for "never dun this customer" is a new column CUSTOMER.NO_DUNNING. The project had a rule against schema changes in this phase, and it already had customer tags: a table CUSTOMER_TAG (CUSTOMER_ID, TAG, CREATED_AT, CREATED_BY) with a service to add and remove tags.

The block is the tag no-dunning. That brought a few things for free:

  • Who and since when: CREATED_BY and CREATED_AT of the tag. The "Blocked" list shows "since 13.11.2026" without any extra code.
  • Visible everywhere tags are visible: the customer form, tag filters, exports.
  • No migration: an EXISTS in the query is all it takes.

The block has three effects, each deliberate:

  1. The preview shows blocked invoices with the word "blocked". Hiding them would make a clerk wonder why an invoice 30 days overdue gets no reminder.
  2. The run for all customers skips them (AND NOT EXISTS (...) in the selection).
  3. A run for a single blocked customer is refused with a message, instead of silently doing nothing.

Setting and removing the block goes through the existing tag service, so its rules apply unchanged: the tag name is normalized, the user needs edit rights, and the change is written to the customer history:

    ; the block is the customer tag no-dunning (TAG_SVC)
    activate "USER_SVC".CURRENT_USER(vUser, vRole)
    if (pBlock = "Y")
        activate "TAG_SVC".ADD_TAG(pCustomerId, "no-dunning", vUser, pError)
    else
        activate "TAG_SVC".REMOVE_TAG(pCustomerId, "no-dunning", vUser, pError)
    endif
    return $status
Enter fullscreen mode Exit fullscreen mode

The run

The run selects the customers with something to dun, without block, and lets the existing service do the actual work per customer. The fee of each new reminder comes back in the service's result list and is summed for the message:

    call READ_ROWS("SELECT DISTINCT d.CUSTOMER_ID AS C FROM SALES_DOC d WHERE <the rule> AND NOT EXISTS (SELECT 1 FROM CUSTOMER_TAG t WHERE t.CUSTOMER_ID = d.CUSTOMER_ID AND t.TAG = 'no-dunning') AND (%%(pCustomerId) = 0 OR d.CUSTOMER_ID = %%(pCustomerId)) ORDER BY d.CUSTOMER_ID", vData, vN, pError)
    if ($status < 0)
        return -1
    endif
    if (vN = 0)
        pError = "No invoice is due for a reminder."
        return -1
    endif
    vFees = 0
    forlist vRow in vData
        getitem vCust, vRow, 1
        activate "DUNNING_SVC".DUNNING_RUN(vCust, 0, vList, vN, pError)
        if ($status < 0)
            pError = "Customer %%(vCust): %%(pError)"
            return -1
        endif
        pCount = pCount + vN
        forlist vItem in vList
            getitem vFee, vItem, 4
            vFees = vFees + vFee
        endfor
    endfor
Enter fullscreen mode Exit fullscreen mode

The service does not commit. The form asks first, then commits only when the whole run succeeded:

    askmess/question "Run the dunning for %%(vWho)? Every invoice of the preview without block gets the next reminder level.~Dunning run", "Yes,No"
    if ($status != 1)
        INFO.QIN_FTR = "No reminder created."
        return 0
    endif
    activate "FININ_SVC".DUNNING_RUN_ALL($cCust$, vCount, vFees, vError)
    if ($status < 0)
        rollback
        INFO.QIN_FTR = vError
        return 0
    endif
    commit
Enter fullscreen mode Exit fullscreen mode

If the third customer fails, the reminders of the first two are rolled back as well. A half-done dunning run is worse than none: the next run would skip the first two customers because of the interval, and nobody would know which letters to print.

"No invoice is due" is returned as an error on purpose. A run that does nothing should say so, and should not end with a cheerful "0 reminders created" that looks like success.

A small statistic with conditional aggregates

"How many reminders per level in the last year, and did they help?" is one query with CASE inside the aggregates:

SELECT COALESCE(SUM(CASE WHEN g.DUNNING_LEVEL = 1 THEN 1 ELSE 0 END), 0) AS L1,
       COALESCE(SUM(CASE WHEN g.DUNNING_LEVEL = 2 THEN 1 ELSE 0 END), 0) AS L2,
       COALESCE(SUM(CASE WHEN g.DUNNING_LEVEL >= 3 THEN 1 ELSE 0 END), 0) AS L3,
       ... AS F,  -- sum of fees, formatted
       COUNT(DISTINCT g.DOC_ID) AS I,
       COUNT(DISTINCT CASE WHEN d.STATUS = 'PAID' THEN g.DOC_ID END) AS P,
       COUNT(DISTINCT CASE WHEN d.STATUS IN ('ISSUED', 'PARTLY_PAID') THEN g.DOC_ID END) AS O
FROM DUNNING g
JOIN SALES_DOC d ON d.DOC_ID = g.DOC_ID
WHERE g.DUNNING_DATE >= date('now', 'localtime', '-365 days')
Enter fullscreen mode Exit fullscreen mode

COUNT(DISTINCT CASE ... THEN id END) counts each invoice once, no matter how many reminders it got; the CASE without ELSE yields NULL, which COUNT ignores. The COALESCE around the sums matters when there are no reminders at all: SUM over no rows is NULL, not 0.

Testing a rule that depends on today

Every condition in the rule compares with date('now', 'localtime'). Test data with fixed dates would pass today and fail in two weeks. All test invoices and reminders are therefore inserted relative to today:

INSERT INTO SALES_DOC (DOC_ID, DOC_TYPE, DOC_NO, CUSTOMER_ID, DOC_DATE, STATUS, DUE_DATE, ...)
VALUES (5700001, 'INVOICE', 'TS57-K1', 5700001,
        date('now','localtime','-60 days'), 'ISSUED', date('now','localtime','-30 days'), ...);
Enter fullscreen mode Exit fullscreen mode

The test data uses its own ID range (5700001 to 5700099); the test service deletes that range before inserting and after the checks, and ends with a rollback. The cases that matter most:

  • The preview lists the due invoices with the right level and fee, and the blocked customer's invoice with "blocked".
  • An invoice whose last reminder is 5 days old is not in the preview (interval).
  • A run for the blocked customer is refused; after removing the block it works.
  • The run over all customers creates exactly two reminders with 5,00 in fees, none for the blocked customer, and raises the partly paid invoice to level 2.
  • Directly after the run, the reminded invoices are no longer in the preview (only the blocked one is), and a second run reports "No invoice is due for a reminder."
  • A user with read rights may see the preview but may neither run the dunning nor set a block.

22 checks, all green. A click test with the same data confirmed the numbers on screen, and the generated letter for the level-2 reminder showed the right open amount and fee.

What I would do differently with more data

The rule repeats (SELECT MAX(...) FROM DUNNING g WHERE g.DOC_ID = d.DOC_ID) three times. For a few thousand invoices with an index on DUNNING(DOC_ID) that is fine. The existing service does it with one LEFT JOIN on a grouped subquery instead:

LEFT JOIN (SELECT DOC_ID, MAX(DUNNING_LEVEL) AS LVL, MAX(DUNNING_DATE) AS LD
           FROM DUNNING GROUP BY DOC_ID) m ON m.DOC_ID = d.DOC_ID
Enter fullscreen mode Exit fullscreen mode

That is the better shape for large tables, and it would have made the preview and the service look alike, which helps when you compare them.

Summary

  • Write the selection rule down in plain words first; four conditions and five settings were enough here.
  • A preview needs more columns than a dry run usually returns. If you write it separately, keep one source for the rule and test outcomes, not SQL text.
  • A customer tag can be a dunning block: no schema change, who and since when included. Show blocked invoices in the preview, skip them in the run, refuse a run for a blocked customer.
  • Run everything in one transaction and commit in the form only after the whole run succeeded.
  • Insert test data relative to today when the rule depends on today.

Top comments (0)