MSBA-272 · Lesson 12 of 12 · 19 min

Case study: a pricing engine plug-in

▶ Video coming soon A video version of this lesson is on the way.

The final sessions of the term brought everything together in one piece of work. Lumenvale's Continuing Education unit, based at Ridgeview, runs non-credit evening and weekend courses for the public, from bookkeeping to welding refreshers. Registrations were recorded in the Course Registration and Course Offering tables of the registration app that Signe had built the previous year. Prices, though, were worked out by hand. Coordinators applied discounts from a laminated sheet beside the phone, and the analysis Kwabena Asante-Lowe did for the Continuing Education profitability model in MSBA-261 had shown the same course sold at five different prices in one term, not all of them intended.

The unit's manager asked central IT for a pricing engine: one place where the rules lived, applied the same way whether a coordinator took a registration by phone, a student registered online through the app, or an employer sent a list of staff. Signe made it Wiremu's capstone, with herself as reviewer, Maribeth as tester and Rupert as approver. Everything in this lesson was built and tested in Wiremu's developer environment; production was planned for January, after the design review.

The rules

The first job was to get the rules out of the laminated sheet and into words everyone agreed on. After two conversations with the unit's coordinators, Wiremu wrote them down, and the manager signed them off.

Continuing Education discount rules agreed for the pricing engine. Rates are stored as data, not in code.
RuleConditionDiscount
Early birdRegistration at least 21 days before the course starts10 percent
AlumniThe student is a Lumenvale graduate, confirmed on their contact record15 percent
Employer sponsoredThe registration is paid by an employer with a current agreement20 percent, or the agreement's own rate
SeniorThe student holds senior status, confirmed by registration staff25 percent

Two combination rules mattered more than the discounts themselves. Only one of alumni, employer sponsored and senior applies, whichever gives the student the lowest price. Early bird combines with that one discount, applied after it. And some courses, marked as fixed price, take no discounts at all, because they are run at cost with partner organizations.

Signe asked one question about the senior rule that changed the design. Was the plug-in going to work out age from a date of birth? The Date of Birth column was secured and Dr. Philippa Ondaatje-Ruiz had been firm about it in MSBA-130. The answer was no: registration staff checked eligibility and set a Senior status flag on the contact, and the engine read only the flag. The pricing engine never needed to see anyone's date of birth.

The design

Wiremu's design used every tool from the course in its proper place. A new table, Pricing Rule, held the discount rules with their rates, effective dates and a priority, so the unit could change rates and add rules for a term without a developer. A shared class, PricingEngine, held the logic and nothing else. A synchronous plug-in, PriceRegistration, set the price on a Course Registration row when it was created or when a column that affected the price changed. A custom API, lcc_QuoteCourseFee, gave the same answer to anyone who asked before registering, such as the registration app showing a price as a student filled in the form.

An architecture diagram. At the centre is a PricingEngine class. Above it, a PriceRegistration plug-in on Create and Update of Course Registration in PreOperation, and a custom API lcc_QuoteCourseFee, both call the engine. The engine reads the Pricing Rule and Course Offering tables and the contact's alumni and senior flags. On the left, callers: the registration app, a coordinator form and an employer bulk import. On the right, a note: unit tests on PricingEngine run in GitHub Actions.
The pricing engine design.
Design decisions, with the lessons they draw on.
ComponentChoiceLesson
PriceRegistration stepCreate and Update of lcc_courseregistration; PreOperation; synchronous; filtering attributes for offering, contact, registration date and sponsor; pre-image "pre"1, 2
DeploymentPlug-in package in the Continuing Education solution2
DiagnosticsStructured traces with IDs, rule names and amounts, no personal data3
lcc_QuoteCourseFeeUnbound function; inputs OfferingId, ContactId, RegistrationDate, SponsorId (optional); outputs Price, Discounts; no execute privilege; no steps allowed4
PerformanceOne query for the offering, one for active rules; registered also on UpdateMultiple for the employer import (planned)10
ErrorsPlain messages for missing data; consistent API errors11

Wiremu had considered an automated low-code plug-in for the first version, since the rules were arithmetic. Signe agreed it could express them, but the guidance from lesson 9 settled it: pricing was production-critical, it needed unit tests and review in source control, and the same logic had to serve a custom API. C# it was.

The Pricing Rule table

The rule table carried most of the design's flexibility, so Wiremu took care over it. Each row had a name that coordinators would recognize, a group (Status for alumni, employer sponsored and senior; Timing for early bird), a rate stored as a fraction, effective from and effective to dates using the Date only behaviour that lesson 3 had shown to be necessary, and an active flag. Early bird had one extra column for the number of days before the start date. Employer agreements lived in their own small table linked to the employer's account, with an optional rate that, when present, replaced the standard employer sponsored rate for that employer.

Signe asked how the unit would run a promotion, such as a lower early-bird threshold for one January intake. The answer showed the value of keeping rules as data: the administrator would add a second early-bird row with its own dates and days, and the engine would apply whichever active timing rule gave the larger discount, a behaviour covered by a unit test. No code change and no deployment would be needed for a seasonal promotion, which was exactly what the unit's manager had hoped for.

Auditing was turned on for the Pricing Rule table, so every change to a rate recorded who made it and when. Kwabena added a page to the Continuing Education report showing revenue and discounts by rule, so the manager could see what each promotion actually cost.

The engine

PricingEngine took everything it needed as parameters: the offering's base fee and fixed-price flag, the registration date, the course start date, the student's alumni and senior flags, the sponsor's agreement rate if any, and the list of active rules. It returned the price and a short description of the discounts applied. It did no queries and knew nothing about Dataverse, which made it easy to test.

The core of PricingEngine. Rates are stored as fractions in the Pricing Rule table; rounding to cents happens once, at the end.
public PriceResult Calculate(PriceInput input, IReadOnlyList<PricingRule> rules)
{
    if (input.FixedPrice)
        return PriceResult.NoDiscount(input.BaseFee, "Fixed-price course");

    // Best single discount among alumni, sponsor and senior
    decimal best = 0m; string bestName = null;
    foreach (var rule in rules.Where(r => r.Group == RuleGroup.Status && r.AppliesTo(input)))
    {
        decimal rate = rule.RateFor(input);
        if (rate > best) { best = rate; bestName = rule.Name; }
    }

    decimal price = input.BaseFee * (1m - best);
    var applied = new List<string>();
    if (bestName != null) applied.Add(bestName);

    var early = rules.Where(r => r.Group == RuleGroup.Timing && r.AppliesTo(input))
                     .OrderByDescending(r => r.RateFor(input))
                     .FirstOrDefault();
    if (early != null)
    {
        price = price * (1m - early.RateFor(input));
        applied.Add(early.Name);
    }

    price = Math.Round(price, 2, MidpointRounding.AwayFromZero);
    return new PriceResult(price, applied);
}

Signe's review comments were small but pointed. Rounding should happen once, at the end, as it did; rounding after each discount would make prices differ by a cent depending on the order rules were applied. The rounding mode should be written down and agreed with finance, which it was: half away from zero, matching LedgerPoint. And the engine should never return a negative price, so a guard went in for misconfigured rules, with a test.

Worked problem

Pricing one registration

A Lumenvale graduate registers for a bookkeeping course with a base fee of 240.00, thirty days before it starts. Their employer does not sponsor them, and they do not hold senior status. What price does the engine set?

Show solution
  1. The course is not fixed price, so discounts apply.
  2. Among the status discounts, only alumni applies, at 15 percent: 240.00 times 0.85 is 204.00.
  3. The registration is at least 21 days before the start, so early bird applies after it, at 10 percent: 204.00 times 0.90 is 183.60.
  4. Round once to cents: 183.60.

Answer: The price is 183.60, with Alumni and Early bird listed as the discounts applied.

The plug-in and the API

With the engine done, the plug-in and the API were short. PriceRegistration read the Target and pre-image to find the offering, contact, registration date and sponsor, retrieved the offering's base fee and start date and the contact's two flags with narrow queries, retrieved the active pricing rules, called the engine, and set the price and the discount description on the Target. It skipped the calculation when none of the inputs had changed, and it threw a plain InvalidPluginExecutionException if the offering had no base fee, telling the coordinator to ask the unit's administrator to set one.

lcc_QuoteCourseFee did the same reads from its parameters and returned the price without writing anything. The registration app called it as a student filled in the form, so the price on screen was the price the plug-in would set when the registration was saved. Maribeth tested exactly that: forty combinations of offering, student and date, quoted through the app and then saved, with the two numbers compared. All forty matched.

Testing

The engine had 38 unit tests by the end, covering each rule alone, each combination, fixed-price courses, boundary dates such as a registration exactly 21 days before the start, the time zone case from lesson 3, missing rules and the negative-price guard. They ran in GitHub Actions on every pull request. The plug-in and API had a handful of tests each with a fake context, and Maribeth's forty end-to-end cases were written up as a test script for the coordinators to repeat in Continuing Education Test after deployment.

Wiremu also tested the employer import path. An employer list of 60 staff, created through CreateMultiple in his environment, priced every row correctly and took a few seconds. The plug-in was registered on Create, so it ran once per row; registering it on the bulk message to read the rules once per batch was recorded as an improvement for later, since the volumes did not yet justify the change.

The design review

The review used the format from MSBA-270. Wiremu presented the rules, the design, the test results and the risks. Signe asked about the rule table: who could change it, and what happened if a coordinator entered 150 instead of 0.15? The answer was a security role that limited editing to the unit's administrator, a business rule on the form and a check in the engine that rejected rates outside zero to one. Rupert asked about deployment and rollback: the Continuing Education solution would go through the pipeline, and if prices looked wrong after go-live, deactivating the step would stop automatic pricing and coordinators could return to the sheet while it was fixed. Dr. Ondaatje-Ruiz confirmed that no date of birth was read and no personal data appeared in traces.

The decision was to approve the pricing engine for production in January, before winter registrations opened, with the unit's administrator trained to maintain the rule table. Until then it stayed in Wiremu's developer environment, with a copy of the solution in Continuing Education Test for the coordinators to try.

A bar chart of test counts by layer: 38 engine unit tests, 9 plug-in and API tests with a fake context, and 40 end-to-end quote-and-save comparisons, all passing.
Tests for the pricing engine, by layer.

Handing over to the unit

A pricing engine that only central IT understood would recreate the problem it was meant to solve, so the handover mattered as much as the code. Wiremu wrote a two-page runbook for the unit's administrator: how to add, end and correct a rule; what each column meant; how to check a price by using the quote in the registration app; and whom to contact if a price looked wrong. Maribeth, who had trained registrar staff on the transcript solution, ran a short session with the administrator and two coordinators in Continuing Education Test, where they changed rates, ran a promotion and broke a rule deliberately to see the validation messages.

The runbook also said what the administrator should not do. Deleting a rule row would lose its history, so rules were ended by setting an effective to date instead. And no one outside central IT would change the PriceRegistration step, the engine or the custom API; those changed only through pull requests and the pipeline, like every other piece of Lumenvale code.

What the course covered

Looking back over the sessions, Signe listed what Wiremu could now do that he could not in September: write and register plug-ins in packages, choose stages and modes, debug with traces and the profiler, define and secure custom APIs, call prompts from code safely, build custom connectors with the right authentication, policies and code, judge when low-code plug-ins and functions fit, design for limits, and handle errors so users and developers both know what happened. These topics make up most of the "extend the platform" domain of Exam AB-400, which Microsoft weights at 35 to 40 percent of the exam, plus parts of the integration domain. Signe planned to sit AB-400 in January; Wiremu thought he might follow in the spring.

Common mistakes

  • MistakeCalculating eligibility from secured personal data inside the plug-in.

    InsteadRead a status flag that staff set after checking eligibility.

  • MistakeRounding after each discount.

    InsteadRound once at the end, with an agreed rounding mode.

  • MistakeHard-coding discount rates.

    InsteadStore them in a rule table with effective dates and validation.

  • MistakeWriting separate logic for the quote and for the saved price.

    InsteadCall one engine from both the plug-in and the custom API.

  • MistakeGoing live without a way to stop automatic pricing.

    InsteadPlan rollback, such as deactivating the step, before deployment.

Summary and key terms

  • The pricing engine separated rules (a Pricing Rule table), logic (a PricingEngine class) and integration (a plug-in and a custom API).
  • The plug-in set prices in PreOperation on Create and Update with filtering attributes; the custom API returned the same price as a quote.
  • Personal data was avoided by reading eligibility flags rather than dates of birth; traces held IDs and amounts only.
  • Unit tests covered rules, combinations, boundaries and rounding; end-to-end tests compared quotes with saved prices.
  • The design review approved production for January with training, validation of the rule table and a rollback plan.
Pricing engine
A component that applies pricing rules consistently wherever a price is needed.
Rule table
A Dataverse table holding business rules as data that administrators can maintain.
Rounding mode
The agreed method for rounding amounts, such as half away from zero.
Rollback plan
The steps to undo or disable a change if it misbehaves after deployment.

Practice problems

Work each problem on paper first, then reveal the answer to check.

  1. Why did the engine take all inputs as parameters and make no queries?

    Show answer

    So it could be unit tested without Dataverse and reused by the plug-in and API.

  2. What is the price of a 300.00 course for a senior registering 30 days ahead?

    Show answer

    300.00 times 0.75 is 225.00; times 0.90 is 202.50.

  3. How could Lumenvale stop automatic pricing quickly if prices were wrong?

    Show answer

    Deactivate the PriceRegistration step.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz