sales.commission
What commission has this salesperson earned?
POST the call — JSON in, JSON out, pinned to this versionPAGE the same formula as one screen, for somebody who wants the answer
What it does
A two-tier plan, which is the commonest shape there is: **3% on everything up to the target, 5% on everything beyond it.** The accelerator above target is the whole point of such a plan — it pays more for the sale that was hard to get than for the one that was always going to happen.
The two tiers are reported separately, because "why is my commission that number" is the question this calculation exists to answer, and a single total does not answer it. `effectiveRate` is the blended percentage actually earned, which is the number a salesperson compares against the plan they were sold.
Call it
One request, JSON in, JSON out. Each example is filled in with the formula's own first case, so it answers as it stands.
curl
curl -X POST 'https://ofi.dev/@stdlib/sales.commission@1.0.0/call' \ -H 'Content-Type: application/json' \ -d '{"sales":80000,"target":100000}' # the same call as a URL, which is linkable and cacheable curl 'https://ofi.dev/@stdlib/sales.commission@1.0.0/call?sales=80000&target=100000'
JavaScript
const response = await fetch('https://ofi.dev/@stdlib/sales.commission@1.0.0/call', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ "sales": 80000, "target": 100000 }) }); const answer = await response.json(); if (!response.ok) throw new Error(answer.message); // 422 carries kind, path, field, label console.log(answer);
Python
import json, urllib.error, urllib.request request = urllib.request.Request( 'https://ofi.dev/@stdlib/sales.commission@1.0.0/call', data=json.dumps({'sales': 80000, 'target': 100000}).encode(), headers={'Content-Type': 'application/json'}, ) try: with urllib.request.urlopen(request) as response: print(json.load(response)) except urllib.error.HTTPError as refusal: print(refusal.code, json.load(refusal))
Ruby
require 'json' require 'net/http' response = Net::HTTP.post( URI('https://ofi.dev/@stdlib/sales.commission@1.0.0/call'), JSON.generate({ 'sales' => 80000, 'target' => 100000 }), 'Content-Type' => 'application/json' ) answer = JSON.parse(response.body) raise answer['message'] unless response.code == '200' pp answer
A refusal comes back as 422, naming the field that caused it.
It proves itself5 / 5
5 cases, named in business language. The build does not produce this page unless every one of them passes, and the answers below are the compiled formula's rather than a transcription.
Short of target, so the base rate only
Try itsales 80000target 100000→commission 2400targetReached falseuptoTarget 2400beyondTarget 0effectiveRate 3Exactly on target, where the accelerator has not started yet
Try itsales 100000target 100000→commission 3000targetReached trueuptoTarget 3000beyondTarget 0effectiveRate 3Over target, where the better rate is worth having
Try itsales 120000target 100000→commission 4000targetReached trueuptoTarget 3000beyondTarget 1000effectiveRate 3.33A month with no sales at all
Try itsales 0target 100000→commission 0targetReached falseuptoTarget 0beyondTarget 0effectiveRate 0Double the target, where most of the pay is the accelerator
Try itsales 200000target 100000→commission 8000targetReached trueuptoTarget 3000beyondTarget 5000effectiveRate 4
What it refuses4 / 4
A refusal is correct behaviour, so it is specified too. Each of these raises the failure the bundle wrote down — try one and watch the message land on the field that caused it.
A negative sales figure, which is a correction and not a sale
Try itsales -500target 100000→A target of zero, which no accelerator can be measured against
Try itsales 50000target 0→Sales written the way people say them
Try itsales 80ktarget 100000→No target given, so there is no plan to apply
Try itsales 80000target missing→
The function
This is the whole of it. There is no other copy: the endpoint above runs this program, and the cases were run against its compilation during the build.
formula.elo
# What commission has this salesperson earned?## A two-tier plan, which is the commonest shape there is: **3% on everything up# to the target, 5% on everything beyond it.** The accelerator above target is# the whole point of such a plan — it pays more for the sale that was hard to# get than for the one that was always going to happen.## The two tiers are reported separately, because "why is my commission that# number" is the question this calculation exists to answer, and a single total# does not answer it. `effectiveRate` is the blended percentage actually earned,# which is the number a salesperson compares against the plan they were sold. let rateUpto = 0.03, rateBeyond = 0.05, commission = fn( input ~> let within = min(input.sales, input.target), beyond = max(0.0, input.sales - input.target), earnedWithin = round(within * rateUpto, 2), earnedBeyond = round(beyond * rateBeyond, 2), total = round(earnedWithin + earnedBeyond, 2) check 'never negative': total >= 0, 'tiers add up': round(earnedWithin + earnedBeyond, 2) == total in { commission: total, targetReached: input.sales >= input.target, uptoTarget: earnedWithin, beyondTarget: earnedBeyond, # Guarded rather than divided blindly: a period with no sales earns no # commission, and asking what percentage of nothing that is has no # answer worth printing. effectiveRate: if input.sales > 0 then round(total / input.sales * 100, 2) else 0.0 } )in { formula: commission }
types.elo
Money = Float(v | notNegative: v >= 0)Target = Float(v | positive: v > 0) Input = { sales: Money, target: Target} Output = { commission: Float, targetReached: Bool, uptoTarget: Float, beyondTarget: Float, effectiveRate: Float}
Compiled · JavaScript
(function(_) { function kAdd(l, r) { if (DateTime.isDateTime(l) && Duration.isDuration(r)) return l.plus(r); if (Duration.isDuration(l) && DateTime.isDateTime(r)) return r.plus(l); if (Duration.isDuration(l) && Duration.isDuration(r)) return l.plus(r); return l + r; } function kDiv(l, r) { if (Duration.isDuration(l) && typeof r === 'number') return Duration.fromMillis(l.toMillis() / r); return l / r; } function kEq(l, r) { if (Duration.isDuration(l) && Duration.isDuration(r)) return l.toMillis() === r.toMillis(); if (DateTime.isDateTime(l) && DateTime.isDateTime(r)) return l.toMillis() === r.toMillis(); if (Array.isArray(l) && Array.isArray(r)) { if (l.length !== r.length) return false; for (let i = 0; i < l.length; i++) if (!kEq(l[i], r[i])) return false; return true; } if (typeof l === 'object' && typeof r === 'object' && l !== null && r !== null && !Array.isArray(l) && !Array.isArray(r)) { const keysL = Object.keys(l); const keysR = Object.keys(r); if (keysL.length !== keysR.length) return false; for (const key of keysL) if (!(key in r) || !kEq(l[key], r[key])) return false; return true; } return l == r; } function kMax2(a, b) { return a > b ? a : b; } function kMember(o, k) { if (o === null || typeof o !== 'object') return null; return Object.prototype.hasOwnProperty.call(o, k) ? o[k] : null; } function kMin2(a, b) { return a < b ? a : b; } function kMul(l, r) { if (Array.isArray(l) || Array.isArray(r)) throw new Error("Array multiplication is not supported"); if (Duration.isDuration(l)) return Number.isInteger(r) ? l.mapUnits(u => u * r) : Duration.fromMillis(l.toMillis() * r); if (Duration.isDuration(r)) return Number.isInteger(l) ? r.mapUnits(u => u * l) : Duration.fromMillis(r.toMillis() * l); return l * r; } function kRound(x) { return x < 0 ? -Math.round(-x) : Math.round(x); } function kRoundTo(x, n) { const f = Math.pow(10, n); return kRound(x * f) / f; } function kSub(l, r) { if (DateTime.isDateTime(l) && Duration.isDuration(r)) return l.minus(r); if (DateTime.isDateTime(l) && DateTime.isDateTime(r)) return Duration.fromMillis(l.toMillis() - r.toMillis()); if (Duration.isDuration(l) && Duration.isDuration(r)) return l.minus(r); return l - r; } function pBool(v, p) { if (typeof v === 'boolean') return pOk(v, p); if (v === 'true') return pOk(true, p); if (v === 'false') return pOk(false, p); return pFail(p, 'expected Bool, got ' + (v === null ? 'Null' : typeof v === 'string' ? JSON.stringify(v) : typeof v)); } function pFail(p, m, c, k, l) { return { success: false, path: p, message: m || '', value: null, cause: c || [], kind: k || 'schema', label: l }; } function pFloat(v, p) { if (typeof v === 'number') return pOk(v, p); if (typeof v === 'string' && /^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/.test(v.trim())) return pOk(parseFloat(v.trim()), p); return pFail(p, 'expected Float, got ' + (v === null ? 'Null' : typeof v === 'string' ? JSON.stringify(v) : typeof v)); } function pOk(v, p) { return { success: true, path: p, message: '', value: v, cause: [] }; } function pRaise(k, l, m) { const e = new Error(m); e.kind = k; if (l) e.label = l; throw e; } function pSchema(props, extrasMode, extrasParser) { const known = props.map(pr => pr[0]); return (v, p) => { if (typeof v !== 'object' || v === null || Array.isArray(v)) return pFail(p, 'expected object, got ' + (v === null ? 'Null' : typeof v)); const o = {}; for (const [key, parser, optional] of props) { if (optional && v[key] == null) continue; const r = parser(v[key], p + '.' + key); if (!r.success) return pFail(p, null, [Object.prototype.hasOwnProperty.call(v, key) ? r : { ...r, kind: 'missing' }]); o[key] = r.value; } if (extrasMode === 'closed') { for (const k in v) if (!known.includes(k)) return pFail(p + '.' + k, 'unexpected attribute'); } else if (extrasMode === 'typed' && extrasParser) { for (const k in v) { if (known.includes(k)) continue; const re = extrasParser(v[k], p + '.' + k); if (!re.success) return pFail(p, null, [re]); o[k] = re.value; } } return pOk(o, p); }; } function pSubtype(baseParser, checks) { return (v, p) => { const r = baseParser(v, p); if (!r.success) return r; for (const [message, label, fn] of checks) { if (!fn(r.value)) return pFail(p, message, [], 'constraint', label); } return r; }; } function pUnwrap(r) { if (r.success) return r.value; function findError(e) { if (e.message) return e; if (e.cause && e.cause[0]) return findError(e.cause[0]); return e; } const err = findError(r); const e = new Error((err.path || '.') + ': ' + (err.message || 'type error')); e.kind = err.kind || 'schema'; e.path = err.path || '.'; if (err.label) e.label = err.label; throw e; } return (() => { const _module_0 = (() => { const rateUpto = 0.03; const rateBeyond = 0.05; const commission = (input) => (() => { const within = kMin2(kMember(input, "sales"), kMember(input, "target")); const beyond = kMax2(0.0, kSub(kMember(input, "sales"), kMember(input, "target"))); const earnedWithin = kRoundTo(kMul(within, rateUpto), 2); const earnedBeyond = kRoundTo(kMul(beyond, rateBeyond), 2); const total = kRoundTo(kAdd(earnedWithin, earnedBeyond), 2); return (() => { if (!(total >= 0)) pRaise("check", "never negative", "never negative"); if (!(kEq(kRoundTo(kAdd(earnedWithin, earnedBeyond), 2), total))) pRaise("check", "tiers add up", "tiers add up"); return ({commission: total, targetReached: kMember(input, "sales") >= kMember(input, "target"), uptoTarget: earnedWithin, beyondTarget: earnedBeyond, effectiveRate: ((kMember(input, "sales") > 0) ? (kRoundTo(kMul(kDiv(total, kMember(input, "sales")), 100), 2)) : (0.0))}); })(); })(); return ({formula: commission}); })(); const formula = kMember(_module_0, "formula"); return (() => { const _p_Input = pSchema([["sales", pSubtype(pFloat, [["constraint 'notNegative' failed", "notNegative", (v) => v >= 0]]), false], ["target", pSubtype(pFloat, [["constraint 'positive' failed", "positive", (v) => v > 0]]), false]], 'closed', null); const Input = (v) => pUnwrap(_p_Input(v, '')); const _p_Output = pSchema([["commission", pFloat, false], ["targetReached", pBool, false], ["uptoTarget", pFloat, false], ["beyondTarget", pFloat, false], ["effectiveRate", pFloat, false]], 'closed', null); const Output = (v) => pUnwrap(_p_Output(v, '')); return Output(formula(Input(_))); })(); })(); })