DecCF./ˈdɛk.ɛf/

Model editor reference

Use these model-building names in the portal model editor. Select a domain module in model settings to make its names available; the portal prepares the selected module for the model automatically.

Core model editor

Use these names in the portal model editor when writing a model.

Model editor namePurpose and model value shape
deccf.accountDeclares a model account with an optional opening amount. initial accepts a finite number or Money, existing supported input/calculation/expression sources, an initializer callback, or a parameter/once binding. Parameter and once initializers are registered during preparation and resolved before periods start, with normal finite-value and currency checks. Historical previous/history bindings cannot initialize an account. Declare parameters captured by a once callback in the model as well. Existing initializer callbacks retain the broad calculation context and account-dependency checks. Returns the account reference; see the execution guide for a callable parameter/once initializer example.

(options?: AccountOptions): AccountReference

const opening = deccf.bind.parameter('opening',{valueType:'number',defaultValue:10000});

const reserve = deccf.bind.once(ctx=>ctx.get(opening)*0.1);

const person = deccf.entity.party({label:'Saver'});

const cash = deccf.account({owner:person,initial:opening});

const emergency = deccf.account({owner:person,initial:reserve});

return deccf.defineModel({
  currency:deccf.currencies.SEK,
  timeline:deccf.periods.annual({from:'2026-01',count:1}),
  entities:{person}, accounts:{cash,emergency},
});

deccf.actionsProvides state and field actions that lifecycle callbacks can schedule. Use these helpers inside a lifecycle transition or event.

Readonly<{ setState(subject: EntityReference, nextState: StateReference): Action; setField(target: FieldReference, value: number | InputReference | Money | ((context: CalculationContext) => number)): Action; activate(flow: CashflowReference): Action; deactivate(flow: CashflowReference): Action; }>

const { actions } = deccf;

deccf.actions.activateSchedules a flow to become active as a lifecycle action.

(flow: CashflowReference): Action

const { activate } = deccf.actions;

deccf.actions.deactivateSchedules a flow to stop as a lifecycle action.

(flow: CashflowReference): Action

const { actions, cashflow, currencies, defineModel, entity, event, inflow, lifecycle, periods, schedule, state } = deccf;

const available = state("available");

const sold = state("sold");

const life = lifecycle({
  states: [available, sold],
  initial: available,
  transitions: [{ from: available, to: sold, when: (ctx) => ctx.time.index === 11 }],
});

const property = entity.asset({ lifecycle: life });

const rent = cashflow({ owner: property, direction: inflow, schedule: schedule.monthly(), amount: 2_000 });

const closeEvent = event({
  when: (ctx) => ctx.isInState(property, sold),
  actions: [actions.deactivate(rent)],
});

const model = defineModel({
  name: "stop-rent-after-sale",
  currency: currencies.SEK,
  timeline: periods.monthly({ from: "2026-01", count: 24 }),
  entities: { property },
  flows: { rent },
  events: { closeEvent },
});

return model;

deccf.actions.setFieldSets a declared entity field when a lifecycle action runs.

(target: FieldReference, value: number | InputReference | Money | ((context: CalculationContext) => number)): Action

const { setField } = deccf.actions;

deccf.actions.setStateMoves an entity into a declared state when a lifecycle action runs.

(subject: EntityReference, nextState: StateReference): Action

const { setState } = deccf.actions;

deccf.addMoneyAdds two Money values of the same currency and returns a Money value. Amounts must be finite; mismatched currencies are rejected. Retains an explicit valuation date only when both operands have the same date; otherwise the result is undated. Adding amounts does not convert their purchasing power. Attach a date explicitly with money() when the resulting total needs a valuation date.

(left: Money, right: Money): Money

const first = deccf.money(100, deccf.currencies.SEK, {date: "2027-01-01"});
const second = deccf.money(20, deccf.currencies.SEK, {date: "2027-01-01"});
const total = deccf.addMoney(first, second);
// total.amount is 120; total.date is "2027-01-01".

deccf.agreementDeclares an agreement attached to an entity, with optional parties, dates, terms, and boundary actions.

(options: { readonly subject: EntityReference; readonly parties?: Readonly<Record<string, EntityReference>>; readonly from?: DateString; readonly to?: DateString; readonly terms?: Readonly<Record<string, AgreementTermReference>>; readonly onStart?: readonly Action[]; readonly onEnd?: readonly Action[]; }): AgreementReference

const { agreement, agreementTerm, cashflow, currencies, defineModel, entity, inflow, periods, schedule } = deccf;

const property = entity.asset();

const landlord = entity.party();

const tenant = entity.party();

const monthlyRent = agreementTerm(12_000);

const lease = agreement({
  subject: property,
  parties: { landlord, tenant },
  from: "2026-01",
  to: "2027-12",
  terms: { monthlyRent },
});

const rent = cashflow({
  dynamic:true,
  owner: property,
  agreement: lease,
  direction: inflow,
  schedule: schedule.monthly(),
  amount: (ctx) => ctx.term(lease, monthlyRent),
});

const model = defineModel({
  name: "rental-agreement",
  currency: currencies.SEK,
  timeline: periods.monthly({ from: "2026-01", count: 24 }),
  entities: { property, landlord, tenant },
  agreements: { lease },
  flows: { rent },
});

return model;

deccf.agreementTermWraps a value as a term attached to an agreement. Use it when agreement details should be declared separately from model calculations.

<T extends InputValue>(value: T | InputReference<T>, options?: InputOptions<T>): AgreementTermReference<T>

const { agreement, agreementTerm, cashflow, currencies, defineModel, entity, inflow, periods, schedule } = deccf;

const property = entity.asset();

const landlord = entity.party();

const tenant = entity.party();

const monthlyRent = agreementTerm(12_000);

const lease = agreement({
  subject: property,
  parties: { landlord, tenant },
  from: "2026-01",
  to: "2027-12",
  terms: { monthlyRent },
});

const rent = cashflow({
  dynamic:true,
  owner: property,
  agreement: lease,
  direction: inflow,
  schedule: schedule.monthly(),
  amount: (ctx) => ctx.term(lease, monthlyRent),
});

const model = defineModel({
  name: "rental-agreement",
  currency: currencies.SEK,
  timeline: periods.monthly({ from: "2026-01", count: 24 }),
  entities: { property, landlord, tenant },
  agreements: { lease },
  flows: { rent },
});

return model;

deccf.allocationallocation({amount, method, limits?, ...options}) returns a component: outputs shares (keyed Money), requested, allocated, unallocated, explanation and optional unmetRequest. Register it. amount is a model-currency monetary source; method is proportional() or priority(). limits caps recipients (default none); redistribute defaults true, signed false, unit 0.01 currency units for rounding. Signed proportional weights cannot use limits. name labels the calculation; schedule/phase follow calculation defaults. Invalid amounts, methods, options or constraints reject. Calculates shares without payment. Keyed values accept a keyed source map, an ordinary repeated column or a repeated calculation/flow output map; numeric leaves are finite numbers or Money in the model currency. Source repeat keys identify recipients, including inside enclosing repeats and after input reordering. Register source repeats as components. Nonnumeric leaves, wrong currencies and unknown recipient keys reject. Existing keyed maps and columns retain their meaning.

(options: AllocationOptions): ComponentReference<AllocationOutputs>

const rows = deccf.input.objectArray([
  {id: deccf.input.id("a"), weight: deccf.input.decimal(1)},
  {id: deccf.input.id("b"), weight: deccf.input.decimal(3)},
]);
const weight = deccf.calculation({name: "Weight", calculate: deccf.expr.multiply(rows.item.data.weight, 1)});
const weights = deccf.repeat(rows, deccf.component({calculations: {weight}, outputs: {weight}}));
const split = deccf.allocation({amount: 100, method: deccf.proportional({weights: weights.outputs.weight})});
const reserved = deccf.allocation({amount: 100, method: deccf.proportional({
  weights: weights.outputs.weight, overrides: weights.outputs.weight,
})});
const first = deccf.allocation({amount: 10,
  method: deccf.priority({order: ["a", "b"], requests: weights.outputs.weight}),
  limits: weights.outputs.weight,
});
return deccf.defineModel({currency: deccf.currencies.SEK,
  timeline: deccf.periods.monthly({from: "2026-01", count: 1}),
  preconditions: {rows}, components: {weights, split, reserved, first},
});
 

deccf.analysisOrdinary scalar metrics that re-evaluate the same authored graph in fresh state. All analysis metrics are excluded in candidate runs. Values emit once at the final model period. Mark their names in monteCarlo.baselineMetrics to evaluate them only once during simulation.

{ scenario(options: ScenarioAnalysisOptions): MetricDeclaration; first(options: GoalAnalysisOptions): MetricDeclaration; threshold(options: ThresholdAnalysisOptions): MetricDeclaration; }

const { analysis } = deccf;

deccf.analysis.firstTests every integer in ascending order between ceil(from) and floor(to), without assuming monotonicity. Requires an integer input; safe integer bounds may span at most 10000. Returns the first feasible integer, including zero, or emits no value when none is feasible. Returns an ordinary numeric metric declaration for defineModel.metrics, evaluated once in the final model period. Candidate runs execute the same authored financial graph in fresh state, excluding every analysis metric. Inputs, Money, arrays and object shape are preserved without mutating the baseline; changes is an optional array of {input,value}, targeting declared scalar leaves. Values, bounds and thresholds accept finite numbers, declared inputs or input-only arithmetic expressions; changed values also accept Money, text and booleans. Unknown inputs/metrics, duplicate changes, analysis-to-analysis selection, text metrics and invalid values fail validation. A candidate with no emitted metric produces no analysis value. Mark analysis metric names in monteCarlo.baselineMetrics so searches run once during the ordinary baseline instead of once per trial. Monetary scenario outputs keep their currency and explicit valuation date; output purchasing-power conversion applies once. Built-in total retains the candidate cashflows’ per-period valuation and npv retains its base-date amount; neither aggregate is deflated again at the final period. A compare callback receives nominal values, including nominal aggregate totals. Optional compare(value,baselineContext) performs a pure financial comparison of the candidate scalar (scenario) or found input value (goal), returning number, Money or undefined. It does not run when no feasible value exists. label and unit are optional presentation metadata. Requires an integer input and from/to bounds. Tests every integer in ascending order from ceil(from) through floor(to), without requiring monotonicity. atLeast defaults to 1; alternatively supply atMost, but never both. Returns the earliest feasible integer including zero, or emits no value if none is feasible. Bounds must be ordered safe integers spanning at most 10000 candidates. The result uses the searched input's units.

(options: GoalAnalysisOptions): MetricDeclaration

const age = deccf.input.integer(60);

const earliest = deccf.analysis.first({input: age, from: 60, to: 75, metric: "feasible", atLeast: 1});

deccf.analysis.scenarioSelects the final nominal candidate metric after scalar input changes. Money/date are retained; normal result valuation applies once. Built-in total retains per-period valuation and npv its base-date amount. A compare callback receives nominal values. No emitted target value yields no analysis value. Returns an ordinary numeric metric declaration for defineModel.metrics, evaluated once in the final model period. Candidate runs execute the same authored financial graph in fresh state, excluding every analysis metric. Inputs, Money, arrays and object shape are preserved without mutating the baseline; changes is an optional array of {input,value}, targeting declared scalar leaves. Values, bounds and thresholds accept finite numbers, declared inputs or input-only arithmetic expressions; changed values also accept Money, text and booleans. Unknown inputs/metrics, duplicate changes, analysis-to-analysis selection, text metrics and invalid values fail validation. A candidate with no emitted metric produces no analysis value. Mark analysis metric names in monteCarlo.baselineMetrics so searches run once during the ordinary baseline instead of once per trial. Monetary scenario outputs keep their currency and explicit valuation date; output purchasing-power conversion applies once. Built-in total retains the candidate cashflows’ per-period valuation and npv retains its base-date amount; neither aggregate is deflated again at the final period. A compare callback receives nominal values, including nominal aggregate totals. Optional compare(value,baselineContext) performs a pure financial comparison of the candidate scalar (scenario) or found input value (goal), returning number, Money or undefined. It does not run when no feasible value exists. label and unit are optional presentation metadata. Selects metric after applying changes. onInvalid defaults to error; omit suppresses only candidate input validation failures, leaving the metric absent. Financial callback/runtime failures still propagate. Optional compare(candidate,baselineContext) is a pure financial calculation returning number, Money or undefined; candidate preserves nominal Money/date and the context reads baseline financial values. For example compare:(candidate,ctx)=>(candidate.amount-ctx.get(initialCapital).amount)/100 calculates a financial difference without authoring run orchestration.

(options: ScenarioAnalysisOptions): MetricDeclaration

const contribution = deccf.input.decimal(10);

const bank = deccf.account({initial: 0});

const saving = deccf.cashflow({
  direction: deccf.inflow, moves: bank, schedule: deccf.schedule.monthly(),
  bindings: {contribution}, amount: ({contribution}) => contribution,
});

return deccf.defineModel({
  currency: deccf.currencies.USD,
  timeline: deccf.periods.monthly({from: "2026-01", count: 12}),
  preconditions: {contribution}, accounts: {bank}, flows: {saving},
  monteCarlo: {baselineMetrics: ["higherContribution", "minimumContribution"]},
  metrics: {
    balance: deccf.metric({calculate: ctx => deccf.money(ctx.get(bank), ctx.currency)}),
    higherContribution: deccf.analysis.scenario({
      metric: "balance", changes: [{input: contribution, value: 20}],
    }),
    minimumContribution: deccf.analysis.threshold({
      input: contribution, from: 0, to: 100, metric: "balance",
      atLeast: 240, select: "minimum", tolerance: 0.001, maxIterations: 24,
    }),
  },
});

deccf.analysis.thresholdBisects a bounded decimal, rate or fraction input and returns its feasible edge in input units. Returns an already feasible selected endpoint immediately, or emits no value if the opposite endpoint is infeasible. Stops at tolerance or maxIterations and always retains the feasible side. Returns an ordinary numeric metric declaration for defineModel.metrics, evaluated once in the final model period. Candidate runs execute the same authored financial graph in fresh state, excluding every analysis metric. Inputs, Money, arrays and object shape are preserved without mutating the baseline; changes is an optional array of {input,value}, targeting declared scalar leaves. Values, bounds and thresholds accept finite numbers, declared inputs or input-only arithmetic expressions; changed values also accept Money, text and booleans. Unknown inputs/metrics, duplicate changes, analysis-to-analysis selection, text metrics and invalid values fail validation. A candidate with no emitted metric produces no analysis value. Mark analysis metric names in monteCarlo.baselineMetrics so searches run once during the ordinary baseline instead of once per trial. Monetary scenario outputs keep their currency and explicit valuation date; output purchasing-power conversion applies once. Built-in total retains the candidate cashflows’ per-period valuation and npv retains its base-date amount; neither aggregate is deflated again at the final period. A compare callback receives nominal values, including nominal aggregate totals. Optional compare(value,baselineContext) performs a pure financial comparison of the candidate scalar (scenario) or found input value (goal), returning number, Money or undefined. It does not run when no feasible value exists. label and unit are optional presentation metadata. Searches a decimal, rate or fraction input between ordered finite from/to bounds. atLeast defaults to 1, or supply atMost; the two options are mutually exclusive. select defaults to minimum, with maximum also supported. Feasibility must be monotonic across the supplied interval: minimum assumes infeasible then feasible; maximum assumes feasible then infeasible. An already feasible selected endpoint returns immediately; if the opposite endpoint is infeasible, no result is emitted. Bisection retains the feasible side and stops at positive absolute tolerance (default 1e-6 in input units) or maxIterations (default 80, integer 1..256). Both controls accept input references or input expressions. Returns the feasible bound even if the iteration limit is reached before tolerance.

(options: ThresholdAnalysisOptions): MetricDeclaration

const contribution = deccf.input.decimal(10);

const bank = deccf.account({initial: 0});

const saving = deccf.cashflow({
  direction: deccf.inflow, moves: bank, schedule: deccf.schedule.monthly(),
  bindings: {contribution}, amount: ({contribution}) => contribution,
});

return deccf.defineModel({
  currency: deccf.currencies.USD,
  timeline: deccf.periods.monthly({from: "2026-01", count: 12}),
  preconditions: {contribution}, accounts: {bank}, flows: {saving},
  monteCarlo: {baselineMetrics: ["higherContribution", "minimumContribution"]},
  metrics: {
    balance: deccf.metric({calculate: ctx => deccf.money(ctx.get(bank), ctx.currency)}),
    higherContribution: deccf.analysis.scenario({
      metric: "balance", changes: [{input: contribution, value: 20}],
    }),
    minimumContribution: deccf.analysis.threshold({
      input: contribution, from: 0, to: 100, metric: "balance",
      atLeast: 240, select: "minimum", tolerance: 0.001, maxIterations: 24,
    }),
  },
});

deccf.bindDeclares current, historical, parameter and once-per-execution reads for static callbacks.

Readonly<BindingFactory>

const { bind } = deccf;

deccf.bind.historyImmutable chronological snapshot of completed calculation values strictly before this period. Omitted reference means the current calculation; the first snapshot is [], and inactive scheduled periods are omitted. Creates a binding to a frozen chronological array of completed calculation values strictly before the current period. Omitted reference selects the current calculation; its first history is []. Only calculation references are supported; inactive scheduled periods are omitted. It adds no same-period dependency. A final report appends its current row explicitly instead of copying accumulated history into every period state.

<T = unknown>(reference?: CalculationReference<T>): BindingReference<readonly T[], "history">

const observations = deccf.calculation({
  name:'observations', publish:true,
  bindings:{prior:deccf.bind.history()},
  calculate:({prior})=>prior.length+1,
});

return deccf.defineModel({
  currency:deccf.currencies.SEK,
  timeline:deccf.periods.annual({from:'2026-01',count:3}),
  calculations:{observations},
});

deccf.bind.onceResolves synchronous data once per execution/trial, shared by readers. Nested functions, Promises and class instances are rejected. Input references must belong to the model; captured parameter bindings must also be declared. Time-varying curves and time/account/flow/calculation reads are unavailable. draw/sample use the initialization period without an owner. Declares a synchronous configuration callback resolved at most once per execution or Monte Carlo trial and shared by readers of that binding. The restricted context exposes get for declared inputs and parameter/once bindings, plus draw/sample; it has no time, ledger balances, flow or calculation reads and rejects time-varying curves. Sampling uses the initialization period without an owner. Plain records and arrays are snapshotted immutably; scalar values and model references are retained. Functions are rejected at every nesting level, as are Promises and class instances. Precompute reusable annual sampled values as data; callbacks requiring current time, owner or balances belong in explicit dynamic execution. Bind row projections directly so repeated components can rebind them. Runtime parameter data cannot supply callbacks. No resolved once value crosses executions.

<T>(resolve: (context: OnceContext) => T & OnceData<T>): OnceBindingReference<T>

const annualIncome = deccf.input.money(42000,deccf.currencies.SEK);

const monthly = deccf.bind.once(ctx=>ctx.get(annualIncome).amount/12);

const income = deccf.calculation({
  name:'monthlyIncome', publish:true, bindings:{monthly},
  calculate:({monthly})=>monthly,
});

return deccf.defineModel({
  currency:deccf.currencies.SEK,
  timeline:deccf.periods.monthly({from:'2026-01',count:12}),
  preconditions:{annualIncome}, calculations:{income},
});

deccf.bind.parameterDeclares a finite numeric runtime parameter, separate from structural model inputs. Values retain their authored units; decimal rates use 0.02 for 2%. Declares a typed runtime parameter. Missing values without a default, unknown names, invalid values and conflicting declarations are errors. It cannot change topology, schedules or timeline. Declares a named runtime value with required valueType using the calculation result schema and optional defaultValue. Values retain their authored units: decimal rates use 0.02 for 2%, and Money retains currency. Supply replacements through run or prepared.run parameters. Missing values without a default, unknown supplied names, invalid values and conflicting declarations of one name fail. Parameter bindings cannot change the compiled model structure, timeline or schedules. A parameter used inside bind.once must also occur in declarative bindings.

(name: string, options: { readonly valueType: "number"; readonly defaultValue?: number; }): ParameterBindingReference<number>
(name: string, options: { readonly valueType: "boolean"; readonly defaultValue?: boolean; }): ParameterBindingReference<boolean>
(name: string, options: { readonly valueType: "text"; readonly defaultValue?: string; }): ParameterBindingReference<string>
(name: string, options: { readonly valueType: "money"; readonly defaultValue?: Money; }): ParameterBindingReference<Money>
<TType extends CalculationResultType>(name: string, options: { readonly valueType: TType; readonly defaultValue?: NoInfer<RuntimeParameterValue<TType>>; }): ParameterBindingReference<RuntimeParameterValue<TType>>

const opening = deccf.bind.parameter('opening',{valueType:'number',defaultValue:10000});

const reserve = deccf.bind.once(ctx=>ctx.get(opening)*0.1);

const person = deccf.entity.party({label:'Saver'});

const cash = deccf.account({owner:person,initial:opening});

const emergency = deccf.account({owner:person,initial:reserve});

return deccf.defineModel({
  currency:deccf.currencies.SEK,
  timeline:deccf.periods.annual({from:'2026-01',count:1}),
  entities:{person}, accounts:{cash,emergency},
});

deccf.bind.previousReads the prior completed calculation or account value. Omitted reference means the current calculation; its first value is 0. Accounts start at their initial balance. Creates a historical binding for a declared calculation, calculation projection or account. Optional reference defaults to the current calculation; this self form is valid only inside a calculation. Call bind.previous().project(path) to select a field of the prior self result, bind.previous(calculation.project(path)) for an explicit target, or chain project calls. Paths are nonempty dotted strings or arrays of field names checked against the result schema at preparation. The first-period calculation sentinel remains 0 even for projections. An inactive preceding period uses inactiveValue or fails when none is supplied. Accounts return opening balances, starting with their declared initial balance, and cannot project fields. It adds no same-period dependency and does not read future values.

<T = unknown>(reference?: CalculationReference<T> | CalculationProjectionReference<T>): PreviousBindingReference<T>
(reference: AccountReference): BindingReference<number, "previous">

const total = deccf.calculation({
  name:'total', publish:true, resultType:{amount:'number',phase:'text'},
  bindings:{priorAmount:deccf.bind.previous().project('amount')},
  calculate:({priorAmount})=>({amount:priorAmount+100,phase:'saving'}),
});

return deccf.defineModel({
  currency:deccf.currencies.SEK,
  timeline:deccf.periods.annual({from:'2026-01',count:3}),
  calculations:{total},
});

deccf.bind.sampleSamples a declared distribution once per model period (default), or reuses the first represented period's sample for every date in a calendar year. Readers share model-wide coordinates independent of owner and evaluation order. Unseeded runs use the distribution center; input overrides retain precedence. Declares a numeric static distribution sample with optional {calendar:'period'|'annual'}, default period. Period sampling has one coordinate per model period; annual sampling reuses the first represented period coordinate throughout each calendar year, including partial years. Consumers share model-wide coordinates independently of owner or evaluation order. Unseeded runs use the distribution center, and input replacements take precedence. The input must be a declared distribution; other inputs, unknown options and unsupported calendars fail. Rates retain decimal units, for example 0.03 means 3%. For annually resetting financial returns, combine an editable rate mean with a declared input.normal({mean:0,stdev:0.15},{visible:false}) shock and bind.sample(shock,{calendar:'annual'}); literal volatility stays out of the editable form. A fixed contractual rate or horizon-wide WACC instead uses bind.once(ctx=>ctx.draw(shock)). ctx.get(distribution) and ordinary bindings read the center and create no sampled spread. Compound each period against the previous balance or a native running product; never apply the latest draw to the full elapsed horizon. Useful uncertain apps can choose calculator:{defaultRun:{mode:'monte-carlo',trials:64,sampling:'sobol'}}. Global seeded trial and Sobol coordinates match general, indexed and worker execution. It returns a binding reference for calculation/flow bindings, without introducing another input. See the annual financial returns example in Static execution for a complete callable model and separate standard presentation.

(reference: InputReference<number>, options?: { readonly calendar?: "annual" | "period"; }): BindingReference<number, "sample">

const capital = deccf.input.money(10000, deccf.currencies.USD, {ui: {label: "Capital ($)"}});

const meanReturn = deccf.input.rate(0.05, {ui: {label: "Annual effective return"}});

const domain = deccf.input.domain({capital, meanReturn});

const shock = deccf.input.normal({mean: 0, stdev: 0.15}, {visible: false});

const sampledReturn = deccf.bind.sample(shock, {calendar: "annual"});

const rate = deccf.calculation({
  name: "rate", bindings: {meanReturn, sampledReturn},
  calculate: ({meanReturn, sampledReturn}) => Math.max(-0.99, meanReturn + sampledReturn),
});

const balance = deccf.calculation({
  name: "balance", bindings: {capital, rate, previous: deccf.bind.previous()},
  calculate: ({capital, rate, previous}, {time}) =>
    (time.index === 0 ? capital.amount : previous) * (1 + rate) ** (1 / 12),
});

const model = deccf.defineModel({
  currency: deccf.currencies.USD,
  timeline: deccf.periods.monthly({from: "2026-11", count: 4}),
  preconditions: {domain, shock}, calculations: {rate, balance},
  calculator: {defaultRun: {mode: "monte-carlo", trials: 64, sampling: "sobol"}},
  monteCarlo: {execution: "indexed", series: ["metric.rate", "metric.endingBalance"]},
  metrics: {
    rate: deccf.metric({value: rate}),
    endingBalance: deccf.metric({value: balance, unit: "money"}),
  },
});

return model;

deccf.calculationDeclares a synchronous calculation. phase defaults to "period"; "periodEnd" runs after cashflow postings, account settlement and options. Static callbacks receive (values, {time,currency}); bindings infer dependencies and allowed account reads. Use dynamic:true for the broad CalculationContext, with explicit dependsOn and readsAccountsFrom. Combining dynamic:true and bindings is invalid. A period calculation reads opening balances, while a periodEnd calculation reads settled current-period balances. ctx.previous(account) always reads the opening balance. A period calculation or flow cannot depend on a periodEnd result. publish defaults to false; true captures values in deterministic.calculations. The optional schedule limits active periods; a read outside it fails unless inactiveValue is supplied. Static callbacks are the default: bindings:{name:source} supplies the first callback argument and the second is {time,currency}. Sources are declared inputs, calculations/projections, accounts, flows, expressions, terms, bind references or scalar literals. Dependencies and account-read permissions are inferred and validated before execution. Period calculations read opening balances; periodEnd calculations read settled balances. Set dynamic:true for the broad CalculationContext and explicitly declare its dependencies. Dynamic and bindings cannot be combined. The result is a reusable calculation reference with the declared resultType; values remain subject to finite-number, shape and Money/currency validation. See Static bindings and explicit dynamic callbacks for callable examples and migration.

<TBindings extends ModelBindings, TResult>(options: StaticCalculationOptions<TBindings, TResult>): CalculationReference<TResult>
<TResult>(options: DynamicCalculationOptions<TResult>): CalculationReference<TResult>

const total = deccf.calculation({
  name:'total', publish:true,
  bindings:{previous:deccf.bind.previous()},
  calculate:({previous})=>previous+100,
});

return deccf.defineModel({
  currency:deccf.currencies.SEK,
  timeline:deccf.periods.annual({from:'2026-01',count:3}),
  calculations:{total},
});

deccf.calculation.projectcalculation.project provides project in the Core model API model editor. Use it when a model needs this operation.

<T, TPath extends string | readonly string[]>(reference: CalculationReference<T>, path: TPath): CalculationProjectionReference<CalculationFieldValue<T, TPath>>

const { project } = deccf.calculation;

deccf.cashflowDeclares a scheduled cash movement or balanced postings. Static callbacks receive (values, {time,currency}) and infer read dependencies from bindings. Set dynamic:true for the broad CalculationContext, including trigger source and booking amount. Dynamic declarations cannot have bindings. Static amount, active and booking callbacks receive (values,{time,currency}); bindings declares and orders their reads. Dynamic:true instead supplies the broad CalculationContext, including trigger source and the booking base amount. Dynamic and bindings cannot be combined. Flow groups propagate their execution mode and bindings. Balanced-posting, finite-number, currency and dependency checks apply in both modes. Constants and expressions remain valid amounts. Returns the declared flow reference. See Static bindings and explicit dynamic callbacks for callable examples.

<TBindings extends ModelBindings>(options: StaticCashflowOptions<TBindings>): CashflowReference
(options: DynamicCashflowOptions): CashflowReference

const income = deccf.input.normal({mean:42000,stdev:3000});

const salary = deccf.cashflow({
  dynamic:true, direction:deccf.inflow, schedule:deccf.schedule.annual(),
  amount:ctx=>Math.max(0,ctx.sample(income)),
});

return deccf.defineModel({
  currency:deccf.currencies.SEK,
  timeline:deccf.periods.annual({from:'2026-01',count:3}),
  preconditions:{income}, flows:{salary},
});

deccf.categoryCreates a reporting category reference for grouping accounts and cashflows. An optional label supplies a display name in results.

(path: string, options?: CategoryOptions): CategoryReference

const owner = deccf.entity.party();

const bank = deccf.account({
  owner,
  type: "asset",
  category: deccf.category("personal.assets.cash.bank"),
  initial: deccf.money(1000, deccf.currencies.SEK),
});

return deccf.defineModel({
  currency: deccf.currencies.SEK,
  timeline: deccf.periods.monthly({ from: "2027-01", count: 2 }),
  entities: { owner },
  accounts: { bank },
});

deccf.columnA keyed field map from declared rows; no repeated component is required.

<TFields extends InputObjectFields, K extends keyof TFields & string>(source: ObjectArrayInputReference<TFields>, field: K): RepeatColumnReference<TFields[K] extends InputReference<infer TValue> ? TValue : InputValue>
<TRow extends InputValueRecord, K extends keyof TRow & string>(source: InputProjectionReference<readonly TRow[]>, field: K): RepeatColumnReference<TRow[K]>
<TFields extends InputObjectFields, TOutputs extends Readonly<Record<string, ComponentOutputReference>>, K extends keyof TFields & string>(source: RepeatedComponentReference<TFields, TOutputs> | RepeatViewReference<TFields, TOutputs>, field: K): RepeatColumnReference<TFields[K] extends InputReference<infer TValue> ? TValue : InputValue>

const annualTotal = deccf.expr.sum(deccf.column(rows, "annual"), {
  resultType: "money",
  currency: deccf.currencies.SEK,
});

deccf.compileModelValidates model declarations and compiles their dependency order. Use it to catch configuration errors before running repeated calculations.

(model: ModelDefinition<ModelCurrency>, options?: { readonly inputOverrides?: ReadonlyMap<InputReference, InputValue>; }): CompilationPlan

const { cashflow, compileModel, currencies, defineModel, entity, inflow, periods, schedule } = deccf;

const building = entity.asset();

const rent = cashflow({ owner: building, direction: inflow, schedule: schedule.monthly(), amount: 10_000 });

const model = defineModel({
  name: "one-year-rent",
  currency: currencies.USD,
  timeline: periods.monthly({ from: "2026-01", count: 12 }),
  entities: { building },
  flows: { rent },
});

const plan = compileModel(model);

console.log(plan.dates.length);

return model;

deccf.componentComposes entities, accounts, flows, calculations, and outputs into a reusable model component.

<TOutputs extends Readonly<Record<string, ComponentOutputReference>> = Readonly<Record<string, ComponentOutputReference>>>(options?: Omit<ComponentOptions, "outputs"> & { readonly outputs?: TOutputs; }): ComponentReference<TOutputs>

const projected = deccf.calculation({
  name: "projected", resultType: "money", bindings: {row: changeable.item.value},
  calculate: ({row}) => deccf.money(
    row.amount.amount * (1 + row.annualReturn - (row.type === "isk" ? row.taxRate : row.fundFee)),
    row.amount.currency,
  ),
});

const accounts = deccf.repeat(changeable, deccf.component({
  calculations: {projected}, outputs: {projected},
}));

const total = deccf.calculation({
  name: "total", calculate: deccf.expr.sum(accounts.outputs.projected, {
    resultType: "money", currency: deccf.currencies.SEK,
  }),
});

return deccf.defineModel({
  currency: deccf.currencies.SEK,
  timeline: deccf.periods.annual({from: "2026-01", count: 1}),
  preconditions: {changeable}, components: {accounts}, calculations: {total},
});

deccf.convertMoneyConverts Money using an explicit finite target-units-per-source-unit rate and a target Currency reference; no exchange rate is fetched. Returns Money with the multiplied amount, target currency and original optional valuation date. Invalid Money, Currency or non-finite rates are rejected. Conversion changes denomination without adjusting purchasing power.

(value: Money, targetCurrency: Currency, unitsOfTargetPerSource: number): Money

const amount = deccf.money(100, deccf.currencies.SEK, {date: "2027-01-01"});
const converted = deccf.convertMoney(amount, deccf.currencies.EUR, 0.09);
// converted.amount is 9; converted.date is "2027-01-01".

deccf.createInputValueReturns a fresh frozen typed value for an input reference. Optional mode defaults to 'initial'; 'newItem' requires an objectArray reference, and other modes are rejected. A variant object initially uses its first catalogue schema; typed variant arrays initially return []. For a variant array, 'newItem' creates the first variant using its authored defaults, including decimal rates (0.02 means 2%), instead of the ordinary homogeneous array's zero/empty new-row policy. When an ID needs generating, supply generateId:()=>string; a missing generator or invalid generated ID produces an explicit error. Declared/saved identities are not replaced, and generation does not mutate the original variant or any standalone choice. This helper creates a value only; it does not append it to a collection or change a Calculator draft.

<TVariants extends ObjectVariantCatalogue, TKey extends string>(reference: ObjectVariantArrayInputReference<TVariants, TKey>, options: { readonly mode: "newItem"; readonly generateId?: () => string; }): ObjectVariantValue<TVariants> & Readonly<Record<TKey, string>>
<TFields extends InputObjectFields>(reference: ObjectArrayInputReference<TFields>, options: { readonly mode: "newItem"; readonly generateId?: () => string; }): InputObjectValue<TFields>
<T extends InputValue>(reference: InputReference<T>, options?: { readonly mode?: "initial"; readonly generateId?: () => string; }): T
<T extends InputValue>(reference: InputReference<T>, options: { readonly mode?: "initial" | "newItem"; readonly generateId?: () => string; }): T | Readonly<Record<string, InputValue>>

const isk = deccf.input.Object({
  type: deccf.input.hidden("isk"),
  amount: deccf.input.money(2500, deccf.currencies.SEK),
  annualReturn: deccf.input.rate(0.02),
  taxRate: deccf.input.rate(0.01),
}, {label: "ISK"});
const vp = deccf.input.Object({
  type: deccf.input.hidden("vp"),
  amount: deccf.input.money(2500, deccf.currencies.SEK),
  annualReturn: deccf.input.rate(0.02),
  fundFee: deccf.input.rate(0.005),
}, {label: "VP-konto"});
const savings = deccf.input.objectArray([isk, vp], {type: "manyOfAnyChangeable", title: "Sparande"});
const initial = deccf.createInputValue(savings); // []
const row = deccf.createInputValue(savings, {mode: "newItem", generateId: () => "account-1"});
// row.type is "isk", amount is 2500 SEK, annualReturn is 0.02 and id is "account-1".

deccf.currenciesProvides the built-in currency values used by money inputs and model reporting. The available codes are listed by the public type declaration.

Readonly<Record<"USD" | "SEK" | "EUR" | "GBP" | "NOK" | "DKK" | "ISK" | "CHF" | "CAD" | "AUD" | "JPY", Currency>>

const { currencies } = deccf;

deccf.currencyCreates a currency value from a three-letter uppercase code. Use it when a model needs a reporting or input denomination.

(code: string): Currency

const { currency } = deccf;

deccf.defineModelCollect declarations into an ordinary model with a required timeline and currency. currency accepts a Currency value or a declared fixed currency-code input, such as input.enum('DKK', {options:[{value:'DKK',label:'DKK'},{value:'EUR',label:'EUR'}]}). Input codes must use three uppercase letters. Their value is resolved before binding accounts and flows on each run, including compiled-model input overrides. This selects the denomination of entered local amounts and never converts Money; explicit foreign Money still fails. The input must be declared in preconditions. describeModel with includeExecutionContext reports the default resolved code. Existing Currency values retain their behavior and run-level reporting relabels remain a separate option; jurisdiction-specific models may reject those relabels. Collects model declarations; currency and timeline are required and declaration maps are optional. Optional inflation is an annual decimal rate (0.02 means 2%), either a finite number greater than -1 or a scalar numeric input reference registered anywhere in this model's inputs. Omission defaults to 0. Reuse an existing reference in its own group, tab or page; no special Inflation field is added. Input overrides resolve the effective rate for each run. A distribution input uses its central value, not an automatic draw; curves, Money, derived references and undeclared references are unsupported. This setting supplies output purchasing-power conversion; financial callbacks must explicitly use inflation if they also need it for future nominal costs or income. Returns the model definition. Optional calculator.defaultRun sets initial interactive mode, trials, seed and sampling; saved selections take precedence. See Initial Calculator run settings and Show money in today's value for examples, defaults and validation. Optional model setting monteCarlo:{execution:'indexed',baselineMetrics:[...]} selects strict indexed Monte Carlo. Omission preserves general execution and its existing summaries. baselineMetrics defaults to []; entries must be unique names of declared metrics. Remaining sampled metrics need declarative metric({value,...}); every scheduled context is evaluated and the final summary retains the last defined emitted value. periodLength:1 and frequency:1 remain defaults; schedule.once(finalDate) selects only a final outcome. Supported sampled value sources are number, text or Money literals and input, calculation, calculation-projection or account references; direct flow, field and expression sources are rejected. All sampled ledger dependencies must support static indexed execution. A nonempty timeline without additional projection periods is required. Events, options, agreements, entity fields/lifecycles, derived inputs, triggered flows, expression bindings/amounts and account initializers using callbacks, expressions or calculations are unsupported. Unsupported callbacks, dynamic dependencies or unsupported graph features cause an error; there is no fallback. Baseline-only calculations can remain dynamic when outside sampled dependencies. Each named baseline metric is evaluated during the complete ordinary unseeded base calculation; its numeric final value is repeated across trials, so standard deviation is zero and all percentiles equal that base value. This is an author-selected fixed baseline statistic, not a sampled uncertainty estimate. Indexed mode summarizes declared numeric metrics only; implicit total, npv, irr and wal sampled summaries are omitted while the complete baseline retains ordinary results. Monthly periods, declared financial operations, global seeded draws, Sobol coordinates and monetary output valuation remain in effect. Active approximate mode (approximate:true with more than 1000 trials) is rejected; at most 1000 trials retain exact execution and inactive approximation metadata. Optional monteCarlo.series selects unique existing account.<name>.balance, flow.<name> or metric.<name> series in general or indexed execution. seriesSummaries[id] contains exact model dates and points of SampledSeriesPointSummary (trials, mean, standardDeviation, min, max and empirical percentiles) or null for missing observations; temporal points omit histograms while existing scalar MetricSummary retains distribution. Series metadata includes optional currency/unit and valuation metadata. Matching baseline arrays preserve the ordinary unseeded curve before annual amount storage. annual:{dates,points,baseline} aggregates each trial before statistics: flows sum, accounts use last balance, metrics follow annualAggregation and fiscalYearStartMonth. Money valuation precedes grouping; amountStorage never discards sampled original dates. Omitted series preserves the existing result shape and avoids temporal summary work. Baseline metric selection is also available in general execution. See Simulate uncertainty and Valuation and uncertainty for a complete callable example, supported values and validation. Optional monteCarlo.samplingLayout accepts only static-first when supplied; omission preserves the original Sobol layout. It preserves model-wide ctx.draw coordinates, promotes every declared bind.sample model-wide period slot before other ctx.sample owner/period slots, and removes promoted slots from the remaining namespace to avoid aliasing. Annual bindings promote the first represented period of each calendar year, including partial years; period bindings promote every period. Inputs sort by declared name and periods chronologically; duplicate consumers share their existing logical sample. Slots are reserved for unused bindings, branches and overridden inputs before execution, so call order and worker partitioning cannot change streams. The opt-in changes Sobol sample streams but leaves pseudorandom streams unchanged; it works in general and indexed execution. The 21,201 actual-coordinate limit still applies and out-of-range dynamic samples fail explicitly. samplingDimensions retains the full potential namespace size, including unused owner/period slots; static-first reorders it rather than limiting supported sampling identities. Structural model changes may change stream assignments.

<TCurrency extends ModelCurrency>(options: ModelOptions<TCurrency>): ModelDefinition<TCurrency>

const initialCapital = deccf.input.money(10000, deccf.currencies.SEK);
const annualReturn = deccf.input.uniform({min: 0.02, max: 0.08});
const sampledReturn = deccf.bind.sample(annualReturn, {calendar: "annual"});
const wealth = deccf.calculation({
  name: "wealth",
  resultType: "number",
  bindings: {initialCapital, sampledReturn},
  calculate: ({initialCapital, sampledReturn}, {time}) =>
    initialCapital.amount * (1 + sampledReturn) ** ((time.index + 1) / 12),
});
const finalDate = deccf.schedule.once("2026-12-01");
const model = deccf.defineModel({
  currency: deccf.currencies.SEK,
  timeline: deccf.periods.monthly({from: "2026-01", count: 12}),
  preconditions: {initialCapital, annualReturn},
  calculations: {wealth},
  monteCarlo: {execution: "indexed", samplingLayout: "static-first", baselineMetrics: ["startingCapital"]},
  metrics: {
    finalWealth: deccf.metric({value: wealth, schedule: finalDate, unit: "money"}),
    startingCapital: deccf.metric({schedule: finalDate, calculate: ctx => ctx.get(initialCapital)}),
  },
});
const simulation = deccf.runMonteCarlo(model, {trials: 128, seed: 7, sampling: "sobol"});
// simulation.summaries.finalWealth describes sampled year-end amounts in SEK.
// simulation.summaries.startingCapital has mean 10000 and standardDeviation 0.
// The full baseline still contains its monthly series and ordinary built-in metrics.
return model;

deccf.derivedDeclares an input-like value calculated from other declared references before simulation. Use it for values users should not edit directly.

<T = unknown>(options: DerivedOptions<T>): DerivedReference

const { derived } = deccf;

deccf.describeModelReturns a frozen editor-facing description of a model's inputs, Calculator defaults and optional scenarios without simulating it. Requires a model returned by defineModel(); other values are rejected. Optional includeExecutionContext defaults to false. When true, resolves default currency, timeline dates and annual decimal inflation from the model's declared inputs; inflation defaults to 0. Execution context fields can be absent when the model defaults cannot resolve them, allowing inputs that need saved or uploaded values to remain editable. Actual run input overrides and validation are applied by run(), not describeModel().

(model: ModelDefinition<ModelCurrency>, options?: { readonly includeExecutionContext?: boolean; }): ModelDescription

const inflation = deccf.input.rate(0.02);
const model = deccf.defineModel({
  currency: deccf.currencies.SEK,
  timeline: deccf.periods.annual({from: "2026-01", count: 2}),
  preconditions: {inflation},
  inflation,
  metrics: {futureAmount: () => deccf.money(10200, deccf.currencies.SEK, {date: "2027-01-01"})},
});
const description = deccf.describeModel(model, {includeExecutionContext: true});
// description.inflation is 0.02; description.dates[0] is "2026-01-01".
return model;

deccf.directionsGroups the built-in inflow and outflow values. Use `inflow` or `outflow` to describe the sign of a cash movement.

Readonly<{ inflow: CashflowDirection; outflow: CashflowDirection; }>

const { directions } = deccf;

deccf.entityCreates an entity reference and its public factories for assets, parties, bundles, and related entity kinds.

(options?: EntityOptions & { readonly family?: "asset" | "party" | "bundle" | "reference" | "household"; }): EntityReference

const { entity } = deccf;

deccf.entity.assetentity.asset provides asset in the Core model API model editor. Use it when a model needs this operation.

(options?: EntityOptions): EntityReference

const company = entity.asset({ attributes: {
  fiscalYearStartMonth: 7,
  companyTaxRate: 0.206,
} });

deccf.entity.bundleentity.bundle provides bundle in the Core model API model editor. Use it when a model needs this operation.

(options?: EntityOptions): EntityReference

const { bundle } = deccf.entity;

deccf.entity.partyentity.party provides party in the Core model API model editor. Use it when a model needs this operation.

(options?: EntityOptions): EntityReference

const anna = entity.party({ attributes: { dateOfBirth: "1990-05-21" } });

deccf.entity.referenceentity.reference provides reference in the Core model API model editor. Use it when a model needs this operation.

(options?: EntityOptions): EntityReference

const { reference } = deccf.entity;

deccf.eventDeclares an event that runs actions once on a schedule or when its condition becomes true.

(options: { readonly schedule?: ScheduleReference; readonly when?: (context: CalculationContext) => boolean; readonly actions?: readonly Action[]; }): EventReference

const { actions, cashflow, currencies, defineModel, entity, event, inflow, lifecycle, periods, schedule, state } = deccf;

const available = state("available");

const sold = state("sold");

const life = lifecycle({
  states: [available, sold],
  initial: available,
  transitions: [{ from: available, to: sold, when: (ctx) => ctx.time.index === 11 }],
});

const property = entity.asset({ lifecycle: life });

const rent = cashflow({ owner: property, direction: inflow, schedule: schedule.monthly(), amount: 2_000 });

const closeEvent = event({
  when: (ctx) => ctx.isInState(property, sold),
  actions: [actions.deactivate(rent)],
});

const model = defineModel({
  name: "stop-rent-after-sale",
  currency: currencies.SEK,
  timeline: periods.monthly({ from: "2026-01", count: 24 }),
  entities: { property },
  flows: { rent },
  events: { closeEvent },
});

return model;

deccf.exprexpr is a model value for expr in the Core model API editor.

Readonly<ExpressionFactory>

const { expr } = deccf;

deccf.expr.addexpr.add provides add in the Core model API model editor. Use it when a model needs this operation.

(left: ExpressionOperand, right: ExpressionOperand): ExpressionReference

const inflation = modules['financial-formulas'].series.rateScenario({
  name: 'monthlyInflation',
  base: 0.002,
  changes: [{ fromPeriod: 12, change: 0.001 }],
});

const indexedRent = modules['financial-formulas'].series.running({
  name: 'indexedRent',
  source: deccf.expr.add(1, inflation),
  operation: 'product',
  initial: 10000,
});

return deccf.defineModel({
  currency: deccf.currencies.SEK,
  timeline: deccf.periods.monthly({ from: '2027-01', count: 24 }),
  calculations: { inflation, indexedRent },
  metrics: { rent: deccf.metric({ value: indexedRent }) },
});

deccf.expr.amountexpr.amount provides amount in the Core model API model editor. Use it when a model needs this operation.

(value: ExpressionOperand): ExpressionReference

const { amount } = deccf.expr;

deccf.expr.balanceexpr.balance provides balance in the Core model API model editor. Use it when a model needs this operation.

(reference: AccountReference | LookupReference<AccountReference> | readonly (AccountReference | LookupReference<AccountReference>)[] | Readonly<Record<string, AccountReference | LookupReference<AccountReference>>> | RepeatOutputProjection<AccountReference>, options?: { readonly after?: readonly CashflowReference[]; }): ExpressionReference

const openingDebt = deccf.expr.multiply(
  deccf.expr.balance(debtAccounts.outputs.debt),
  -1,
);

const selectedDebt = deccf.expr.balance(
  deccf.lookup(debtAccounts.outputs.debt, loanRow.id),
);

deccf.expr.divideexpr.divide provides divide in the Core model API model editor. Use it when a model needs this operation.

(left: ExpressionOperand, right: ExpressionOperand): ExpressionReference

const { divide } = deccf.expr;

deccf.expr.eqexpr.eq provides eq in the Core model API model editor. Use it when a model needs this operation.

(left: ExpressionOperand, right: ExpressionOperand): ExpressionReference

const taxes = personalTax({
  person,
  rules: { municipalRate, communityMember: expr.eq(churchChoice, "yes"), communityFeeRate, burialFeeRate },
  taxBases: {
    [B.INK1_10_1]: { amount: taxableBusinessProfit, period: "annual" },
    [B.TAX_LIABILITY_SELF_EMPLOYMENT]: { amount: selectedContributions, period: "annual" },
  },
  propertyAssessments: [
    { assessmentValue, buildingYear: 1980, ownershipShare: 0.5 },
  ],
});

deccf.expr.flowexpr.flow provides flow in the Core model API model editor. Use it when a model needs this operation.

(reference: CashflowReference): ExpressionReference

const { flow } = deccf.expr;

deccf.expr.maxexpr.max provides max in the Core model API model editor. Use it when a model needs this operation.

(left: ExpressionOperand, right: ExpressionOperand): ExpressionReference

const { max } = deccf.expr;

deccf.expr.minexpr.min provides min in the Core model API model editor. Use it when a model needs this operation.

(left: ExpressionOperand, right: ExpressionOperand): ExpressionReference

const { min } = deccf.expr;

deccf.expr.moneyexpr.money provides money in the Core model API model editor. Use it when a model needs this operation.

(value: ExpressionOperand): ExpressionReference

const { money } = deccf.expr;

deccf.expr.multiplyexpr.multiply provides multiply in the Core model API model editor. Use it when a model needs this operation.

(left: ExpressionOperand, right: ExpressionOperand): ExpressionReference

const openingDebt = deccf.expr.multiply(
  deccf.expr.balance(debtAccounts.outputs.debt),
  -1,
);

const selectedDebt = deccf.expr.balance(
  deccf.lookup(debtAccounts.outputs.debt, loanRow.id),
);

deccf.expr.netCashexpr.netCash provides net cash in the Core model API model editor. Use it when a model needs this operation.

(reference: EntityReference): ExpressionReference

const cash = formulas.series.running({
  name:"cash", source:expr.netCash(owner), operation:"sum", initial:opening,
});

const minimum = formulas.series.running({
  name:"minimum", source:cash, operation:"min", initial:opening,
});

deccf.expr.subtractexpr.subtract provides subtract in the Core model API model editor. Use it when a model needs this operation.

(left: ExpressionOperand, right: ExpressionOperand): ExpressionReference

const opening = calculation({
  name:"opening", calculate:expr.subtract(capital, purchaseCosts),
});

const bank = account({ owner, type:"asset", initial:opening });

const reserve = metric({ value:opening, label:"Starting cash" });

deccf.expr.sumexpr.sum provides sum in the Core model API model editor. Use it when a model needs this operation.

(values: readonly ExpressionOperand[] | Readonly<Record<string, ExpressionOperand>> | RepeatOutputProjection<CalculationReference | CalculationProjectionReference | CashflowReference> | RepeatColumnReference, options?: { readonly resultType?: CalculationResultType; readonly currency?: Currency; }): ExpressionReference

const annualTotal = deccf.expr.sum(deccf.column(rows, "annual"), {
  resultType: "money",
  currency: deccf.currencies.SEK,
});

deccf.expr.whenexpr.when provides when in the Core model API model editor. Use it when a model needs this operation.

(condition: boolean | InputReference<boolean> | InputProjectionReference | LookupReference | CalculationReference | CalculationProjectionReference | ExpressionReference, whenTrue: ExpressionOperand, whenFalse: ExpressionOperand): ExpressionReference

const ownCost = input.lockable(true,
  input.money(1000, currencies.SEK, { ui: { label: "Monthly cost" } }));

const enabled = input.boolean(true, { ui: "check" });

const chosenCost = expr.when(enabled, ownCost.value, money(0, currencies.SEK));

deccf.fieldDeclares a stateful numeric field with an initial value and optional period-to-period update callback.

(options: FieldOptions): FieldReference

const { currencies, defineModel, entity, field, periods } = deccf;

const property = entity.asset({
  fields: {
    occupancy: field({ initial: 0.9, next: (previous) => previous }),
  },
});

const investor = entity.party({ parent: property });

const model = defineModel({
  name: "property-ownership",
  currency: currencies.SEK,
  timeline: periods.annual({ from: "2026-01", count: 1 }),
  entities: { property, investor },
});

return model;

deccf.flowGroupGroups flows and named inputs under shared settings such as owner, direction, or schedule. Its preconditions may reuse input handles already declared in an input domain; the group reads the same declared input rather than creating another input.

(options: FlowGroupOptions): FlowGroupReference

const { cashflow, currencies, defineModel, entity, flowGroup, flows, outflow, periods, schedule } = deccf;

const company = entity.asset();

const operatingCosts = flowGroup({
  name: "operatingCosts",
  owner: company,
  direction: outflow,
  schedule: schedule.monthly(),
  flows: [
    cashflow({ name: "rent", amount: 12_000 }),
    cashflow({ name: "insurance", schedule: schedule.annual(), amount: 2_400 }),
  ],
});

const model = defineModel({
  currency: currencies.SEK,
  timeline: periods.monthly({ from: "2026-01", count: 12 }),
  entities: { company },
  flows: flows(operatingCosts),
});

return model;

deccf.flowsFlattens nested flow groups into flow references while preserving inherited defaults for defineModel().

(...declarations: (FlowGroupItem | readonly FlowGroupItem[])[]): readonly CashflowReference[]

const { cashflow, currencies, defineModel, entity, flowGroup, flows, outflow, periods, schedule } = deccf;

const company = entity.asset();

const operatingCosts = flowGroup({
  name: "operatingCosts",
  owner: company,
  direction: outflow,
  schedule: schedule.monthly(),
  flows: [
    cashflow({ name: "rent", amount: 12_000 }),
    cashflow({ name: "insurance", schedule: schedule.annual(), amount: 2_400 }),
  ],
});

const model = defineModel({
  currency: currencies.SEK,
  timeline: periods.monthly({ from: "2026-01", count: 12 }),
  entities: { company },
  flows: flows(operatingCosts),
});

return model;

deccf.frequenciesProvides named period frequencies used by time and schedule helpers.

Readonly<{ day: Readonly<{ unit: "day"; size: 1; }>; week: Readonly<{ unit: "day"; size: 7; }>; month: Readonly<{ unit: "month"; size: 1; }>; quarter: Readonly<{ unit: "month"; size: 3; }>; year: Readonly<{ unit: "month"; size: 12; }>; }>

const { frequencies } = deccf;

deccf.fundingAllocates funding from one or more sources to a target while recording the resulting transfers.

(options: FundingOptions): ComponentReference<FundingOutputs>

const { funding } = deccf;

deccf.inflowMarks a cashflow as money entering the model owner's cash position.

CashflowDirection

const { inflow } = deccf;

deccf.inputProvides typed factories for model inputs, including numbers, enums, objects, arrays, dates, and distributions.

Readonly<InputFactory>

const { input } = deccf;

deccf.input.aspectDeclares a named object of typed inputs using the aspect layout. Optional constraints defaults to [] and declares relations {left,relation,right,message?} between leaves inside this object. Paths are relative safe dot-separated field names; array traversal, prototype keys, unknown paths, accessors and incompatible endpoint types are rejected at declaration. Supported relations are <, <=, >, >=, == and !=. Numeric scalar kinds can be mixed; Money endpoints must use the same currency and compare nominal amounts; dates compare chronological instants (a year-month means its first day). After input normalization and leaf validation, each failed relation adds DECCF_INPUT_DOMAIN at its left leaf path using message or a generated relation. Optional missing or already invalid endpoints produce no duplicate relation error. Rules and resolved values remain immutable; no callback is needed. Constraints can be attached to concrete object variants, but not the variant chooser or a path crossing variants. Optional ui.note displays plain text after this object's fields, at the end of its group, tab or page. It defaults to absent; blank and non-string values display nothing. Notes add no stored input or calculation value and are not supported on scalars, arrays or custom widgets. A compact sumdropdown object does not display a note. See Organize inputs into pages, tabs and groups for a callable example.

<TFields extends InputObjectFields>(fields: TFields, options?: ObjectConstraintOptions): ObjectInputReference<TFields>

const savings = deccf.input.aspect({
  annualSavings: deccf.input.money(25000, deccf.currencies.SEK),
}, {ui:{label:"Savings",note:"Enter the same nominal amount for each year."}});

deccf.input.booleanDeclares an editable true-or-false input, optionally displayed as a switch or checkbox.

(value: boolean, options?: BooleanInputOptions): InputReference<boolean>

const ownCost = input.lockable(true,
  input.money(1000, currencies.SEK, { ui: { label: "Monthly cost" } }));

const enabled = input.boolean(true, { ui: "check" });

const chosenCost = expr.when(enabled, ownCost.value, money(0, currencies.SEK));

deccf.input.boolenAlias of boolean, retained for existing models.

(value: boolean, options?: BooleanInputOptions): InputReference<boolean>

const { boolen } = deccf.input;

deccf.input.curveinput.curve provides curve in the Core model API model editor. Use it when a model needs this operation.

(points: readonly { readonly date: DateString; readonly value: number; }[], options?: CurveOptions): InputReference<number>

const { cashflow, currencies, defineModel, entity, inflow, input, periods, schedule } = deccf;

const price = input.curve([
  { date: "2026-01", value: 100 },
  { date: "2026-07", value: 110 },
], { interpolation: "linear" });

const asset = entity.asset();

const value = cashflow({
  dynamic:true,
  owner: asset,
  direction: inflow,
  schedule: schedule.monthly(),
  amount: (ctx) => ctx.get(price),
});

const model = defineModel({
  name: "dated-price-curve",
  currency: currencies.SEK,
  timeline: periods.monthly({ from: "2026-01", count: 12 }),
  preconditions: { price },
  entities: { asset },
  flows: { value },
});

return model;

deccf.input.dateinput.date provides date in the Core model API model editor. Use it when a model needs this operation.

(value: DateString | null, options?: InputOptions<DateString | null>): InputReference<DateString | null>

const reportDate = deccf.input.date('2028-01');

const finalValue = deccf.metric({
  schedule:deccf.schedule.once(reportDate),
  calculate:ctx=>ctx.time.index+1,
});

return deccf.defineModel({
  currency:deccf.currencies.USD,
  timeline:deccf.periods.annual({from:'2026-01', count:3}),
  preconditions:{reportDate}, metrics:{finalValue},
});

deccf.input.decimalDeclares an editable decimal input with optional numeric limits and display metadata.

(value: number, options?: InputOptions<number>): InputReference<number>

const salary = input.money(480000, currencies.SEK, {domain: deccf.sym.pos});

const paymentWeight = input.decimal(1, {domain: deccf.sym.max100});

const share = input.fraction(.5, {domain: deccf.sym.max1});

const budgetMode = input.enum('after', {
  options: modules.household.sym.budgetMode('en'),
  ui: {label: 'Budget mode'},
});

deccf.input.domainDeclares a named object of typed inputs using the domain layout. Optional constraints defaults to [] and declares relations {left,relation,right,message?} between leaves inside this object. Paths are relative safe dot-separated field names; array traversal, prototype keys, unknown paths, accessors and incompatible endpoint types are rejected at declaration. Supported relations are <, <=, >, >=, == and !=. Numeric scalar kinds can be mixed; Money endpoints must use the same currency and compare nominal amounts; dates compare chronological instants (a year-month means its first day). After input normalization and leaf validation, each failed relation adds DECCF_INPUT_DOMAIN at its left leaf path using message or a generated relation. Optional missing or already invalid endpoints produce no duplicate relation error. Rules and resolved values remain immutable; no callback is needed. Constraints can be attached to concrete object variants, but not the variant chooser or a path crossing variants. Optional ui.note displays plain text after this object's fields, at the end of its group, tab or page. It defaults to absent; blank and non-string values display nothing. Notes add no stored input or calculation value and are not supported on scalars, arrays or custom widgets. A compact sumdropdown object does not display a note. See Organize inputs into pages, tabs and groups for a callable example.

<TFields extends InputObjectFields>(fields: TFields, options?: ObjectConstraintOptions): DomainInputReference<TFields>

const currentAge = deccf.input.integer(45);
const retirementAge = deccf.input.integer(65);
const lifeExpectancy = deccf.input.integer(95);
const domain = deccf.input.domain({personal: deccf.input.object({currentAge, retirementAge, lifeExpectancy})}, {
  constraints: [
    {left: "personal.currentAge", relation: "<=", right: "personal.retirementAge"},
    {left: "personal.retirementAge", relation: "<=", right: "personal.lifeExpectancy", message: "Retirement must not follow life expectancy."},
  ],
});
return deccf.defineModel({currency: deccf.currencies.USD,
  timeline: deccf.periods.annual({from: "2026-01", count: 1}), preconditions: domain});

deccf.input.enumDeclares a choice input from explicit stored values and display labels.

<T extends string>(value: T, options: EnumInputOptions<T>): InputReference<T>

const homeDecision = input.enum('keep', {
  options: modules.housing.sym.keepSellBuy('en'),
});

deccf.input.familyRoleinput.familyRole provides family role in the Core model API model editor. Use it when a model needs this operation.

(value: "adult" | "child", options?: InputOptions<"adult" | "child">): InputReference<"adult" | "child">

const members = input.objectArray([
  {id:input.id("anna"), name:input.str("Anna"), role:input.familyRole("adult")},
  {id:input.id("erik"), name:input.str("Erik"), role:input.familyRole("adult")},
]);

const person = members.item.data;

const taxOwnership = input.objectArray([{
  personId:input.hidden(person.id),
  name:input.readOnly(person.name),
  share:input.fraction(.5),
}], {connectedSource:members, connectedWhere:{role:"adult"}, dynamic:false});

const domain = input.domain({
  family:input.section({members}),
  ownership:input.section({taxOwnership}),
});

deccf.input.fractioninput.fraction provides fraction in the Core model API model editor. Use it when a model needs this operation.

(value: number, options?: InputOptions<number>): InputReference<number>

const salary = input.money(480000, currencies.SEK, {domain: deccf.sym.pos});

const paymentWeight = input.decimal(1, {domain: deccf.sym.max100});

const share = input.fraction(.5, {domain: deccf.sym.max1});

const budgetMode = input.enum('after', {
  options: modules.household.sym.budgetMode('en'),
  ui: {label: 'Budget mode'},
});

deccf.input.groupDeclares a named object of typed inputs using the group layout. Optional constraints defaults to [] and declares relations {left,relation,right,message?} between leaves inside this object. Paths are relative safe dot-separated field names; array traversal, prototype keys, unknown paths, accessors and incompatible endpoint types are rejected at declaration. Supported relations are <, <=, >, >=, == and !=. Numeric scalar kinds can be mixed; Money endpoints must use the same currency and compare nominal amounts; dates compare chronological instants (a year-month means its first day). After input normalization and leaf validation, each failed relation adds DECCF_INPUT_DOMAIN at its left leaf path using message or a generated relation. Optional missing or already invalid endpoints produce no duplicate relation error. Rules and resolved values remain immutable; no callback is needed. Constraints can be attached to concrete object variants, but not the variant chooser or a path crossing variants. Optional ui.note displays plain text after this object's fields, at the end of its group, tab or page. It defaults to absent; blank and non-string values display nothing. Notes add no stored input or calculation value and are not supported on scalars, arrays or custom widgets. A compact sumdropdown object does not display a note. See Organize inputs into pages, tabs and groups for a callable example.

<TFields extends InputObjectFields>(fields: TFields, options?: ObjectConstraintOptions): ObjectInputReference<TFields>

const inflation = deccf.input.rate(0.02, {ui: {label: "Annual inflation"}});

const assumptions = deccf.input.group({inflation});

const owner = deccf.entity.party();

const income = deccf.cashflow({
  owner,
  direction: deccf.inflow,
  schedule: deccf.schedule.annual(),
  amount: 10200,
});

const model = deccf.defineModel({
  currency: deccf.currencies.SEK,
  timeline: deccf.periods.annual({from: "2026-01", count: 2}),
  preconditions: {assumptions},
  inflation,
  entities: {owner},
  flows: {income},
});

const result = deccf.run(model, {moneyValue: "today"});

return model;

deccf.input.groupsgroups(source, fields, options={}) returns an ordinary connected keyed object-array: {id,name,...fields} per selected source row. source is a keyed object-array with a string label field; label defaults to 'name'. fields contains typed inputs, including nested lists/objects. id/name are reserved protected fields: hidden id follows the source key, name its label/heading. where is an all-match scalar-equality map (default no filter). rows defaults to []: typed objectArray initial maps require id:input.id(...) or input.str(...) matching a source; optional name cannot override its label. Other groups use field defaults. ui, visible, required, title, type ('cards' default or 'table') retain ordinary semantics; other options reject. Rename/reorder preserves surviving nested edits; additions use defaults, removals remove groups. Outer add/remove controls are absent; nested lists retain theirs. Register both inputs. item.data, repeat(), column(), JSON, saved cases and scenarios work as for objectArray. Money stays Money; rates are fractions (0.02=2%). Invalid sources, fields, label/where, reserved fields or typed rows reject at declaration; submitted values retain input/connection validation.

<TSource extends InputObjectFields, TFields extends InputObjectFields>(source: ObjectArrayInputReference<TSource>, fields: TFields & { readonly id?: never; readonly name?: never; }, options?: GroupsInputOptions<TSource, TFields>): ObjectArrayInputReference<TFields & { readonly id: InputReference<string>; readonly name: InputReference<string>; }>

const projects = deccf.input.objectArray([{
  id: deccf.input.id("workshop"), name: deccf.input.str("Workshop"),
  active: deccf.input.boolean(true),
}]);
const budgets = deccf.input.groups(projects, {
  costs: deccf.input.objectArray([{
    id: deccf.input.id("equipment"),
    amount: deccf.input.money(1200, deccf.currencies.SEK),
  }]),
}, {where: {active: true}});
const cost = deccf.calculation({
  name: "Project cost",
  calculate: deccf.expr.sum(deccf.column(budgets.item.data.costs, "amount"), {
    resultType: "money", currency: deccf.currencies.SEK,
  }),
});
const perProject = deccf.repeat(budgets, deccf.component({
  calculations: {cost}, outputs: {cost},
}));
const model = deccf.defineModel({
  currency: deccf.currencies.SEK,
  timeline: deccf.periods.monthly({from: "2026-01", count: 1}),
  preconditions: {projects, budgets}, components: {perProject},
  metrics: {projectCost: deccf.metric({value: deccf.expr.sum(perProject.outputs.cost, {resultType: "money"})})},
});

return model;

deccf.input.hiddeninput.hidden provides hidden in the Core model API model editor. Use it when a model needs this operation.

<T extends InputReference<InputValue>>(value: T, options?: InputMetadataOptions): T
<T extends InputValue>(value: InputProjectionReference<T> | T, options?: InputMetadataOptions): InputReference<T>

const isk = deccf.input.Object({
  type: deccf.input.hidden("isk"),
  amount: deccf.input.money(2500, deccf.currencies.SEK),
  annualReturn: deccf.input.rate(0.02),
}, {label: "ISK"});

const vp = deccf.input.Object({
  type: deccf.input.hidden("vp"),
  amount: deccf.input.money(2500, deccf.currencies.SEK),
  annualReturn: deccf.input.rate(0.02),
}, {label: "VP-konto"});

const savings = deccf.input.objectArray([isk, vp], {type: "manyOfAnyChangeable", title: "Sparande"});

const selectedSavings = deccf.input.Object([isk, vp], {title: "Sparande"});

deccf.input.idinput.id provides id in the Core model API model editor. Use it when a model needs this operation.

(value: string, options?: InputOptions<string>): InputReference<string>
(options: Readonly<{ generate: "uuid"; }>, metadata?: Omit<InputOptions<string>, "newItem">): InputReference<string | undefined>

const projects = deccf.input.objectArray([{
  id:deccf.input.id("workshop"), name:deccf.input.str("Workshop"),
  active:deccf.input.boolean(true),
}]);

const budgets = deccf.input.groups(projects, {
  costs:deccf.input.objectArray([{
    id:deccf.input.id("equipment"),
    amount:deccf.input.money(1200, deccf.currencies.SEK),
  }]),
}, {where:{active:true}, ui:{label:"Project budgets"}});

deccf.input.integerDeclares an editable whole-number input.

(value: number, options?: InputOptions<number>): InputReference<number>

const age = deccf.input.integer(60);

const earliest = deccf.analysis.first({input: age, from: 60, to: 75, metric: "feasible", atLeast: 1});

deccf.input.lockableinput.lockable provides lockable in the Core model API model editor. Use it when a model needs this operation.

<T extends InputReference<InputValue>>(locked: boolean, value: T, options?: InputMetadataOptions): LockableInputReference<T>

const ownCost = input.lockable(true,
  input.money(1000, currencies.SEK, { ui: { label: "Monthly cost" } }));

const enabled = input.boolean(true, { ui: "check" });

const chosenCost = expr.when(enabled, ownCost.value, money(0, currencies.SEK));

deccf.input.logNormalinput.logNormal provides log normal in the Core model API model editor. Use it when a model needs this operation.

(parameters: { readonly mu: number; readonly sigma: number; readonly clip?: NumericDomain; }, options?: DistributionOptions): InputReference<number>

const { logNormal } = deccf.input;

deccf.input.moneyDeclares an editable money input with a typed currency. Optional ui.initialValueFrom copies a missing saved UI field from an absolute object-field path before using its declared default. Optional ui.initialValueScale defaults to 1 and multiplies a copied finite number or Money amount, preserving currency and other Money data; it must be finite and positive. Invalid scales, unsupported source values and nonfinite results use the declared default. Explicit target values, including zero, win and are never scaled. Unknown or malformed paths, accessors, inherited properties and array-row paths use the normal default. Saved scenario selections of a retired hidden leaf follow its unique editable replacement alias and scale; explicit replacement selections win. Protected ancestors, readonly fields, connected values and array-row selections retain their normal restrictions. Saved inputs are not mutated. This affects opening case and scenario drafts only; direct calculation input validation is unchanged.

(amount: number, denomination: Currency, options?: InputOptions<Money>): InputReference<Money>

const annualIncome = deccf.input.money(42000, deccf.currencies.USD, {
  required:false,
  ui:{initialValueFrom:"domain.income.monthlyIncome", initialValueScale:12}
});

deccf.input.normalinput.normal provides normal in the Core model API model editor. Use it when a model needs this operation.

(parameters: { readonly mean: number; readonly stdev: number; readonly clip?: NumericDomain; }, options?: DistributionOptions): InputReference<number>

const income = deccf.input.normal({mean:42000,stdev:3000});

const salary = deccf.cashflow({
  dynamic:true, direction:deccf.inflow, schedule:deccf.schedule.annual(),
  amount:ctx=>Math.max(0,ctx.sample(income)),
});

return deccf.defineModel({
  currency:deccf.currencies.SEK,
  timeline:deccf.periods.annual({from:'2026-01',count:3}),
  preconditions:{income}, flows:{salary},
});

deccf.input.objectDeclares a named object of typed inputs using the object layout. Variant catalogues contain ordinary input.Object(fields, {label}) references (input.object is the lowercase alias). Each needs a non-empty label and a unique non-empty string type declared with input.hidden('isk'), for example. Values are ordinary objects with a hidden type discriminator; rates are decimal fractions, so input.rate(0.02) means 2%. Empty or malformed catalogues, missing labels, missing/non-hidden/non-string/duplicate type values, incompatible options and unknown saved type values produce explicit errors. Saved malformed or unknown choices remain visible for correction rather than defaulting to the first choice. The active variant controls nested input validation, hidden/readonly fields, locks and money currency handling. New variant declarations do not support connectedSource or connectionBinding; these produce explicit errors, including bindings inside variant fields. Existing ordinary connected arrays retain their behavior. Switching an editable choice preserves identity and common field values only when names, value types and units/currencies match; target-specific fields use their declared initial defaults and inactive fields are removed. There is no cache of inactive edits. Preserved values outside target bounds remain available with normal validation errors. Generated collection identities never change the original variant reference or its standalone choice value. Object(variants, {title}?) and object(variants, {title}?) return one alternative object input, defaulting to the first catalogue entry. Its always-editable selector uses title as its label; the active fields follow in normal layout flow. A standalone choice has no generated collection id. Object(fields, options?) and object(fields, options?) still group ordinary fields, including the existing sumdropdown layout. describeModel() exposes discriminator:'type', variants:[{value,label,schema}], and fallback fields/value from the first variant; active fields come from the selected variant schema. Optional constraints defaults to [] and declares relations {left,relation,right,message?} between leaves inside this object. Paths are relative safe dot-separated field names; array traversal, prototype keys, unknown paths, accessors and incompatible endpoint types are rejected at declaration. Supported relations are <, <=, >, >=, == and !=. Numeric scalar kinds can be mixed; Money endpoints must use the same currency and compare nominal amounts; dates compare chronological instants (a year-month means its first day). After input normalization and leaf validation, each failed relation adds DECCF_INPUT_DOMAIN at its left leaf path using message or a generated relation. Optional missing or already invalid endpoints produce no duplicate relation error. Rules and resolved values remain immutable; no callback is needed. Constraints can be attached to concrete object variants, but not the variant chooser or a path crossing variants. Optional ui.note displays plain text after this object's fields, at the end of its group, tab or page. It defaults to absent; blank and non-string values display nothing. Notes add no stored input or calculation value and are not supported on scalars, arrays or custom widgets. A compact sumdropdown object does not display a note. See Organize inputs into pages, tabs and groups for a callable example.

<const TVariants extends ObjectVariantCatalogue>(variants: TVariants, options?: ObjectVariantOptions): ObjectVariantInputReference<TVariants>
<TFields extends InputObjectFields>(fields: TFields, options?: ObjectInputOptions): ObjectInputReference<TFields>

const isk = deccf.input.Object({
  type: deccf.input.hidden("isk"),
  amount: deccf.input.money(2500, deccf.currencies.SEK),
  annualReturn: deccf.input.rate(0.02),
  taxRate: deccf.input.rate(0.01),
}, {label: "ISK"});
const vp = deccf.input.Object({
  type: deccf.input.hidden("vp"),
  amount: deccf.input.money(2500, deccf.currencies.SEK),
  annualReturn: deccf.input.rate(0.02),
  fundFee: deccf.input.rate(0.005),
}, {label: "VP-konto"});
const savings = deccf.input.object([isk, vp], {title: "Sparande"});
// Register savings in preconditions. It starts with ISK, amount 2500 SEK and a 2% annual return.

deccf.input.ObjectDeclares a named object of typed inputs using the Object layout. Variant catalogues contain ordinary input.Object(fields, {label}) references (input.object is the lowercase alias). Each needs a non-empty label and a unique non-empty string type declared with input.hidden('isk'), for example. Values are ordinary objects with a hidden type discriminator; rates are decimal fractions, so input.rate(0.02) means 2%. Empty or malformed catalogues, missing labels, missing/non-hidden/non-string/duplicate type values, incompatible options and unknown saved type values produce explicit errors. Saved malformed or unknown choices remain visible for correction rather than defaulting to the first choice. The active variant controls nested input validation, hidden/readonly fields, locks and money currency handling. New variant declarations do not support connectedSource or connectionBinding; these produce explicit errors, including bindings inside variant fields. Existing ordinary connected arrays retain their behavior. Switching an editable choice preserves identity and common field values only when names, value types and units/currencies match; target-specific fields use their declared initial defaults and inactive fields are removed. There is no cache of inactive edits. Preserved values outside target bounds remain available with normal validation errors. Generated collection identities never change the original variant reference or its standalone choice value. Object(variants, {title}?) and object(variants, {title}?) return one alternative object input, defaulting to the first catalogue entry. Its always-editable selector uses title as its label; the active fields follow in normal layout flow. A standalone choice has no generated collection id. Object(fields, options?) and object(fields, options?) still group ordinary fields, including the existing sumdropdown layout. describeModel() exposes discriminator:'type', variants:[{value,label,schema}], and fallback fields/value from the first variant; active fields come from the selected variant schema. Optional constraints defaults to [] and declares relations {left,relation,right,message?} between leaves inside this object. Paths are relative safe dot-separated field names; array traversal, prototype keys, unknown paths, accessors and incompatible endpoint types are rejected at declaration. Supported relations are <, <=, >, >=, == and !=. Numeric scalar kinds can be mixed; Money endpoints must use the same currency and compare nominal amounts; dates compare chronological instants (a year-month means its first day). After input normalization and leaf validation, each failed relation adds DECCF_INPUT_DOMAIN at its left leaf path using message or a generated relation. Optional missing or already invalid endpoints produce no duplicate relation error. Rules and resolved values remain immutable; no callback is needed. Constraints can be attached to concrete object variants, but not the variant chooser or a path crossing variants. Optional ui.note displays plain text after this object's fields, at the end of its group, tab or page. It defaults to absent; blank and non-string values display nothing. Notes add no stored input or calculation value and are not supported on scalars, arrays or custom widgets. A compact sumdropdown object does not display a note. See Organize inputs into pages, tabs and groups for a callable example.

<const TVariants extends ObjectVariantCatalogue>(variants: TVariants, options?: ObjectVariantOptions): ObjectVariantInputReference<TVariants>
<TFields extends InputObjectFields>(fields: TFields, options?: ObjectInputOptions): ObjectInputReference<TFields>

const isk = deccf.input.Object({
  type: deccf.input.hidden("isk"),
  amount: deccf.input.money(2500, deccf.currencies.SEK),
  annualReturn: deccf.input.rate(0.02),
  taxRate: deccf.input.rate(0.01),
}, {label: "ISK"});
const vp = deccf.input.Object({
  type: deccf.input.hidden("vp"),
  amount: deccf.input.money(2500, deccf.currencies.SEK),
  annualReturn: deccf.input.rate(0.02),
  fundFee: deccf.input.rate(0.005),
}, {label: "VP-konto"});
const savings = deccf.input.Object([isk, vp], {title: "Sparande"});
// Register savings in preconditions. It starts with ISK, amount 2500 SEK and a 2% annual return.

deccf.input.objectArrayCreates mixed rows from object variants. `type` is `manyOfAnyChangeable`, `manyOfAny` or `anyOf`. Example: `deccf.input.objectArray([isk, vp], {type: "manyOfAnyChangeable", title: "Sparande"})`. Variant catalogues contain ordinary input.Object(fields, {label}) references (input.object is the lowercase alias). Each needs a non-empty label and a unique non-empty string type declared with input.hidden('isk'), for example. Values are ordinary objects with a hidden type discriminator; rates are decimal fractions, so input.rate(0.02) means 2%. Empty or malformed catalogues, missing labels, missing/non-hidden/non-string/duplicate type values, incompatible options and unknown saved type values produce explicit errors. Saved malformed or unknown choices remain visible for correction rather than defaulting to the first choice. The active variant controls nested input validation, hidden/readonly fields, locks and money currency handling. New variant declarations do not support connectedSource or connectionBinding; these produce explicit errors, including bindings inside variant fields. Existing ordinary connected arrays retain their behavior. Switching an editable choice preserves identity and common field values only when names, value types and units/currencies match; target-specific fields use their declared initial defaults and inactive fields are removed. There is no cache of inactive edits. Preserved values outside target bounds remain available with normal validation errors. Generated collection identities never change the original variant reference or its standalone choice value. objectArray(rows, options?) retains homogeneous initial rows, optional item/key schema, cards/table views and dynamic membership unless options.type is explicitly manyOfAnyChangeable, manyOfAny or anyOf. These three calls interpret the first array as a variant catalogue, return a keyed array input and start empty. Optional title labels the collection. manyOfAnyChangeable adds the first variant immediately, permits repeated types and gives each card an editable selector. manyOfAny offers variant labels in the add menu, permits repeated types and fixes each existing card's type. anyOf uses that menu and fixed cards but allows at most one row per type; used types are disabled, deletion reenables a type and add is disabled when all are present. Uniqueness is also validated on submitted calculation data. Fixed cards restrict draft editing, not otherwise valid replacement calculation inputs. New rows use the selected variant's authored initial values, rather than homogeneous-array zero/empty new-row defaults. Without an explicit key, each newly added row receives a fresh hidden id; saved identities remain stable and describing/compiling generates no IDs. Existing explicit keys are supported. describeModel() exposes selectionMode matching options.type, view:'cards' and an alternative object item with discriminator:'type' and variants:[{value,label,schema}]. Within repeat(rows, component), rows.item.value supplies the complete immutable typed row to calculation or cashflow bindings. It retains the stable row key, active variant discriminator and all selected variant fields, nested objects/arrays and Money values; inactive variant fields are absent. Branch on row.type when variants have different financial assumptions. rows.item.data.<field> remains the existing symbolic field view, not the whole row, and is not expanded with inactive fields. Nested row/object views also expose value and resolve in their own enclosing row scope. Reordering, replacing or deleting rows refreshes bindings at each run; an empty collection creates no components. Use expr.sum with an explicit resultType (and currency for Money) for a typed zero over empty outputs. These row references require their declared collection and a matching repeat row scope; merely declaring or separately repeating the collection does not supply a current row, and a missing scope rejects with DECCF_UNDECLARED_REFERENCE. Whole-row Money follows the selected run currency exactly as ordinary input reads; foreign-currency values stay unchanged. Invalid input rows retain ordinary input validation errors.

<const TVariants extends ObjectVariantCatalogue, TKey extends string = "id">(variants: TVariants, options: ObjectVariantArrayOptions<TKey>): ObjectVariantArrayInputReference<TVariants, TKey>
<TFields extends InputObjectFields>(rows: readonly TFields[] | readonly ObjectInputReference<TFields>[], options?: ObjectArrayOptions<TFields>): ObjectArrayInputReference<TFields>

const isk = deccf.input.Object({
  type: deccf.input.hidden("isk"),
  amount: deccf.input.money(2500, deccf.currencies.SEK),
  annualReturn: deccf.input.rate(0.02),
  taxRate: deccf.input.rate(0.01),
}, {label: "ISK"});
const vp = deccf.input.Object({
  type: deccf.input.hidden("vp"),
  amount: deccf.input.money(2500, deccf.currencies.SEK),
  annualReturn: deccf.input.rate(0.02),
  fundFee: deccf.input.rate(0.005),
}, {label: "VP-konto"});
const changeable = deccf.input.objectArray([isk, vp], {type: "manyOfAnyChangeable", title: "Sparande"});
const fixed = deccf.input.objectArray([isk, vp], {type: "manyOfAny", title: "Sparande"});
const unique = deccf.input.objectArray([isk, vp], {type: "anyOf", title: "Sparande"});
const projected = deccf.calculation({
  name: "projected", resultType: "money", bindings: {row: changeable.item.value},
  calculate: ({row}) => deccf.money(
    row.amount.amount * (1 + row.annualReturn - (row.type === "isk" ? row.taxRate : row.fundFee)),
    row.amount.currency,
  ),
});
const accounts = deccf.repeat(changeable, deccf.component({
  calculations: {projected}, outputs: {projected},
}));
const total = deccf.calculation({
  name: "total", calculate: deccf.expr.sum(accounts.outputs.projected, {resultType: "money", currency: deccf.currencies.SEK}),
});
const model = deccf.defineModel({
  currency: deccf.currencies.SEK, timeline: deccf.periods.annual({from: "2026-01", count: 1}),
  preconditions: {changeable, fixed, unique}, components: {accounts}, calculations: {total},
});
// Empty accounts produce a total of 0 SEK; added cards contribute their selected variant's result.

deccf.input.rateDeclares an editable rate input, usually representing an annual or period rate. Optional ui.initialValueFrom initializes a missing saved UI field from an absolute object-field path before using its declared default; supplied target values, including zero, win. It defaults to absent. Optional ui.initialValueScale defaults to 1 and multiplies a copied finite number or Money amount while preserving currency. The scale must be finite and positive; invalid scales, unsupported source values and nonfinite results use the declared default. Explicit target values are never scaled. Unknown or malformed paths, accessors, inherited properties and array-row paths use the normal default. Reads do not mutate saved inputs. This is UI draft initialization only; direct calculation input validation is unchanged.

(value: number, options?: InputOptions<number>): InputReference<number>

const growth = deccf.input.rate(0, {ui:{initialValueFrom:"domain.legacyGrowth"}});

deccf.input.readonlyinput.readonly provides readonly in the Core model API model editor. Use it when a model needs this operation.

<T extends InputReference<InputValue>>(value: T, options?: InputMetadataOptions): T
<T extends InputValue>(value: InputProjectionReference<T> | T, options?: InputMetadataOptions): InputReference<T>

const { readonly } = deccf.input;

deccf.input.readOnlyinput.readOnly provides read only in the Core model API model editor. Use it when a model needs this operation.

<T extends InputReference<InputValue>>(value: T, options?: InputMetadataOptions): T
<T extends InputValue>(value: InputProjectionReference<T> | T, options?: InputMetadataOptions): InputReference<T>

const members = input.objectArray([
  {id:input.id("anna"), name:input.str("Anna"), role:input.familyRole("adult")},
  {id:input.id("erik"), name:input.str("Erik"), role:input.familyRole("adult")},
]);

const person = members.item.data;

const taxOwnership = input.objectArray([{
  personId:input.hidden(person.id),
  name:input.readOnly(person.name),
  share:input.fraction(.5),
}], {connectedSource:members, connectedWhere:{role:"adult"}, dynamic:false});

const domain = input.domain({
  family:input.section({members}),
  ownership:input.section({taxOwnership}),
});

deccf.input.sectionDeclares a named object of typed inputs using the section layout. Optional constraints defaults to [] and declares relations {left,relation,right,message?} between leaves inside this object. Paths are relative safe dot-separated field names; array traversal, prototype keys, unknown paths, accessors and incompatible endpoint types are rejected at declaration. Supported relations are <, <=, >, >=, == and !=. Numeric scalar kinds can be mixed; Money endpoints must use the same currency and compare nominal amounts; dates compare chronological instants (a year-month means its first day). After input normalization and leaf validation, each failed relation adds DECCF_INPUT_DOMAIN at its left leaf path using message or a generated relation. Optional missing or already invalid endpoints produce no duplicate relation error. Rules and resolved values remain immutable; no callback is needed. Constraints can be attached to concrete object variants, but not the variant chooser or a path crossing variants. Optional ui.note displays plain text after this object's fields, at the end of its group, tab or page. It defaults to absent; blank and non-string values display nothing. Notes add no stored input or calculation value and are not supported on scalars, arrays or custom widgets. A compact sumdropdown object does not display a note. See Organize inputs into pages, tabs and groups for a callable example.

<TFields extends InputObjectFields>(fields: TFields, options?: ObjectConstraintOptions): ObjectInputReference<TFields>

const { input } = deccf;

export const section1 = input.section({
  name: input.str("Anna"),
  amount: input.money(100, deccf.currencies.SEK),
});

deccf.input.sniAn empty value asks domain methods to infer the industry from account history.

(mainGroup?: string, options?: InputOptions<string>): InputReference<string>

const { input } = deccf;

const forecast = businessForecast({
  owner: company,
  schedule: schedule.monthly(),
  template: "industry",
  sni: input.sni("47"), // Retail trade
});

deccf.input.strDeclares an editable string input. ui.choicesFrom displays names from an input list, storing stable string keys: {path, key, label, where?}. path is an exact absolute input path; key is an ID/string field, label a string field. where is an optional all-match scalar-equality map (default all rows). Static ui.choices entries {value,label} remain available with empty sources or no matches. Values must be nonempty and unique across both lists. Renaming/reordering refreshes labels, retaining keys. Removed/filtered-out selections stay Unavailable and invalid until corrected; never automatically reassigned. Empty sources without static choices disable the control; zero filter matches offer no source rows. Invalid paths, fields, filters or duplicate keys show configuration errors. Blank labels show Unnamed item plus a number. Ordinary string input metadata only; domain components validate key meaning.

(value?: string, options?: InputOptions<string>): InputReference<string>

const projects = deccf.input.objectArray([{
  id: deccf.input.id("workshop"), name: deccf.input.str("Workshop"),
  active: deccf.input.boolean(true),
}]);
const target = deccf.input.str("shared", {ui: {
  label: "Project", choicesFrom: {path: "projects", key: "id", label: "name", where: {active: true}},
  choices: [{value: "shared", label: "Shared costs"}],
}});
// Register projects and target as inputs. Shared costs remains available with no active projects.

deccf.input.tableToSieinput.tableToSie provides table to sie in the Core model API model editor. Use it when a model needs this operation.

(defaultContent?: string, options?: TableToSieOptions): InputReference<string>

const { currencies, defineModel, entity, input, periods } = deccf;

const { stdaccount } = modules.accountplan;

const { sieStatement, thisYear } = modules["sie-import"];

const year = thisYear();

const compactDate = date => date.replaceAll("-", "");

const sampleSie = [
  "#SIETYP 1",
  `#RAR 0 ${compactDate(year.start)} ${compactDate(year.end)}`,
  '#KONTO 1930 "Cash at bank"',
  '#KONTO 2091 "Retained earnings"',
  "#UB 0 1930 100.00",
  "#UB 0 2091 -100.00",
].join("\n");

const company = entity.asset();

const sieContent = input.tableToSie(sampleSie, {
  dynamicAccounts: true,
  personalAccounts: true,
  businessAccounts: true,
  splitResAndUb: true,
  dynamicPeriods: true,
  fileDrop: true,
});

const bank = stdaccount({ code: "1930", owner: company });

const retainedEarnings = stdaccount({ code: "2091", owner: company });

const importedBalances = sieStatement({
  owner: company,
  sieContent,
});

const model = defineModel({
  name: "sie-balance-import",
  currency: currencies.SEK,
  timeline: periods.monthly({ from: "2025-01", count: 36 }),
  preconditions: { sieContent },
  entities: { company },
  accounts: { bank, retainedEarnings },
  flows: { importedBalances },
});

return model;

deccf.input.textfileinput.textfile provides textfile in the Core model API model editor. Use it when a model needs this operation.

(defaultText?: string, options?: InputOptions<string>): InputReference<string>

const { textfile } = deccf.input;

deccf.input.triangularinput.triangular provides triangular in the Core model API model editor. Use it when a model needs this operation.

(parameters: { readonly min: number; readonly mode: number; readonly max: number; readonly clip?: NumericDomain; }, options?: DistributionOptions): InputReference<number>

const { triangular } = deccf.input;

deccf.input.uniforminput.uniform provides uniform in the Core model API model editor. Use it when a model needs this operation.

(parameters: { readonly min: number; readonly max: number; readonly clip?: NumericDomain; }, options?: DistributionOptions): InputReference<number>

const {input,account,cashflow,inflow,schedule,bind,defineModel,currencies,periods}=deccf;

const currentAge=input.integer(40);

const chosenAges=input.objectArray([
  {id:input.id("later"),age:input.integer(41)},
]);

const ageSelection=input.object({automatic:input.boolean(true),ages:chosenAges});

const salesAmount=input.uniform({min:100,max:200});

const bank=account({initial:1000});

const sales=cashflow({direction:inflow,moves:bank,schedule:schedule.monthly(),
  bindings:{amount:bind.sample(salesAmount,{calendar:"annual"})},
  amount:({amount})=>amount});

return defineModel({
  name:"Shop cash forecast",currency:currencies.EUR,
  timeline:periods.monthly({from:"2026-11",count:16}),
  preconditions:{currentAge,ageSelection,salesAmount},
  accounts:{bank},flows:{sales},
  monteCarlo:{series:["account.bank.balance","flow.sales"]},
});

deccf.lifecycleDeclares states, an initial state, transitions, and optional actions for an entity lifecycle.

(options: { readonly states: readonly StateReference[]; readonly initial: StateReference; readonly transitions?: readonly StateTransition[]; readonly onEnter?: readonly Action[]; }): LifecycleReference

const { currencies, defineModel, entity, lifecycle, periods, state } = deccf;

const active = state("active");

const closed = state("closed");

const life = lifecycle({
  states: [active, closed],
  initial: active,
  transitions: [{ from: active, to: closed, when: (ctx) => ctx.time.index === 11 }],
});

const asset = entity.asset({ lifecycle: life });

const model = defineModel({
  name: "asset-lifecycle",
  currency: currencies.SEK,
  timeline: periods.monthly({ from: "2026-01", count: 12 }),
  entities: { asset },
});

return model;

deccf.lookupDeclares a keyed lookup whose values can be resolved during model evaluation.

<T extends ComponentOutputReference, F = never>(sourceMap: RepeatOutputProjection<T>, key: LookupKey, options?: LookupOptions<F>): LookupReference<T | F>
<T extends InputValue, F = never>(sourceMap: RepeatColumnReference<T>, key: LookupKey, options?: LookupOptions<F>): LookupReference<T | F>
<T, F = never>(sourceMap: Readonly<Record<string, T>>, key: LookupKey, options?: LookupOptions<F>): LookupReference<T | F>

const openingDebt = deccf.expr.multiply(
  deccf.expr.balance(debtAccounts.outputs.debt),
  -1,
);

const selectedDebt = deccf.expr.balance(
  deccf.lookup(debtAccounts.outputs.debt, loanRow.id),
);

deccf.metricDeclares a scalar or text result evaluated after simulation. Supply exactly one of calculate or value. periodLength and frequency default to 1 model period. An optional calendar schedule selects which of those otherwise-eligible periods to evaluate; it supports fixed dates and declared input/derived dates. The schedule intersects frequency and the requirement for a complete periodLength window. Omitting it preserves evaluation in every otherwise-eligible period. A skipped period does not create a context or call the metric callback; its series value is null. The summary keeps the last defined emitted value, or omits the metric if none is emitted. Trigger-relative schedules and undeclared schedule inputs fail validation. label/unit are optional presentation metadata; annualAggregation defaults to last, and fiscalYearStartMonth defaults to the owner's setting or January. Callbacks are synchronous and may return a number, Money or undefined; valueType:"text" permits a string or undefined.

(options: MetricOptions): MetricDeclaration

const reportDate = deccf.input.date('2028-01');

const finalValue = deccf.metric({
  schedule:deccf.schedule.once(reportDate),
  calculate:ctx=>ctx.time.index+1,
});

return deccf.defineModel({
  currency:deccf.currencies.USD,
  timeline:deccf.periods.annual({from:'2026-01', count:3}),
  preconditions:{reportDate}, metrics:{finalValue},
});

deccf.ModelErrorCreates a model error with a stable code and a human-readable message. Optional details default to an empty object. path and period identify a known location; cause retains the underlying failure. During a calculation, inputReference can identify a declared input without knowing its name in the containing model. For an object-array field, also supply its unique inputRowId and an inputFieldPath array of declared field names (default: the input itself). The calculation resolves a verified source to the full input path. Unknown references, duplicate row IDs and undeclared fields cannot identify an input. Source resolution applies to input-validation codes such as DECCF_INPUT_DOMAIN; ordinary calculation error codes keep their calculation location. The error itself does not change a value; Calculator Apps can use a valid model default or omit an affected card and explain that choice in Results.

typeof ModelError

const duration = deccf.input.integer(120);

const active = deccf.input.boolean(true);

const model = deccf.defineModel({
  currency: deccf.currencies.SEK,
  timeline: deccf.periods.monthly({ from: "2026-01", count: 1 }),
  preconditions: { duration, active },
  metrics: {
    payment: (ctx) => {
      if (!ctx.get(active)) return 0;
      const months = ctx.get(duration);
      if (months <= 0) {
        throw new deccf.ModelError("DECCF_INPUT_DOMAIN", "Duration must be positive.", {
          inputReference: duration,
        });
      }
      return 120000 / months;
    },
  },
});

return model;

deccf.moneyCreates a typed Money value from a finite numeric amount and a Currency reference. Optional third argument {date: 'YYYY-MM-DD'} attaches an explicit valuation date; omission leaves the amount undated. The date must be a valid calendar date (an ISO year-month is also accepted). This date describes when the nominal money amount is valued, including future amounts inside a published record produced on an earlier model date. With run moneyValue:'today', it takes precedence over the output series point date or the final metric evaluation date. The returned Money retains its amount, currency and optional date; money() itself performs no inflation conversion. Plain numbers do not acquire monetary meaning. Currency conversion still requires convertMoney() with an explicit exchange rate.

(amount: number, denomination: Currency, options?: { readonly date?: DateString; }): Money

const futureAmount = deccf.money(10200, deccf.currencies.SEK, {date: "2027-01-01"});
// futureAmount retains its nominal amount and explicit valuation date.

deccf.optionDeclares a conditional payoff series that can be exercised when its condition changes from false to true.

(options: { readonly subject?: EntityReference; readonly direction?: CashflowDirection; readonly currency?: Currency; readonly schedule?: ScheduleReference; readonly maxExercises?: number; readonly when: (context: CalculationContext) => boolean; readonly payoff: (context: CalculationContext) => number | Money; }): OptionReference

const { currencies, defineModel, entity, field, inflow, option, periods, schedule } = deccf;

const propertyValue = field({ initial: 1_800_000, next: (previous) => previous * 1.03 });

const property = entity.asset({ fields: { propertyValue } });

const exit = option({
  subject: property,
  direction: inflow,
  currency: currencies.SEK,
  when: (ctx) => ctx.get(propertyValue) >= 2_000_000,
  payoff: (ctx) => ctx.get(propertyValue),
});

const model = defineModel({
  name: "property-exit-option",
  currency: currencies.SEK,
  timeline: periods.annual({ from: "2026-01", count: 12 }),
  entities: { property },
  options: { exit },
});

return model;

deccf.outflowMarks a cashflow as money leaving the model owner's cash position.

CashflowDirection

const { outflow } = deccf;

deccf.periodsCreates a timeline with a calendar, start date, and number of periods.

Readonly<Record<Calendar, (options: TimelineOptions) => Timeline>>

const { periods } = deccf;

deccf.periods.annualCreates an annual timeline from a start date and period count.

(options: TimelineOptions): Timeline

const model = deccf.defineModel({
  name: 'Monte Carlo starting settings',
  currency: deccf.currencies.USD,
  timeline: deccf.periods.annual({from:'2026-01', count:1}),
  calculator: {
    defaultRun: {mode:'monte-carlo', trials:128, sampling:'sobol'},
  },
});

return model;

deccf.periods.dailyCreates a daily timeline from a start date and period count.

(options: TimelineOptions): Timeline

const { daily } = deccf.periods;

deccf.periods.monthlyCreates a monthly timeline from a start date and period count.

(options: TimelineOptions): Timeline

const { monthly } = deccf.periods;

deccf.periods.quarterlyCreates a quarterly timeline from a start date and period count.

(options: TimelineOptions): Timeline

const { quarterly } = deccf.periods;

deccf.periods.weeklyCreates a weekly timeline from a start date and period count.

(options: TimelineOptions): Timeline

const { weekly } = deccf.periods;

deccf.phaseDeclares a named phase used to group model periods and scheduled behavior.

(options: { readonly from: DateString; readonly to: DateString; }): PhaseReference

const { cashflow, currencies, defineModel, entity, inflow, periods, phase, schedule } = deccf;

const building = entity.asset();

const construction = phase({ from: "2026-01", to: "2026-06" });

const operations = phase({ from: "2026-07", to: "2027-12" });

const rent = cashflow({ owner: building, direction: inflow, schedule: schedule.monthly(), amount: 1_000 });

const model = defineModel({
  name: "phased-building",
  currency: currencies.SEK,
  timeline: periods.monthly({ from: "2026-01", count: 24 }),
  entities: { building },
  flows: { rent },
  phases: { construction, operations },
});

return model;

deccf.preparePrepares a model's fixed structure, input overrides, calendar, bindings and validation once. Returns an immutable object with run({parameters?,seed?,trial?}) and withParameters(parameters). Scoped parameter handles validate and snapshot supplied values once; source mutations cannot change them. Missing required names are deferred until run. Each run replaces only supplied names, validates those replacements and leaves the scoped snapshot unchanged. The run method rejects structural overrides: prepare again to change ordinary inputs, schedules, timeline, currency or output selection. Without outputs each run returns the complete result. With outputs:{name:reference}, each run returns only a frozen named record of final account/calculation/projection values, without report construction. Account values are numbers; structured calculation values and Money retain their native types and nominal amounts. Missing/undeclared/unsupported outputs and invalid runtime parameters are errors. Selected outputs still execute the native timeline and balanced postings; dynamic readers retain the bookkeeping they need. Prepares fixed model structure, structural input overrides, calendar and read bindings for reuse. options accepts ordinary run settings plus optional outputs:{name:accountOrCalculationOrProjection}. Returns an immutable object with run({parameters?,seed?,trial?}) and withParameters(parameters); other per-run keys are rejected. withParameters validates and snapshots supplied names once and returns a new immutable handle; chaining inherits prior names, and later source-object mutations cannot change the snapshot. Each run validates only supplied overrides, replacing each complete named value without merging nested records or changing the scoped defaults. Unknown names and invalid values fail immediately; missing required parameters may remain unset until run. Currency is fixed by preparation; seed/trial can change per run, while balances, history and once values remain independent. Without outputs it returns a complete result; with outputs it returns a frozen record of final native values, with numeric account balances and unchanged typed Money, without report valuation or series wrappers. Unknown output references and invalid parameters fail. Each execution starts fresh, including balances, history and bind.once values. Changing timeline, schedules, accounts or structural inputs requires preparing again. Selected outputs retain the native simulation and validation; unused report bookkeeping is omitted only where no reader needs it. Optional amountStorage accepts 'period' (default), 'calendar-year' or 'fiscal-year'; other values are rejected. Annual storage compacts published monetary series, compatibility cashflow series, account postings and report groups. Flows and postings sum after output valuation; account balances keep their last observation; Money-valued metrics and numeric metrics with unit:'money' use annualAggregation ('last' by default). Fiscal grouping follows each owner's attributes.fiscalYearStartMonth (integer 1–12); ownerless values use January, and a metric's explicit fiscal start takes precedence. Source periods belong to their start-date year and are never split or prorated. Each compacted series index publishes actual covered dates, inclusive periodEnds, periodLabels and sourceCalendar, including partial years. Account postings retain account, flow, side, owner, category and flow_role, with periodEnd and periodLabel; period remains the original first calculation-period index. Report groups have an equivalent annual index. The calculation timeline, result.dates, live reference accessors, nonmonetary series and authored structured calculation records retain their original detail. Final metrics and Monte Carlo summaries are unchanged; only the ordinary baseline's published money observations are compacted. Shared scenario options apply to every scenario, and prepare() fixes the option at preparation. Result metadata amountStorage appears only in annual modes. Native reports use annual views; differing fiscal calendars require an owner selection, and calendar-year-only views cannot split fiscal totals. See Store monetary results by year for a monthly model example and output limits.

<TOutputs extends PreparedOutputs>(model: ModelDefinition<ModelCurrency> | CompilationPlan, options: RunOptions & { readonly outputs: TOutputs; }): PreparedModel<PreparedOutputValues<TOutputs>>
(model: ModelDefinition<ModelCurrency> | CompilationPlan, options?: RunOptions): PreparedModel

const assumptions = deccf.bind.parameter('assumptions', {
  valueType:{annual:'number'}, defaultValue:{annual:1200},
});

const total = deccf.calculation({
  name:'total', bindings:{assumptions},
  calculate:({assumptions},{time})=>assumptions.annual*(time.index+1),
});

const model = deccf.defineModel({
  currency:deccf.currencies.SEK,
  timeline:deccf.periods.annual({from:'2026-01',count:3}),
  calculations:{total},
});

const prepared = deccf.prepare(model,{outputs:{total}});

const source = {annual:2400};

const scoped = prepared.withParameters({assumptions:source});

source.annual = 9000;

const fixed = scoped.run();

const replaced = scoped.run({parameters:{assumptions:{annual:3000}}});

return model;

deccf.prioritypriority({order, requests?}) returns an allocation method. order is an array of unique nonempty recipient IDs. requests supplies nonnegative amounts by ID; omitted requests take the remaining amount in order, subject to limits. Creates no postings. Keyed values accept a keyed source map, an ordinary repeated column or a repeated calculation/flow output map; numeric leaves are finite numbers or Money in the model currency. Source repeat keys identify recipients, including inside enclosing repeats and after input reordering. Register source repeats as components. Nonnumeric leaves, wrong currencies and unknown recipient keys reject. Existing keyed maps and columns retain their meaning.

(options: PriorityOptions): AllocationMethodReference

const rows = deccf.input.objectArray([
  {id: deccf.input.id("a"), weight: deccf.input.decimal(1)},
  {id: deccf.input.id("b"), weight: deccf.input.decimal(3)},
]);
const weight = deccf.calculation({name: "Weight", calculate: deccf.expr.multiply(rows.item.data.weight, 1)});
const weights = deccf.repeat(rows, deccf.component({calculations: {weight}, outputs: {weight}}));
const split = deccf.allocation({amount: 100, method: deccf.proportional({weights: weights.outputs.weight})});
const reserved = deccf.allocation({amount: 100, method: deccf.proportional({
  weights: weights.outputs.weight, overrides: weights.outputs.weight,
})});
const first = deccf.allocation({amount: 10,
  method: deccf.priority({order: ["a", "b"], requests: weights.outputs.weight}),
  limits: weights.outputs.weight,
});
return deccf.defineModel({currency: deccf.currencies.SEK,
  timeline: deccf.periods.monthly({from: "2026-01", count: 1}),
  preconditions: {rows}, components: {weights, split, reserved, first},
});
 

deccf.proportionalproportional({weights, overrides?, zeroBasis?}) returns an allocation/funding method. weights defines recipients and relative nonnegative weights. overrides reserves fixed amounts by recipient before distributing the remainder (default none). zeroBasis defaults to 'error'; 'equal' splits a zero-weight remainder equally. Empty weights leave the amount unallocated. Keyed values accept a keyed source map, an ordinary repeated column or a repeated calculation/flow output map; numeric leaves are finite numbers or Money in the model currency. Source repeat keys identify recipients, including inside enclosing repeats and after input reordering. Register source repeats as components. Nonnumeric leaves, wrong currencies and unknown recipient keys reject. Existing keyed maps and columns retain their meaning.

(options: ProportionalOptions): AllocationMethodReference

const rows = deccf.input.objectArray([
  {id: deccf.input.id("a"), weight: deccf.input.decimal(1)},
  {id: deccf.input.id("b"), weight: deccf.input.decimal(3)},
]);
const weight = deccf.calculation({name: "Weight", calculate: deccf.expr.multiply(rows.item.data.weight, 1)});
const weights = deccf.repeat(rows, deccf.component({calculations: {weight}, outputs: {weight}}));
const split = deccf.allocation({amount: 100, method: deccf.proportional({weights: weights.outputs.weight})});
const reserved = deccf.allocation({amount: 100, method: deccf.proportional({
  weights: weights.outputs.weight, overrides: weights.outputs.weight,
})});
const first = deccf.allocation({amount: 10,
  method: deccf.priority({order: ["a", "b"], requests: weights.outputs.weight}),
  limits: weights.outputs.weight,
});
return deccf.defineModel({currency: deccf.currencies.SEK,
  timeline: deccf.periods.monthly({from: "2026-01", count: 1}),
  preconditions: {rows}, components: {weights, split, reserved, first},
});
 

deccf.repeatRepeats a component over the rows of an object-array input and exposes each row's outputs.

<TFields extends InputObjectFields, TOutputs extends Readonly<Record<string, ComponentOutputReference>>, TSourceOutputs extends Readonly<Record<string, ComponentOutputReference>>>(source: ObjectArrayInputReference<TFields> | InputProjectionReference<readonly InputValue[]> | RepeatedComponentReference<TFields, TSourceOutputs> | RepeatViewReference<TFields, TSourceOutputs>, template: ComponentReference<TOutputs>): RepeatedComponentReference<TFields, TOutputs>

const projected = deccf.calculation({
  name: "projected", resultType: "money", bindings: {row: changeable.item.value},
  calculate: ({row}) => deccf.money(
    row.amount.amount * (1 + row.annualReturn - (row.type === "isk" ? row.taxRate : row.fundFee)),
    row.amount.currency,
  ),
});

const accounts = deccf.repeat(changeable, deccf.component({
  calculations: {projected}, outputs: {projected},
}));

const total = deccf.calculation({
  name: "total", calculate: deccf.expr.sum(accounts.outputs.projected, {
    resultType: "money", currency: deccf.currencies.SEK,
  }),
});

return deccf.defineModel({
  currency: deccf.currencies.SEK,
  timeline: deccf.periods.annual({from: "2026-01", count: 1}),
  preconditions: {changeable}, components: {accounts}, calculations: {total},
});

deccf.runEvaluates a model or compiled plan and returns a complete deterministic result with series, metrics, accessors and timings. Optional moneyValue accepts 'nominal' (default) or 'today'; other values are rejected. 'today' converts declared monetary outputs to purchasing power at the first resolved timeline date using the model's effective annual inflation, amount / (1 + inflation) ** elapsedYears. Whole calendar anniversaries count as full years, with actual days used for a partial anniversary year. An explicit money() valuation date wins; otherwise series use their point dates and custom money metrics use their last evaluated window date. Typed Money leaves in structured calculations, cashflows, accounts, options and monetary summaries are converted. Plain numeric outputs, ages, rates and text retain their values. model.total sums converted cashflows; model.npv already represents base-date present value and remains unchanged. Inputs, state and economic callbacks keep their nominal values. Zero inflation gives identical amounts; negative inflation greater than -1 is supported. The result exposes moneyValue, inflation and moneyValueBaseDate, also in serialized output. Existing currency, discountRate, overrides, deterministic input settings, seed and trial options remain supported; see Run configuration for validation. Optional amountStorage accepts 'period' (default), 'calendar-year' or 'fiscal-year'; other values are rejected. Annual storage compacts published monetary series, compatibility cashflow series, account postings and report groups. Flows and postings sum after output valuation; account balances keep their last observation; Money-valued metrics and numeric metrics with unit:'money' use annualAggregation ('last' by default). Fiscal grouping follows each owner's attributes.fiscalYearStartMonth (integer 1–12); ownerless values use January, and a metric's explicit fiscal start takes precedence. Source periods belong to their start-date year and are never split or prorated. Each compacted series index publishes actual covered dates, inclusive periodEnds, periodLabels and sourceCalendar, including partial years. Account postings retain account, flow, side, owner, category and flow_role, with periodEnd and periodLabel; period remains the original first calculation-period index. Report groups have an equivalent annual index. The calculation timeline, result.dates, live reference accessors, nonmonetary series and authored structured calculation records retain their original detail. Final metrics and Monte Carlo summaries are unchanged; only the ordinary baseline's published money observations are compacted. Shared scenario options apply to every scenario, and prepare() fixes the option at preparation. Result metadata amountStorage appears only in annual modes. Native reports use annual views; differing fiscal calendars require an owner selection, and calendar-year-only views cannot split fiscal totals. See Store monetary results by year for a monthly model example and output limits.

(model: ModelDefinition<ModelCurrency> | CompilationPlan, options?: RunOptions): CashflowResult

const inflation = deccf.input.rate(0.02);
const model = deccf.defineModel({
  currency: deccf.currencies.SEK,
  timeline: deccf.periods.annual({from: "2026-01", count: 2}),
  preconditions: {inflation},
  inflation,
  metrics: {futureAmount: () => deccf.money(10200, deccf.currencies.SEK, {date: "2027-01-01"})},
});
const result = deccf.run(model, {moneyValue: "today", amountStorage: "calendar-year"});
// result.deterministic.metrics["metric.futureAmount"].amount is 10000.
// Annual series retain their own index.dates and index.periodEnds.
return model;

deccf.runMonteCarloOptional third argument controls defaults to {}: runMonteCarlo(model, options, {onProgress}). The call stays synchronous and returns the unchanged MonteCarloResult. onProgress receives immutable completed-work snapshots: phase ('preparing', 'baseline', 'trials', 'finalizing' or 'complete'), completedTrials, totalTrials, completedWork, totalWork and baselineComplete. For N trials, totalTrials is N and totalWork is trials + 2: one baseline, N trials and one final summary. completedWork counts only finished units; baselineComplete becomes true after the ordinary base calculation. Counts measure completed work, not estimated elapsed time; baseline order follows the selected execution strategy. Events may be coalesced. Observer errors do not affect results and return values are not awaited; keep callbacks brief. Failed calculations never emit complete. Omission disables observations. Controls stay separate from calculation options, result data, receipts and cache identities. Synchronous observations alone cannot make a progress indicator paint during the call. The Calculator owns automatic progress display; financial model code needs no UI logic or custom simulation loop. See Calculation progress for timing and opt-in Web API framing. Runs synchronously, optionally reporting completed work through onProgress in a separate third control argument. Events may be coalesced; baseline timing follows the selected execution strategy. An observer does not make a window paint during synchronous execution. Failed calculations never emit complete. Runs repeated sampled calculations and returns the complete ordinary base result plus sampled metric summaries, percentiles, histograms and timings. Requires trials, a positive integer, and an explicit integer seed. Optional sampling is pseudo-random (default) or sobol; Sobol trials must be a power of two, at most 2^32. Supports the same moneyValue:'nominal'|'today' option as run(), defaulting to 'nominal'. For 'today', each trial converts its monetary results before computing statistics using the effective overridden model inflation; a distribution inflation input uses its central value; the base result uses central input values. Rates and other plain numeric metrics retain their units. Base-date NPV is unchanged. Metadata moneyValue, inflation and moneyValueBaseDate describes the base calculation. See Simulate uncertainty for other sampling options and limits. Optional amountStorage accepts 'period' (default), 'calendar-year' or 'fiscal-year'; other values are rejected. Annual storage compacts published monetary series, compatibility cashflow series, account postings and report groups. Flows and postings sum after output valuation; account balances keep their last observation; Money-valued metrics and numeric metrics with unit:'money' use annualAggregation ('last' by default). Fiscal grouping follows each owner's attributes.fiscalYearStartMonth (integer 1–12); ownerless values use January, and a metric's explicit fiscal start takes precedence. Source periods belong to their start-date year and are never split or prorated. Each compacted series index publishes actual covered dates, inclusive periodEnds, periodLabels and sourceCalendar, including partial years. Account postings retain account, flow, side, owner, category and flow_role, with periodEnd and periodLabel; period remains the original first calculation-period index. Report groups have an equivalent annual index. The calculation timeline, result.dates, live reference accessors, nonmonetary series and authored structured calculation records retain their original detail. Final metrics and Monte Carlo summaries are unchanged; only the ordinary baseline's published money observations are compacted. Shared scenario options apply to every scenario, and prepare() fixes the option at preparation. Result metadata amountStorage appears only in annual modes. Native reports use annual views; differing fiscal calendars require an owner selection, and calendar-year-only views cannot split fiscal totals. See Store monetary results by year for a monthly model example and output limits. Optional model setting monteCarlo:{execution:'indexed',baselineMetrics:[...]} selects strict indexed Monte Carlo. Omission preserves general execution and its existing summaries. baselineMetrics defaults to []; entries must be unique names of declared metrics. Remaining sampled metrics need declarative metric({value,...}); every scheduled context is evaluated and the final summary retains the last defined emitted value. periodLength:1 and frequency:1 remain defaults; schedule.once(finalDate) selects only a final outcome. Supported sampled value sources are number, text or Money literals and input, calculation, calculation-projection or account references; direct flow, field and expression sources are rejected. All sampled ledger dependencies must support static indexed execution. A nonempty timeline without additional projection periods is required. Events, options, agreements, entity fields/lifecycles, derived inputs, triggered flows, expression bindings/amounts and account initializers using callbacks, expressions or calculations are unsupported. Unsupported callbacks, dynamic dependencies or unsupported graph features cause an error; there is no fallback. Baseline-only calculations can remain dynamic when outside sampled dependencies. Each named baseline metric is evaluated during the complete ordinary unseeded base calculation; its numeric final value is repeated across trials, so standard deviation is zero and all percentiles equal that base value. This is an author-selected fixed baseline statistic, not a sampled uncertainty estimate. Indexed mode summarizes declared numeric metrics only; implicit total, npv, irr and wal sampled summaries are omitted while the complete baseline retains ordinary results. Monthly periods, declared financial operations, global seeded draws, Sobol coordinates and monetary output valuation remain in effect. Active approximate mode (approximate:true with more than 1000 trials) is rejected; at most 1000 trials retain exact execution and inactive approximation metadata. Optional monteCarlo.series selects unique existing account.<name>.balance, flow.<name> or metric.<name> series in general or indexed execution. seriesSummaries[id] contains exact model dates and points of SampledSeriesPointSummary (trials, mean, standardDeviation, min, max and empirical percentiles) or null for missing observations; temporal points omit histograms while existing scalar MetricSummary retains distribution. Series metadata includes optional currency/unit and valuation metadata. Matching baseline arrays preserve the ordinary unseeded curve before annual amount storage. annual:{dates,points,baseline} aggregates each trial before statistics: flows sum, accounts use last balance, metrics follow annualAggregation and fiscalYearStartMonth. Money valuation precedes grouping; amountStorage never discards sampled original dates. Omitted series preserves the existing result shape and avoids temporal summary work. Baseline metric selection is also available in general execution. See Simulate uncertainty and Valuation and uncertainty for a complete callable example, supported values and validation. Optional monteCarlo.samplingLayout accepts only static-first when supplied; omission preserves the original Sobol layout. It preserves model-wide ctx.draw coordinates, promotes every declared bind.sample model-wide period slot before other ctx.sample owner/period slots, and removes promoted slots from the remaining namespace to avoid aliasing. Annual bindings promote the first represented period of each calendar year, including partial years; period bindings promote every period. Inputs sort by declared name and periods chronologically; duplicate consumers share their existing logical sample. Slots are reserved for unused bindings, branches and overridden inputs before execution, so call order and worker partitioning cannot change streams. The opt-in changes Sobol sample streams but leaves pseudorandom streams unchanged; it works in general and indexed execution. The 21,201 actual-coordinate limit still applies and out-of-range dynamic samples fail explicitly. samplingDimensions retains the full potential namespace size, including unused owner/period slots; static-first reorders it rather than limiting supported sampling identities. Structural model changes may change stream assignments.

(model: ModelDefinition<ModelCurrency> | CompilationPlan, options: MonteCarloOptions, controls?: MonteCarloControls): MonteCarloResult

const inflation = deccf.input.rate(0.02);
const model = deccf.defineModel({
  currency: deccf.currencies.SEK,
  timeline: deccf.periods.annual({from: "2026-01", count: 2}),
  preconditions: {inflation},
  inflation,
  metrics: {futureAmount: () => deccf.money(10200, deccf.currencies.SEK, {date: "2027-01-01"})},
});
// Optional API observation example; the Calculator shows progress automatically.
const observations = [];
const result = deccf.runMonteCarlo(model, {trials: 128, seed: 7, moneyValue: "today", amountStorage: "fiscal-year"}, {onProgress: progress => observations.push(progress)});
// Each immutable observation has completedWork/totalWork and completedTrials/totalTrials.
// On success the final phase is "complete" and completedWork is 130 (128 + 2).
// The baseline uses annual storage; sampled metric summaries retain their values.
return model;

deccf.runScenariosRuns named scenarios with shared run options and returns {name, result} entries with per-scenario timings and a timings property on the array. Each scenario has a name and optional overrides Map keyed by declared InputReference values; scalar and curve overrides follow normal input validation. Optional moneyValue:'nominal'|'today' defaults to 'nominal'. Every scenario independently resolves its inflation input and converts its monetary outputs and summaries at its own first resolved timeline date. Pass trials with Monte Carlo settings to simulate every scenario; monetary statistics are computed from converted trial values. Inputs and callbacks retain nominal values, plain numeric outputs retain their units, and base-date NPV is unchanged. Optional amountStorage accepts 'period' (default), 'calendar-year' or 'fiscal-year'; other values are rejected. Annual storage compacts published monetary series, compatibility cashflow series, account postings and report groups. Flows and postings sum after output valuation; account balances keep their last observation; Money-valued metrics and numeric metrics with unit:'money' use annualAggregation ('last' by default). Fiscal grouping follows each owner's attributes.fiscalYearStartMonth (integer 1–12); ownerless values use January, and a metric's explicit fiscal start takes precedence. Source periods belong to their start-date year and are never split or prorated. Each compacted series index publishes actual covered dates, inclusive periodEnds, periodLabels and sourceCalendar, including partial years. Account postings retain account, flow, side, owner, category and flow_role, with periodEnd and periodLabel; period remains the original first calculation-period index. Report groups have an equivalent annual index. The calculation timeline, result.dates, live reference accessors, nonmonetary series and authored structured calculation records retain their original detail. Final metrics and Monte Carlo summaries are unchanged; only the ordinary baseline's published money observations are compacted. Shared scenario options apply to every scenario, and prepare() fixes the option at preparation. Result metadata amountStorage appears only in annual modes. Native reports use annual views; differing fiscal calendars require an owner selection, and calendar-year-only views cannot split fiscal totals. See Store monetary results by year for a monthly model example and output limits. Optional model setting monteCarlo:{execution:'indexed',baselineMetrics:[...]} selects strict indexed Monte Carlo. Omission preserves general execution and its existing summaries. baselineMetrics defaults to []; entries must be unique names of declared metrics. Remaining sampled metrics need declarative metric({value,...}); every scheduled context is evaluated and the final summary retains the last defined emitted value. periodLength:1 and frequency:1 remain defaults; schedule.once(finalDate) selects only a final outcome. Supported sampled value sources are number, text or Money literals and input, calculation, calculation-projection or account references; direct flow, field and expression sources are rejected. All sampled ledger dependencies must support static indexed execution. A nonempty timeline without additional projection periods is required. Events, options, agreements, entity fields/lifecycles, derived inputs, triggered flows, expression bindings/amounts and account initializers using callbacks, expressions or calculations are unsupported. Unsupported callbacks, dynamic dependencies or unsupported graph features cause an error; there is no fallback. Baseline-only calculations can remain dynamic when outside sampled dependencies. Each named baseline metric is evaluated during the complete ordinary unseeded base calculation; its numeric final value is repeated across trials, so standard deviation is zero and all percentiles equal that base value. This is an author-selected fixed baseline statistic, not a sampled uncertainty estimate. Indexed mode summarizes declared numeric metrics only; implicit total, npv, irr and wal sampled summaries are omitted while the complete baseline retains ordinary results. Monthly periods, declared financial operations, global seeded draws, Sobol coordinates and monetary output valuation remain in effect. Active approximate mode (approximate:true with more than 1000 trials) is rejected; at most 1000 trials retain exact execution and inactive approximation metadata. Optional monteCarlo.series selects unique existing account.<name>.balance, flow.<name> or metric.<name> series in general or indexed execution. seriesSummaries[id] contains exact model dates and points of SampledSeriesPointSummary (trials, mean, standardDeviation, min, max and empirical percentiles) or null for missing observations; temporal points omit histograms while existing scalar MetricSummary retains distribution. Series metadata includes optional currency/unit and valuation metadata. Matching baseline arrays preserve the ordinary unseeded curve before annual amount storage. annual:{dates,points,baseline} aggregates each trial before statistics: flows sum, accounts use last balance, metrics follow annualAggregation and fiscalYearStartMonth. Money valuation precedes grouping; amountStorage never discards sampled original dates. Omitted series preserves the existing result shape and avoids temporal summary work. Baseline metric selection is also available in general execution. See Simulate uncertainty and Valuation and uncertainty for a complete callable example, supported values and validation. Optional monteCarlo.samplingLayout accepts only static-first when supplied; omission preserves the original Sobol layout. It preserves model-wide ctx.draw coordinates, promotes every declared bind.sample model-wide period slot before other ctx.sample owner/period slots, and removes promoted slots from the remaining namespace to avoid aliasing. Annual bindings promote the first represented period of each calendar year, including partial years; period bindings promote every period. Inputs sort by declared name and periods chronologically; duplicate consumers share their existing logical sample. Slots are reserved for unused bindings, branches and overridden inputs before execution, so call order and worker partitioning cannot change streams. The opt-in changes Sobol sample streams but leaves pseudorandom streams unchanged; it works in general and indexed execution. The 21,201 actual-coordinate limit still applies and out-of-range dynamic samples fail explicitly. samplingDimensions retains the full potential namespace size, including unused owner/period slots; static-first reorders it rather than limiting supported sampling identities. Structural model changes may change stream assignments.

(model: ModelDefinition<ModelCurrency>, scenarios: readonly { readonly name: string; readonly overrides?: ReadonlyMap<InputReference, InlineRunInput>; }[], options: MonteCarloOptions): ScenarioResultList<MonteCarloResult>
(model: ModelDefinition<ModelCurrency>, scenarios: readonly { readonly name: string; readonly overrides?: ReadonlyMap<InputReference, InlineRunInput>; }[], options?: RunOptions): ScenarioResultList<CashflowResult>

const inflation = deccf.input.rate(0.02);
const model = deccf.defineModel({
  currency: deccf.currencies.SEK,
  timeline: deccf.periods.annual({from: "2026-01", count: 2}),
  preconditions: {inflation},
  inflation,
  metrics: {futureAmount: () => deccf.money(10200, deccf.currencies.SEK, {date: "2027-01-01"})},
});
const results = deccf.runScenarios(model, [
  {name: "Base"},
  {name: "Higher inflation", overrides: new Map([[inflation, 0.04]])},
], {moneyValue: "today", amountStorage: "calendar-year"});
return model;

deccf.scaleMoneyMultiplies a Money value by a finite numeric factor and returns Money in the same currency. Retains the optional valuation date. The factor is unitless; scaling performs no inflation conversion.

(value: Money, factor: number): Money

const amount = deccf.money(100, deccf.currencies.SEK, {date: "2027-01-01"});
const doubled = deccf.scaleMoney(amount, 2);
// doubled.amount is 200; doubled.date is "2027-01-01".

deccf.scheduleCreates recurring or dated model schedules, such as monthly, annual, or one-time occurrences.

Readonly<ScheduleFactory>

const { schedule } = deccf;

deccf.schedule.annualCreates a recurring annual schedule between the requested dates.

(options?: RecurringScheduleOptions): ScheduleReference

const income = deccf.input.normal({mean:42000,stdev:3000});

const salary = deccf.cashflow({
  dynamic:true, direction:deccf.inflow, schedule:deccf.schedule.annual(),
  amount:ctx=>Math.max(0,ctx.sample(income)),
});

return deccf.defineModel({
  currency:deccf.currencies.SEK,
  timeline:deccf.periods.annual({from:'2026-01',count:3}),
  preconditions:{income}, flows:{salary},
});

deccf.schedule.dailyschedule.daily provides daily in the Core model API model editor. Use it when a model needs this operation.

(options?: RecurringScheduleOptions): ScheduleReference

const { daily } = deccf.schedule;

deccf.schedule.everyschedule.every provides every in the Core model API model editor. Use it when a model needs this operation.

(frequency: { readonly unit: "day" | "month"; readonly size: number; }, options?: RecurringScheduleOptions): ScheduleReference

const { every } = deccf.schedule;

deccf.schedule.monthlyCreates a recurring monthly schedule between the requested dates.

(options?: RecurringScheduleOptions): ScheduleReference

const { input } = deccf;

const forecast = businessForecast({
  owner: company,
  schedule: schedule.monthly(),
  template: "industry",
  sni: input.sni("47"), // Retail trade
});

deccf.schedule.onceCreates a one-time schedule for the requested date or period.

(date: DateString | InputReference<DateString>, options?: { readonly placement?: Placement; }): ScheduleReference

const reportDate = deccf.input.date('2028-01');

const finalValue = deccf.metric({
  schedule:deccf.schedule.once(reportDate),
  calculate:ctx=>ctx.time.index+1,
});

return deccf.defineModel({
  currency:deccf.currencies.USD,
  timeline:deccf.periods.annual({from:'2026-01', count:3}),
  preconditions:{reportDate}, metrics:{finalValue},
});

deccf.schedule.onceAfterNoOfDaysschedule.onceAfterNoOfDays provides once after no of days in the Core model API model editor. Use it when a model needs this operation.

(days: number): ScheduleReference

const { account, cashflow, category, currencies, defineModel, entity, periods, schedule, trigger } = deccf;

const anna = entity.party();

const cash = account({ owner: anna, type: "asset", category: category("assets.cash") });

const receivables = account({ owner: anna, type: "asset", category: category("assets.receivables") });

const rentIncome = account({ owner: anna, type: "income", category: category("income.rent") });

const latePay = trigger("latePay");

const billedRent = cashflow({
  dynamic:true,
  cashAccount: cash,
  schedule: schedule.monthly(),
  amount: 12_000,
  bookings: [
    { debit: cash, amount: (ctx) => ctx.amount / 2 },
    { debit: receivables, amount: (ctx) => ctx.amount / 2 },
    { credit: rentIncome, amount: (ctx) => ctx.amount },
  ],
  triggers: latePay,
});

const delayedSettlement = cashflow({
  dynamic:true,
  cashAccount: cash,
  schedule: schedule.onceAfterNoOfDays(30),
  triggeredBy: latePay,
  bookings: [
    { debit: cash, amount: (ctx) => ctx.source.amount / 2 },
    { credit: receivables, amount: (ctx) => ctx.source.amount / 2 },
  ],
});

const model = defineModel({
  name: "late-rent-settlement",
  currency: currencies.SEK,
  timeline: periods.monthly({ from: "2026-01", count: 12 }),
  entities: { anna },
  accounts: { cash, receivables, rentIncome },
  flows: { billedRent, delayedSettlement },
});

return model;

deccf.schedule.phaseEndschedule.phaseEnd provides phase end in the Core model API model editor. Use it when a model needs this operation.

(phase: PhaseReference): ScheduleReference

const { phaseEnd } = deccf.schedule;

deccf.schedule.phaseEnterschedule.phaseEnter provides phase enter in the Core model API model editor. Use it when a model needs this operation.

(phase: PhaseReference): ScheduleReference

const { phaseEnter } = deccf.schedule;

deccf.schedule.phaseStartschedule.phaseStart provides phase start in the Core model API model editor. Use it when a model needs this operation.

(phase: PhaseReference): ScheduleReference

const { phaseStart } = deccf.schedule;

deccf.schedule.quarterlyschedule.quarterly provides quarterly in the Core model API model editor. Use it when a model needs this operation.

(options?: RecurringScheduleOptions): ScheduleReference

const { cashflow, currencies, defineModel, entity, inflow, periods, schedule } = deccf;

const building = entity.asset();

const once = cashflow({ owner: building, direction: inflow, schedule: schedule.once("2026-01-15"), amount: 100 });

const monthly = cashflow({ owner: building, direction: inflow, schedule: schedule.monthly({ from: "2026-01", to: "2027-12" }), amount: 200 });

const everyOtherQuarter = cashflow({ owner: building, direction: inflow, schedule: schedule.quarterly({ interval: 2 }), amount: 300 });

const yearEnd = cashflow({ owner: building, direction: inflow, schedule: schedule.yearEnd({ from: "2026-01", to: "2028-12" }), amount: 400 });

const midMonth = cashflow({ owner: building, direction: inflow, schedule: schedule.monthly({ dayOfMonth: 15 }), amount: 500 });

const monthEnd = cashflow({ owner: building, direction: inflow, schedule: schedule.monthly({ endOfMonth: true, except: ["2026-12-31"] }), amount: 600 });

const extraDate = cashflow({ owner: building, direction: inflow, schedule: schedule.monthly({ also: ["2026-04-05"] }), amount: 700 });

const model = defineModel({
  name: "schedule-examples",
  currency: currencies.SEK,
  timeline: periods.monthly({ from: "2026-01", count: 36 }),
  entities: { building },
  flows: { once, monthly, everyOtherQuarter, yearEnd, midMonth, monthEnd, extraDate },
});

return model;

deccf.schedule.weeklyschedule.weekly provides weekly in the Core model API model editor. Use it when a model needs this operation.

(options?: RecurringScheduleOptions): ScheduleReference

const { weekly } = deccf.schedule;

deccf.schedule.yearEndRun once in the final period of each calendar year.

(options?: Pick<RecurringScheduleOptions, "from" | "to" | "placement" | "except" | "also">): ScheduleReference

const { cashflow, currencies, defineModel, entity, inflow, periods, schedule } = deccf;

const building = entity.asset();

const once = cashflow({ owner: building, direction: inflow, schedule: schedule.once("2026-01-15"), amount: 100 });

const monthly = cashflow({ owner: building, direction: inflow, schedule: schedule.monthly({ from: "2026-01", to: "2027-12" }), amount: 200 });

const everyOtherQuarter = cashflow({ owner: building, direction: inflow, schedule: schedule.quarterly({ interval: 2 }), amount: 300 });

const yearEnd = cashflow({ owner: building, direction: inflow, schedule: schedule.yearEnd({ from: "2026-01", to: "2028-12" }), amount: 400 });

const midMonth = cashflow({ owner: building, direction: inflow, schedule: schedule.monthly({ dayOfMonth: 15 }), amount: 500 });

const monthEnd = cashflow({ owner: building, direction: inflow, schedule: schedule.monthly({ endOfMonth: true, except: ["2026-12-31"] }), amount: 600 });

const extraDate = cashflow({ owner: building, direction: inflow, schedule: schedule.monthly({ also: ["2026-04-05"] }), amount: 700 });

const model = defineModel({
  name: "schedule-examples",
  currency: currencies.SEK,
  timeline: periods.monthly({ from: "2026-01", count: 36 }),
  entities: { building },
  flows: { once, monthly, everyOtherQuarter, yearEnd, midMonth, monthEnd, extraDate },
});

return model;

deccf.sniMainGroupsLists the Swedish SNI 2025 two-digit industry groups available to SNI input fields.

readonly SniMainGroup[]

const { sniMainGroups } = deccf;

deccf.stateCreates a named lifecycle state that can be used in transitions and actions.

(label: string): StateReference

const { currencies, defineModel, entity, lifecycle, periods, state } = deccf;

const active = state("active");

const closed = state("closed");

const life = lifecycle({
  states: [active, closed],
  initial: active,
  transitions: [{ from: active, to: closed, when: (ctx) => ctx.time.index === 11 }],
});

const asset = entity.asset({ lifecycle: life });

const model = defineModel({
  name: "asset-lifecycle",
  currency: currencies.SEK,
  timeline: periods.monthly({ from: "2026-01", count: 12 }),
  entities: { asset },
});

return model;

deccf.statementCreates a flow group that brings declared accounts to target statement balances.

(options: StatementOptions): FlowGroupReference

const { account, category, currencies, defineModel, entity, periods, schedule, statement } = deccf;

const company = entity.asset();

const revenue = account({ owner: company, type: "income", category: category("company.income.sales") });

const operatingCosts = account({ owner: company, type: "expense", category: category("company.expense.operating") });

const importClearing = account({ owner: company, type: "asset", category: category("company.assets.import_clearing") });

const historicalIncomeStatement = statement({
  name: "historical-2025-income-statement",
  owner: company,
  schedule: schedule.monthly({ from: "2025-01", to: "2025-12" }),
  balances: [
    { account: revenue, value: 1_200_000 },
    { account: operatingCosts, value: -780_000 },
  ],
  balancingAccount: importClearing,
});

const model = defineModel({
  name: "historical-income-statement-import",
  currency: currencies.SEK,
  timeline: periods.monthly({ from: "2025-01", count: 12 }),
  entities: { company },
  accounts: { revenue, operatingCosts, importClearing },
  flows: { historicalIncomeStatement },
});

return model;

deccf.subtractMoneySubtracts the second Money value from the first and returns a Money value. Amounts must be finite and both currencies must match. Retains a valuation date only when both operands have the same date; otherwise the result is undated. The subtraction performs no inflation conversion.

(left: Money, right: Money): Money

const first = deccf.money(100, deccf.currencies.SEK, {date: "2027-01-01"});
const second = deccf.money(20, deccf.currencies.SEK, {date: "2027-01-01"});
const remaining = deccf.subtractMoney(first, second);
// remaining.amount is 80; remaining.date is "2027-01-01".

deccf.symProvides built-in numeric domains for common positive and percentage inputs.

Readonly<{ pos: readonly [0, 100000000]; max100: readonly [0, 100]; max1: readonly [0, 1]; }>

const { sym } = deccf;

deccf.transferMoves an amount between accounts using a scheduled, balanced transfer.

(options: TransferOptions): ComponentReference<TransferOutputs>

const { transfer } = deccf;

deccf.triggerCreates a named event trigger that can notify subscribed flows in later periods.

(name?: string): TriggerReference

const { cashflow, currencies, defineModel, entity, inflow, periods, schedule, trigger } = deccf;

const { stdaccount } = modules.accountplan;

const { businessBaseForecast, forecastInvestment } = modules["business-base-forecast"];

const company = entity.asset({ label: "Northwind Tools" });

const sieLoaded = trigger("sie-loaded");

const importedHistory = cashflow({
  owner: company,
  direction: inflow,
  schedule: schedule.once("2026-01-31"),
  amount: 1,
  triggers: sieLoaded,
});

const equipment = stdaccount({ code: "1221", owner: company, initial: 100_000 });

const accumulatedDepreciation = stdaccount({ code: "1229", owner: company, initial: -20_000 });

const depreciationExpense = stdaccount({ code: "7830", owner: company });

const forecast = businessBaseForecast({
  name: "forecast",
  owner: company,
  schedule: schedule.monthly(),
  triggeredBy: sieLoaded,
  sections: {
    investments: forecastInvestment({ openingAssets: { remainingLifeYears: 5 } }),
  },
});

return defineModel({
  name: "Northwind forecast",
  currency: currencies.SEK,
  timeline: periods.monthly({ from: "2026-01", count: 12 }),
  entities: { company },
  accounts: { equipment, accumulatedDepreciation, depreciationExpense },
  flows: { importedHistory, forecast },
});

deccf.validateInputChecks a supplied value against an input reference and returns a readonly list of path-specific validation errors; valid values return []. Optional path sets the error path prefix. For variant objects/arrays, type selects the active schema before checking fields, rates, money currencies and nested constraints. Unknown or malformed discriminators and duplicate anyOf types are errors; these values are not replaced by the first variant. Ordinary homogeneous arrays and object validation retain their existing behavior.

<T extends InputValue>(reference: InputReference<T>, value: unknown, options?: { readonly path?: string; }): readonly InputValidationError[]

const isk = deccf.input.Object({
  type: deccf.input.hidden("isk"),
  amount: deccf.input.money(2500, deccf.currencies.SEK),
  annualReturn: deccf.input.rate(0.02),
  taxRate: deccf.input.rate(0.01),
}, {label: "ISK"});
const vp = deccf.input.Object({
  type: deccf.input.hidden("vp"),
  amount: deccf.input.money(2500, deccf.currencies.SEK),
  annualReturn: deccf.input.rate(0.02),
  fundFee: deccf.input.rate(0.005),
}, {label: "VP-konto"});
const savings = deccf.input.Object([isk, vp], {title: "Sparande"});
const errors = deccf.validateInput(savings, {type: "unknown"}, {path: "selectedSavings"});
// errors identifies the unknown type without substituting ISK.

deccf.AccountOptionsAccountOptions describes a model value used by the Core model API editor functions.

Model value shape: { owner?: EntityReference | RepeatOutputProjection<EntityReference> | LookupReference<EntityReference>; side?: "owed" | "due"; type?: "asset" | "liability" | "equity" | "income" | "expense" | "transfer"; category?: CategoryReference; initial?: number | Money | CalculationProjectionReference<unknown> | ExpressionReference | CalculationReference<unknown> | InputReference<number | Money> | LookupReference<number | Money | CalculationProjectionReference<unknown> | CalculationReference<unknown> | InputReference<number | Money>> | InputProjectionReference<number | Money> | ParameterBindingReference<number | Money> | OnceBindingReference<number | Money> | ((context: CalculationContext) => number | Money) }

deccf.AccountPostingResultOne signed ledger posting observation. With annual amountStorage, rows sum by account, flow, side, owner, currency and flow_role after output valuation; date and period identify the first covered source period. Optional periodEnd is the inclusive covered end date and periodLabel is the year label. Categories and transaction/period-close roles are preserved.

Model value shape: { date: DateString; periodEnd?: DateString; periodLabel?: string; period: number; flow: string; flow_role: "transaction" | "period-close"; account: string; account_type: "asset" | "liability" | "equity" | "income" | "expense" | "transfer"; owner: string; category: string; category_label?: string; side: "debit" | "credit"; amount: number; currency: string }

deccf.AccountReferenceAccountReference describes a model value used by the Core model API editor functions.

Model value shape: Reference<"account">

deccf.ActionAction describes a model value used by the Core model API editor functions.

Model value shape: Readonly<Record<string, unknown>>

deccf.AgreementReferenceAgreementReference describes a model value used by the Core model API editor functions.

Model value shape: Reference<"agreement">

deccf.AgreementTermReferenceAgreementTermReference describes a model value used by the Core model API editor functions.

Model value shape: Reference<"term"> & { readonly __valueType?: T }

deccf.AllocationKeyedValuesAllocationKeyedValues describes a model value used by the Core model API editor functions.

Model value shape: Readonly<Record<string, AllocationValue>> | Reference<"repeat-column"> | Reference<"input-collection-column"> | Reference<"repeat-output-projection">

deccf.AllocationMethodReferenceAllocationMethodReference describes a model value used by the Core model API editor functions.

Model value shape: Reference<"allocation-method">

deccf.AllocationOptionsAllocationOptions describes a model value used by the Core model API editor functions.

Model value shape: { name?: string; amount: AllocationValue; method: AllocationMethodReference; limits?: AllocationKeyedValues; redistribute?: boolean; signed?: boolean; unit?: number; schedule?: ScheduleReference; phase?: "period" | "periodEnd" }

deccf.AllocationOutputsAllocationOutputs describes a model value used by the Core model API editor functions.

Model value shape: { readonly shares: CalculationProjectionReference; readonly requested: CalculationProjectionReference; readonly allocated: CalculationProjectionReference; readonly unallocated: CalculationProjectionReference; readonly explanation: CalculationProjectionReference; readonly unmetRequest: CalculationProjectionReference; }

deccf.AllocationValueAllocationValue describes a model value used by the Core model API editor functions.

Model value shape: number | Money | InputReference<number | Money> | InputProjectionReference<number | Money> | ExpressionReference | CalculationReference | CalculationProjectionReference | CashflowReference | RepeatOutputProjection<CalculationReference | CalculationProjectionReference | CashflowReference>

deccf.AmountStorageOptional amountStorage accepts 'period' (default), 'calendar-year' or 'fiscal-year'; other values are rejected. Annual storage compacts published monetary series, compatibility cashflow series, account postings and report groups. Flows and postings sum after output valuation; account balances keep their last observation; Money-valued metrics and numeric metrics with unit:'money' use annualAggregation ('last' by default). Fiscal grouping follows each owner's attributes.fiscalYearStartMonth (integer 1–12); ownerless values use January, and a metric's explicit fiscal start takes precedence. Source periods belong to their start-date year and are never split or prorated. Each compacted series index publishes actual covered dates, inclusive periodEnds, periodLabels and sourceCalendar, including partial years. Account postings retain account, flow, side, owner, category and flow_role, with periodEnd and periodLabel; period remains the original first calculation-period index. Report groups have an equivalent annual index. The calculation timeline, result.dates, live reference accessors, nonmonetary series and authored structured calculation records retain their original detail. Final metrics and Monte Carlo summaries are unchanged; only the ordinary baseline's published money observations are compacted. Shared scenario options apply to every scenario, and prepare() fixes the option at preparation. Result metadata amountStorage appears only in annual modes. Native reports use annual views; differing fiscal calendars require an owner selection, and calendar-year-only views cannot split fiscal totals. See Store monetary results by year for a monthly model example and output limits.

Model value shape: "period" | "calendar-year" | "fiscal-year"

deccf.AnalysisChangeAnalysisChange describes a model value used by the Core model API editor functions.

Model value shape: { input: InputReference<InputValue>; value: string | number | boolean | Money | InputReference<InputValue> | ExpressionReference }

deccf.AnalysisNumberA finite number or an input-only expression, resolved against the baseline inputs.

Model value shape: number | InputReference | ExpressionReference

deccf.BindingFactoryBindingFactory describes a model value used by the Core model API editor functions.

Model value shape: { sample: (reference: InputReference<number>, options?: { readonly calendar?: "annual" | "period"; }) => BindingReference<number, "sample">; previous: { <T = unknown>(reference?: CalculationReference<T> | CalculationProjectionReference<T>): PreviousBindingReference<T>; (reference: AccountReference): BindingReference<number, "previous">; }; history: <T = unknown>(reference?: CalculationReference<T>) => BindingReference<readonly T[], "history">; parameter: { (name: string, options: { readonly valueType: "number"; readonly defaultValue?: number; }): ParameterBindingReference<number>; (name: string, options: { readonly valueType: "boolean"; readonly defaultValue?: boolean; }): ParameterBindingReference<boolean>; (name: string, options: { readonly valueType: "text"; readonly defaultValue?: string; }): ParameterBindingReference<string>; (name: string, options: { readonly valueType: "money"; readonly defaultValue?: Money; }): ParameterBindingReference<Money>; <TType extends CalculationResultType>(name: string, options: { readonly valueType: TType; readonly defaultValue?: NoInfer<RuntimeParameterValue<TType>>; }): ParameterBindingReference<RuntimeParameterValue<TType>>; }; once: <T>(resolve: (context: OnceContext) => T & OnceData<T>) => OnceBindingReference<T> }

deccf.BindingReferenceBindingReference describes a model value used by the Core model API editor functions.

Model value shape: Reference<"binding"> & { readonly __valueType?: T; readonly __bindingType?: TKind }

deccf.BindingSourceBindingSource describes a model value used by the Core model API editor functions.

Model value shape: number | boolean | string | null | Money | BindingReference | InputReference<InputValue> | InputProjectionReference | CalculationReference | CalculationProjectionReference | AccountReference | CashflowReference | ExpressionReference | AgreementTermReference | LookupReference

deccf.BindingValueBindingValue describes a model value used by the Core model API editor functions.

Model value shape: T extends BindingReference<infer TValue> ? TValue : T extends InputReference<infer TValue> | InputProjectionReference<infer TValue> ? TValue : T extends CalculationReference<infer TValue> | CalculationProjectionReference<infer TValue> ? TValue : T extends AccountReference ? number : T extends CashflowReference ? Money : T extends number | boolean | string | null | Money ? T : unknown

deccf.BindingValuesBindingValues describes a model value used by the Core model API editor functions.

Model value shape: { readonly [K in keyof TBindings]: BindingValue<TBindings[K]> }

deccf.BookingAmountBookingAmount describes a model value used by the Core model API editor functions.

Model value shape: LookupReference<number | Money | InputReference | CalculationReference | CalculationProjectionReference | ExpressionReference> | DerivedReference | number | Money | InputReference | InputProjectionReference<number | Money> | ExpressionReference | ((context: CalculationContext) => number | Money)

deccf.BookingRowBookingRow describes a model value used by the Core model API editor functions.

Model value shape: Readonly<{ readonly debit: AccountReference | LookupReference<AccountReference>; readonly amount?: BookingAmount; }> | Readonly<{ readonly credit: AccountReference | LookupReference<AccountReference>; readonly amount?: BookingAmount; }>

deccf.BooleanInputOptionsBooleanInputOptions describes a model value used by the Core model API editor functions.

Model value shape: { newItem?: boolean; ui?: "switch" | "check" | Readonly<InputUIOptions & { readonly control?: "switch" | "check"; }>; required?: boolean; visible?: InputVisibility }

deccf.CalculationContextCalculationContext describes a model value used by the Core model API editor functions.

Model value shape: { currency: Currency; sourceCurrency: Currency; time: TimeContext; metricPeriod?: Readonly<{ readonly startIndex: number; readonly endIndex: number; readonly startDate: DateString; readonly endDate: DateString; readonly length: number; }>; owner?: EntityReference; amount?: number; source?: TriggerSource; accountsFor: (owner?: EntityReference) => readonly AccountReference[]; sourceFor: (flow: CashflowReference) => TriggerSource | null; get: { <T extends InputValue>(reference: InputReference<T>): T; (reference: FieldReference): number; (reference: AccountReference): number; (reference: CashflowReference): Money; <T = number>(reference: CalculationReference): T; (reference: CalculationProjectionReference): unknown; (reference: ExpressionReference): number | Money; <T extends InputValue>(reference: AgreementTermReference<T>): T; }; previous: { (reference: FieldReference): number; (reference: CashflowReference): number; (reference: AccountReference): number; (reference: CalculationReference): number; }; isInState: (entity: EntityReference, value: StateReference) => boolean; currentState: (entity: EntityReference) => StateReference | null; inPhase: (reference: PhaseReference) => boolean; enteredAt: (entity: EntityReference, value: StateReference) => number | null; term: <T extends InputValue>(agreement: AgreementReference, term: AgreementTermReference<T>) => T; … 11 more fields }

deccf.CalculationDefinitionOptionsCalculationDefinitionOptions describes a model value used by the Core model API editor functions.

Model value shape: { name: string; publish?: boolean; unit?: string; owner?: EntityReference | LookupReference<EntityReference>; dependsOn?: readonly (CashflowReference | CalculationProjectionReference<unknown> | CalculationReference<unknown>)[]; readsAccountsFrom?: readonly AccountReference[]; schedule?: ScheduleReference; phase?: "period" | "periodEnd"; resultType?: CalculationResultType; inactiveValue?: unknown; resolveAccounts?: (context: Readonly<{ readonly owner?: EntityReference; readonly accounts: readonly ModelAccountDefinition[]; }>) => readonly AccountReference[] }

deccf.CalculationFieldValueCalculationFieldValue describes a model value used by the Core model API editor functions.

Model value shape: TPath extends readonly [infer Head extends string, ...infer Tail extends string[]] ? Head extends keyof T ? Tail extends [] ? T[Head] : CalculationFieldValue<T[Head], Tail> : unknown : TPath extends string ? TPath extends `${infer Head}.${infer Tail}` ? Head extends keyof T ? CalculationFieldValue<T[Head], Tail> : unknown : TPath extends keyof T ? T[TPath] : unknown : unknown

deccf.CalculationOptionsCalculationOptions describes a model value used by the Core model API editor functions.

Model value shape: StaticCalculationOptions<TBindings, TResult> | DynamicCalculationOptions<TResult>

deccf.CalculationProjectionReferenceCalculationProjectionReference describes a model value used by the Core model API editor functions.

Model value shape: Reference<"calculation-projection"> & { readonly __valueType?: T }

deccf.CalculationReferenceCalculationReference describes a model value used by the Core model API editor functions.

Model value shape: { __valueType?: T; project: <TPath extends string | readonly string[]>(path: TPath) => CalculationProjectionReference<CalculationFieldValue<T, TPath>>; kind: "calculation"; token: symbol }

deccf.CalculationResultFieldsCalculationResultFields describes a model value used by the Core model API editor functions.

Model value shape: CalculationResultFields

deccf.CalculationResultTypeCalculationResultType describes a model value used by the Core model API editor functions.

Model value shape: "number" | "money" | "boolean" | "text" | CalculationResultFields | Readonly<{ kind: "money" }> | Readonly<{ kind: "record"; fields: CalculationResultFields }> | Readonly<{ kind: "map" | "optional"; valueType: CalculationResultType }> | Readonly<{ kind: "union"; types: readonly CalculationResultType[] }>

deccf.CalculatorOptionsOptional calculator pages (both default true) and initial run controls.

Model value shape: { runInput?: boolean; scenarios?: boolean; defaultRun?: Readonly<CalculatorRunDefaults> }

deccf.CalculatorRunDefaultsInitial Calculator run controls; saved or explicitly selected settings take precedence.

Model value shape: { mode?: "deterministic" | "monte-carlo"; trials?: number; seed?: number; sampling?: "pseudo-random" | "sobol" }

deccf.CalendarCalendar describes a model value used by the Core model API editor functions.

Model value shape: "daily" | "weekly" | "monthly" | "quarterly" | "annual"

deccf.CashflowContributionKindPresentation-editor contract; CashflowStatement is supplied by the presentation editor.

Model value shape: "result" | "depreciation" | "non-cash" | "working-capital" | "investing" | "financing" | "owner-transfer" | "unclassified"

deccf.CashflowDefinitionOptionsCashflowDefinitionOptions describes a model value used by the Core model API editor functions.

Model value shape: { name?: string; owner?: EntityReference | LookupReference<EntityReference>; agreement?: AgreementReference; direction?: CashflowDirection; category?: CategoryReference; currency?: Currency; schedule?: ScheduleReference; debit?: AccountReference | LookupReference<AccountReference>; credit?: AccountReference | LookupReference<AccountReference>; compileBookings?: CompileCashflowBookings; resolveAccounts?: ResolveCashflowAccounts; cashAccount?: AccountReference | LookupReference<AccountReference>; triggers?: TriggerReference | readonly TriggerReference[]; triggeredBy?: TriggerReference; dependsOn?: readonly (CashflowReference | CalculationProjectionReference<unknown> | CalculationReference<unknown>)[]; moves?: AccountReference | LookupReference<AccountReference>; … 4 more fields }

deccf.CashflowDirectionCashflowDirection describes a model value used by the Core model API editor functions.

Model value shape: { kind: "cashflow-direction"; name: "inflow" | "outflow"; sign: 1 | -1 }

deccf.CashflowOptionsCashflowOptions describes a model value used by the Core model API editor functions.

Model value shape: StaticCashflowOptions<TBindings> | DynamicCashflowOptions

deccf.CashflowReferenceCashflowReference describes a model value used by the Core model API editor functions.

Model value shape: Reference<"flow">

deccf.CashflowResultCashflowResult describes a model value used by the Core model API editor functions.

Model value shape: { moneyValue: MoneyValue; amountStorage?: AmountStorage; inflation: number; moneyValueBaseDate: DateString; results_version: "0.23"; engine: Readonly<{ readonly name: "deccf"; readonly version: string; }>; warnings: readonly string[]; inputs?: Readonly<{ readonly preconditions: readonly ResultsInputPrecondition[]; }>; deterministic: DeterministicResults; scenarios: Readonly<{ readonly status: "not_run"; readonly summaries: readonly never[]; }>; monte_carlo: Readonly<{ readonly status: "not_run"; readonly trials: 0; readonly seed: number; readonly metrics: Readonly<Record<string, never>>; readonly trial_summaries: readonly never[]; }>; graph?: Readonly<{ readonly entities: readonly ResultsGraphEntity[]; readonly accounts?: readonly ResultsGraphAccount[]; readonly agreements?: readonly ResultsGraphAgreement[]; }>; statements: Readonly<{ readonly statements: readonly never[]; }>; slices: readonly never[]; timings: ResultTimings; model: string; … 16 more fields }

deccf.CashflowSeriesCompatibility numeric cashflow or option series. Annual amountStorage compacts values and publishes an optional index with actual dates, inclusive periodEnds, periodLabels and sourceCalendar. Default period storage keeps the existing shape. Reference methods such as result.flow(ref) retain the calculation-period observations.

Model value shape: { index?: ResultSeriesIndex; type: "cashflow" | "option"; name: string; category: string; currency: string; values: readonly number[] }

deccf.CategoryHierarchyNodeCategoryHierarchyNode describes a model value used by the Core model API editor functions.

Model value shape: { path: string; label: string }

deccf.CategoryOptionsCategoryOptions describes a model value used by the Core model API editor functions.

Model value shape: { label?: string; hierarchy?: readonly CategoryHierarchyNode[] }

deccf.CategoryReferenceCategoryReference describes a model value used by the Core model API editor functions.

Model value shape: Reference<"category">

deccf.CompilationPlanCompilationPlan describes a model value used by the Core model API editor functions.

Model value shape: { kind: "compiled-model"; declarationBindings?: ReadonlyMap<object, object>; model: ModelDefinition<Currency>; template: ModelDefinition<ModelCurrency>; repeatedComponents: ReadonlyMap<RepeatedComponentReference<Readonly<Record<string, InputReference<InputValue>>>, Readonly<Record<string, ComponentOutputReference>>>, ReadonlyMap<string, Readonly<{ readonly component: ComponentReference; readonly outputs: Readonly<Record<string, ComponentOutputReference>>; }>>>; componentBindings: ReadonlyMap<ComponentReference<Readonly<Record<string, ComponentOutputReference>>>, ComponentReference<Readonly<Record<string, ComponentOutputReference>>>>; dates: readonly DateString[]; timelineCount: number; preconditions: readonly (readonly [string, InputReference<number>])[]; entities: readonly (readonly [string, EntityReference])[]; accounts: readonly (readonly [string, AccountReference])[]; reportGroups: readonly (readonly [string, Readonly<{ readonly id: string; readonly label?: string; readonly owner?: EntityReference; readonly accounts: readonly AccountReference[]; }>])[]; flows: readonly (readonly [string, CashflowReference])[]; phases: readonly (readonly [string, PhaseReference])[] }

deccf.CompileCashflowBookingsCompileCashflowBookings describes a model value used by the Core model API editor functions.

Model value shape: (context: { readonly owner?: EntityReference; readonly accounts: readonly ModelAccountDefinition[]; readonly currency: Currency; readonly getInput: (reference: InputReference<InputValue>) => unknown; /** Resolved model periods available to scheduled flows. */ readonly dates: readonly DateString[]; readonly calendar: Calendar; /** Period indexes where the inherited flow schedule occurs. */ readonly occurrencePeriods: readonly number[]; }) => ResolvedCashflowBookings

deccf.ComponentOptionsComponentOptions describes a model value used by the Core model API editor functions.

Model value shape: { owner?: EntityReference | LookupReference<EntityReference>; preconditions?: Readonly<Record<string, InputReference<InputValue> | Readonly<Record<string, unknown>>>>; entities?: Readonly<Record<string, EntityReference>>; accounts?: Readonly<Record<string, AccountReference>>; phases?: Readonly<Record<string, PhaseReference>>; flows?: Readonly<Record<string, CashflowReference | FlowGroupReference>>; agreements?: Readonly<Record<string, AgreementReference>>; events?: Readonly<Record<string, EventReference>>; options?: Readonly<Record<string, OptionReference>>; metrics?: Readonly<Record<string, MetricValue>>; components?: Readonly<Record<string, RepeatedComponentReference<Readonly<Record<string, InputReference<InputValue>>>, Readonly<Record<string, ComponentOutputReference>>> | ComponentReference<Readonly<Record<string, ComponentOutputReference>>> | RepeatViewReference<Readonly<Record<string, InputReference<InputValue>>>, Readonly<Record<string, ComponentOutputReference>>>>>; calculations?: Readonly<Record<string, CalculationReference<unknown>>>; outputs?: Readonly<Record<string, AccountReference | EntityReference | CashflowReference | CalculationProjectionReference<unknown> | CalculationReference<unknown>>>; reportGroups?: Readonly<Record<string, ReportGroupOptions>> }

deccf.ComponentOutputReferenceComponentOutputReference describes a model value used by the Core model API editor functions.

Model value shape: EntityReference | AccountReference | CashflowReference | FlowGroupReference | CalculationReference | CalculationProjectionReference

deccf.ComponentReferenceComponentReference describes a model value used by the Core model API editor functions.

Model value shape: { outputs: TOutputs; kind: "component"; token: symbol }

deccf.CurrencyCurrency describes a model value used by the Core model API editor functions.

Model value shape: { kind: "currency"; code: string }

deccf.CurveOptionsCurveOptions describes a model value used by the Core model API editor functions.

Model value shape: { interpolation?: "step" | "linear"; kind?: "money" | "currency" | "decimal" | "rate" | "fraction" | "integer"; domain?: NumericDomain; required?: boolean; visible?: InputVisibility; newItem?: number | Readonly<{ generate: "uuid"; }>; ui?: Readonly<InputUIOptions> }

deccf.DataCardsLayoutOptionsDataCardsLayoutOptions describes a model value used by the Core model API editor functions.

Model value shape: { columns?: number; date?: string; periodIndex?: number; year?: string | number; title?: string | false; visible?: boolean | "auto"; scenario?: string | number | readonly (string | number)[] }

deccf.DataCardsOptionsChoose source records or declared cards; the alternatives cannot be combined.

Model value shape: DataCardsLayoutOptions & ( | { readonly source: PresentationCalculationSource; readonly cards?: never; readonly percentile?: never } | { /** Non-empty named record with safe own-property keys, in display order. */ readonly cards: Readonly<Record<string, PresentationDeclaredDataCard>>; readonly source?: never; /** Integer 0..100, default 50. Metric leaves use deterministic values before Monte Carlo, * and only this exported percentile afterward; missing samples remain null. * Calculation selectors retain their ordinary deterministic snapshot selection. */ readonly percentile?: number; } )

deccf.DateStringDateString describes a model value used by the Core model API editor functions.

Model value shape: `${number}-${number}` | `${number}-${number}-${number}`

deccf.DerivedDependencyDerivedDependency describes a model value used by the Core model API editor functions.

Model value shape: InputReference | DerivedReference

deccf.DerivedKindDerivedKind describes a model value used by the Core model API editor functions.

Model value shape: "date" | "decimal" | "rate" | "fraction" | "integer" | "text"

deccf.DerivedOptionsDerivedOptions describes a model value used by the Core model API editor functions.

Model value shape: { inputs: Readonly<Record<string, DerivedDependency>>; calculate: (values: Readonly<Record<string, InputValue>>) => T; kind?: DerivedKind }

deccf.DerivedReferenceDerivedReference describes a model value used by the Core model API editor functions.

Model value shape: Reference<"derived">

deccf.DeterministicResultsDeterministicResults describes a model value used by the Core model API editor functions.

Model value shape: { status: "ok"; calculations?: Readonly<Record<string, PublishedCalculationSeries>>; metrics: Readonly<Record<string, ResultScalar>>; series: Readonly<Record<string, ResultSeries>>; annual_rollup: Readonly<{ readonly series: Readonly<Record<string, ResultSeries>>; }>; categories?: readonly ResultCategory[]; account_postings: readonly AccountPostingResult[]; transitions?: readonly Readonly<Record<string, unknown>>[]; journal?: readonly Readonly<Record<string, unknown>>[] }

deccf.DeterministicRunConfigDeterministicRunConfig describes a model value used by the Core model API editor functions.

Model value shape: { annual_discount_rate?: number; parameters?: Readonly<Record<`inputs.${string}`, InputValue>>; inputs?: Readonly<Record<string, InlineRunInput>> }

deccf.DistributionOptionsDistributionOptions describes a model value used by the Core model API editor functions.

Model value shape: { clip?: NumericDomain; kind?: "money" | "currency" | "decimal" | "rate" | "fraction" | "integer"; domain?: NumericDomain; required?: boolean; visible?: InputVisibility; newItem?: number | Readonly<{ generate: "uuid"; }>; ui?: Readonly<InputUIOptions> }

deccf.DomainInputReferenceDomainInputReference describes a model value used by the Core model API editor functions.

Model value shape: ObjectInputReference<TFields> & { readonly [domainInputType]: true }

deccf.DynamicCalculationOptionsDynamicCalculationOptions describes a model value used by the Core model API editor functions.

Model value shape: { dynamic: true; bindings?: never; calculate: ExpressionReference | ((context: CalculationContext) => TResult); name: string; publish?: boolean; unit?: string; owner?: EntityReference | LookupReference<EntityReference>; dependsOn?: readonly (CashflowReference | CalculationProjectionReference<unknown> | CalculationReference<unknown>)[]; readsAccountsFrom?: readonly AccountReference[]; schedule?: ScheduleReference; phase?: "period" | "periodEnd"; resultType?: CalculationResultType; inactiveValue?: unknown; resolveAccounts?: (context: Readonly<{ readonly owner?: EntityReference; readonly accounts: readonly ModelAccountDefinition[]; }>) => readonly AccountReference[] }

deccf.DynamicCashflowOptionsDynamicCashflowOptions describes a model value used by the Core model API editor functions.

Model value shape: { dynamic: true; bindings?: never; active?: (context: CalculationContext) => boolean; amount?: BookingAmount; bookings?: readonly BookingRow[]; name?: string; owner?: EntityReference | LookupReference<EntityReference>; agreement?: AgreementReference; direction?: CashflowDirection; category?: CategoryReference; currency?: Currency; schedule?: ScheduleReference; debit?: AccountReference | LookupReference<AccountReference>; credit?: AccountReference | LookupReference<AccountReference>; compileBookings?: CompileCashflowBookings; resolveAccounts?: ResolveCashflowAccounts; … 9 more fields }

deccf.EntityFactoryEntityFactory describes a model value used by the Core model API editor functions.

Model value shape: { asset: (options?: EntityOptions) => EntityReference; party: (options?: EntityOptions) => EntityReference; bundle: (options?: EntityOptions) => EntityReference; reference: (options?: EntityOptions) => EntityReference }

deccf.EntityOptionsEntityOptions describes a model value used by the Core model API editor functions.

Model value shape: { label?: string | InputProjectionReference<string>; owner?: EntityReference | LookupReference<EntityReference>; parent?: EntityReference; fields?: Readonly<Record<string, FieldReference>>; attributes?: Readonly<Record<string, string | number | boolean | InputProjectionReference<InputValue>>>; lifecycle?: LifecycleReference }

deccf.EntityReferenceEntityReference describes a model value used by the Core model API editor functions.

Model value shape: Reference<"entity">

deccf.EnumInputOptionsEnumInputOptions describes a model value used by the Core model API editor functions.

Model value shape: { options: readonly EnumOption<T>[]; domain?: NumericDomain; newItem?: T | Readonly<{ generate: "uuid"; }>; required?: boolean; visible?: InputVisibility; ui?: Readonly<InputUIOptions> }

deccf.EnumOptionEnumOption describes a model value used by the Core model API editor functions.

Model value shape: { value: T; label: string }

deccf.EventReferenceEventReference describes a model value used by the Core model API editor functions.

Model value shape: Reference<"event">

deccf.ExpressionFactoryExpressionFactory describes a model value used by the Core model API editor functions.

Model value shape: { amount: (value: ExpressionOperand) => ExpressionReference; money: (value: ExpressionOperand) => ExpressionReference; eq: (left: ExpressionOperand, right: ExpressionOperand) => ExpressionReference; when: (condition: boolean | InputReference<boolean> | InputProjectionReference | LookupReference | CalculationReference | CalculationProjectionReference | ExpressionReference, whenTrue: ExpressionOperand, whenFalse: ExpressionOperand) => ExpressionReference; add: (left: ExpressionOperand, right: ExpressionOperand) => ExpressionReference; subtract: (left: ExpressionOperand, right: ExpressionOperand) => ExpressionReference; multiply: (left: ExpressionOperand, right: ExpressionOperand) => ExpressionReference; divide: (left: ExpressionOperand, right: ExpressionOperand) => ExpressionReference; min: (left: ExpressionOperand, right: ExpressionOperand) => ExpressionReference; max: (left: ExpressionOperand, right: ExpressionOperand) => ExpressionReference; sum: (values: readonly ExpressionOperand[] | Readonly<Record<string, ExpressionOperand>> | RepeatOutputProjection<CalculationReference | CalculationProjectionReference | CashflowReference> | RepeatColumnReference, options?: { readonly resultType?: CalculationResultType; readonly currency?: Currency; }) => ExpressionReference; flow: (reference: CashflowReference) => ExpressionReference; balance: (reference: AccountReference | LookupReference<AccountReference> | readonly (AccountReference | LookupReference<AccountReference>)[] | Readonly<Record<string, AccountReference | LookupReference<AccountReference>>> | RepeatOutputProjection<AccountReference>, options?: { readonly after?: readonly CashflowReference[]; }) => ExpressionReference; netCash: (reference: EntityReference) => ExpressionReference }

deccf.ExpressionOperandExpressionOperand describes a model value used by the Core model API editor functions.

Model value shape: number | string | boolean | Money | InputReference<InputValue> | InputProjectionReference | LookupReference | RepeatOutputProjection<CalculationReference | CalculationProjectionReference | CashflowReference> | CashflowReference | CalculationReference | CalculationProjectionReference | ExpressionReference

deccf.ExpressionReferenceExpressionReference describes a model value used by the Core model API editor functions.

Model value shape: Reference<"expression">

deccf.FieldOptionsFieldOptions describes a model value used by the Core model API editor functions.

Model value shape: { initial: number | InputReference<number> | InputProjectionReference<number> | ((context: CalculationContext) => number); next?: (previous: number, context: CalculationContext) => number }

deccf.FieldReferenceFieldReference describes a model value used by the Core model API editor functions.

Model value shape: Reference<"field">

deccf.FlowGroupDefaultsFlowGroupDefaults describes a model value used by the Core model API editor functions.

Model value shape: Partial<Omit<CashflowOptions, "name" | "amount" | "debit" | "credit" | "bookings">>

deccf.FlowGroupItemFlowGroupItem describes a model value used by the Core model API editor functions.

Model value shape: CashflowReference | FlowGroupReference

deccf.FlowGroupOptionsFlowGroupOptions describes a model value used by the Core model API editor functions.

Model value shape: { name?: string; preconditions?: Readonly<Record<string, InputReference<InputValue> | Readonly<Record<string, unknown>>>>; flows: readonly FlowGroupItem[]; owner?: EntityReference | LookupReference<EntityReference>; currency?: Currency; dynamic?: boolean; bindings?: Readonly<Record<string, BindingSource>>; active?: ((context: CalculationContext) => boolean) | StaticCallback<Readonly<Record<string, BindingSource>>, boolean>; agreement?: AgreementReference; direction?: CashflowDirection; category?: CategoryReference; schedule?: ScheduleReference; compileBookings?: CompileCashflowBookings; resolveAccounts?: ResolveCashflowAccounts; cashAccount?: AccountReference | LookupReference<AccountReference>; triggers?: TriggerReference | readonly TriggerReference[]; … 7 more fields }

deccf.FlowGroupReferenceFlowGroupReference describes a model value used by the Core model API editor functions.

Model value shape: Reference<"flow-group">

deccf.FundingOptionsFundingOptions describes a model value used by the Core model API editor functions.

Model value shape: { from: Readonly<Record<string, AccountReference | EntityReference>> | RepeatOutputProjection<AccountReference | EntityReference>; to: AccountReference | EntityReference | RepeatOutputProjection<AccountReference | EntityReference> | LookupReference<AccountReference | EntityReference>; posting?: TransferPostingPolicy; retainOwnShare?: boolean; shortfall?: "error" | "report"; dependsOn?: readonly (CashflowReference | CalculationProjectionReference<unknown> | CalculationReference<unknown>)[]; amount: AllocationValue; unit?: number; name?: string; schedule?: ScheduleReference; method: AllocationMethodReference; limits?: AllocationKeyedValues; redistribute?: boolean; signed?: boolean }

deccf.FundingOutputsFundingOutputs describes a model value used by the Core model API editor functions.

Model value shape: AllocationOutputs & { readonly shortfall: CalculationProjectionReference; readonly transfers: CalculationReference; readonly retained: CalculationReference; }

deccf.GoalAnalysisOptionsGoalAnalysisOptions describes a model value used by the Core model API editor functions.

Model value shape: { compare?: (candidate: number, baseline: CalculationContext) => number | Money | undefined; input: InputReference<number>; from: AnalysisNumber; to: AnalysisNumber; atLeast?: AnalysisNumber; atMost?: AnalysisNumber; unit?: string; metric: string; changes?: readonly AnalysisChange[]; label?: string }

deccf.GroupsInputOptionsGroupsInputOptions describes a model value used by the Core model API editor functions.

Model value shape: { where?: Readonly<InputScalarFilter<TSource>>; label?: Extract<{ [K in keyof TSource]: TSource[K] extends InputReference<string> ? K : never; }[keyof TSource], string>; rows?: readonly (TFields & { readonly id: InputReference<string>; readonly name?: InputReference<string>; })[]; title?: string; type?: "table" | "cards"; required?: boolean; visible?: InputVisibility; ui?: Readonly<InputUIOptions> }

deccf.HistogramOptionsExported Monte Carlo distributions; actual observed bins only.

Model value shape: { metric?: string | PresentationMetricSelector; shape?: string; maxScenarios?: number; title?: string | false; visible?: boolean | "auto"; scenario?: string | number | readonly (string | number)[] }

deccf.IndirectCashflowGroupIndirectCashflowGroup describes a model value used by the Core model API editor functions.

Model value shape: { id: string; label?: string; kinds?: readonly CashflowContributionKind[]; accounts?: readonly (string | AccountReference)[]; categories?: readonly string[]; excludeAccounts?: readonly (string | AccountReference)[]; excludeCategories?: readonly string[]; details?: boolean }

deccf.IndirectCashflowStatementOptionsIndirectCashflowStatementOptions describes a model value used by the Core model API editor functions.

Model value shape: { method: "indirect"; title?: string | false; owner?: string | EntityReference | readonly (string | EntityReference)[]; asset?: string | EntityReference | readonly (string | EntityReference)[]; scenario?: string | number | readonly (string | number)[]; period?: "monthly" | "months" | "years" | "yearly"; year?: string | number; yearPage?: number; controls?: boolean; visible?: boolean | "auto"; totals?: boolean; cashAccounts?: readonly (string | AccountReference)[]; groups?: readonly IndirectCashflowGroup[]; rows?: readonly (string | IndirectCashflowSummary)[] }

deccf.IndirectCashflowSummaryIndirectCashflowSummary describes a model value used by the Core model API editor functions.

Model value shape: { id: string; label: string; add?: readonly string[]; subtract?: readonly string[]; cumulative?: true }

deccf.InlineRunInputInlineRunInput describes a model value used by the Core model API editor functions.

Model value shape: InputValue | InlineRunInputValue | InlineRunInputSeries

deccf.InlineRunInputSeriesInlineRunInputSeries describes a model value used by the Core model API editor functions.

Model value shape: { series: InlineSeriesInput | readonly { readonly date: DateString; readonly value: number; }[]; source?: Readonly<Record<string, unknown>> }

deccf.InlineRunInputValueInlineRunInputValue describes a model value used by the Core model API editor functions.

Model value shape: { value: InputValue; source?: Readonly<Record<string, unknown>> }

deccf.InlineSeriesInputInlineSeriesInput describes a model value used by the Core model API editor functions.

Model value shape: { points: readonly { readonly date: DateString; readonly value: number; }[]; interpolation?: "step" | "linear" }

deccf.InputConnectionMetadataInputConnectionMetadata describes a model value used by the Core model API editor functions.

Model value shape: { visible?: InputVisibility; hidden?: boolean; readOnly?: boolean; dynamic?: boolean; view?: "table" | "cards" | "sumdropdown"; discriminator?: "type"; variants?: readonly Readonly<{ readonly value: string; readonly label: string; readonly schema: InputDescription; }>[]; selectionMode?: ObjectVariantSelectionMode; title?: string; valueSource?: readonly string[]; connectedSource?: Readonly<{ readonly path: readonly string[]; readonly key: string; readonly where?: Readonly<Record<string, string | number | boolean>>; }> }

deccf.InputDescriptionInputDescription describes a model value used by the Core model API editor functions.

Model value shape: { constraints?: readonly ObjectInputConstraint[]; domain?: NumericDomain; name: string; shape: string; type: string; value?: InputValue; defaultValue?: InputValue; required?: boolean; layout?: InputLayout; ui?: Readonly<{ readonly [key: string]: unknown; readonly label?: string; }>; fields?: readonly InputDescription[]; item?: InputDescription; key?: string; options?: readonly Readonly<{ readonly value: string; readonly label: string; }>[]; series?: Readonly<{ readonly points: readonly Readonly<{ readonly date: DateString; readonly value: number; }>[]; readonly interpolation: "step" | "linear"; }>; visible?: InputVisibility; … 10 more fields }

deccf.InputFactoryInputFactory describes a model value used by the Core model API editor functions.

Model value shape: { decimal: (value: number, options?: InputOptions<number>) => InputReference<number>; rate: (value: number, options?: InputOptions<number>) => InputReference<number>; fraction: (value: number, options?: InputOptions<number>) => InputReference<number>; integer: (value: number, options?: InputOptions<number>) => InputReference<number>; boolean: (value: boolean, options?: BooleanInputOptions) => InputReference<boolean>; boolen: (value: boolean, options?: BooleanInputOptions) => InputReference<boolean>; lockable: <T extends InputReference<InputValue>>(locked: boolean, value: T, options?: InputMetadataOptions) => LockableInputReference<T>; hidden: { <T extends InputReference<InputValue>>(value: T, options?: InputMetadataOptions): T; <T extends InputValue>(value: InputProjectionReference<T> | T, options?: InputMetadataOptions): InputReference<T>; }; readonly: { <T extends InputReference<InputValue>>(value: T, options?: InputMetadataOptions): T; <T extends InputValue>(value: InputProjectionReference<T> | T, options?: InputMetadataOptions): InputReference<T>; }; readOnly: { <T extends InputReference<InputValue>>(value: T, options?: InputMetadataOptions): T; <T extends InputValue>(value: InputProjectionReference<T> | T, options?: InputMetadataOptions): InputReference<T>; }; str: (value?: string, options?: InputOptions<string>) => InputReference<string>; id: { (value: string, options?: InputOptions<string>): InputReference<string>; (options: Readonly<{ generate: "uuid"; }>, metadata?: Omit<InputOptions<string>, "newItem">): InputReference<string | undefined>; }; enum: <T extends string>(value: T, options: EnumInputOptions<T>) => InputReference<T>; domain: <TFields extends InputObjectFields>(fields: TFields, options?: ObjectConstraintOptions) => DomainInputReference<TFields>; section: <TFields extends InputObjectFields>(fields: TFields, options?: ObjectConstraintOptions) => ObjectInputReference<TFields>; aspect: <TFields extends InputObjectFields>(fields: TFields, options?: ObjectConstraintOptions) => ObjectInputReference<TFields>; … 16 more fields }

deccf.InputLayoutInputLayout describes a model value used by the Core model API editor functions.

Model value shape: "domain" | "section" | "aspect" | "group"

deccf.InputMetadataOptionsInputMetadataOptions describes a model value used by the Core model API editor functions.

Model value shape: { required?: boolean; visible?: InputVisibility; ui?: Readonly<InputUIOptions> }

deccf.InputObjectFieldsInputObjectFields describes a model value used by the Core model API editor functions.

Model value shape: Readonly<Record<string, InputReference<InputValue>>>

deccf.InputObjectValueInputObjectValue describes a model value used by the Core model API editor functions.

Model value shape: { readonly [K in keyof TFields]: TFields[K] extends InputReference<infer TValue> ? TValue : never }

deccf.InputOptionsInputOptions describes a model value used by the Core model API editor functions.

Model value shape: { kind?: "money" | "currency" | "decimal" | "rate" | "fraction" | "integer"; domain?: NumericDomain; required?: boolean; visible?: InputVisibility; newItem?: T | Readonly<{ generate: "uuid"; }>; ui?: Readonly<InputUIOptions> }

deccf.InputProjectionReferenceInputProjectionReference describes a model value used by the Core model API editor functions.

Model value shape: Reference<"input-projection"> & { readonly __valueType?: T }

deccf.InputReferenceInputReference describes a model value used by the Core model API editor functions.

Model value shape: Reference<"input"> & { readonly __valueType?: T }

deccf.InputRowProjectionInputRowProjection describes a model value used by the Core model API editor functions.

Model value shape: Readonly<{ /** The complete immutable typed row, including active variant fields, for calculation bindings. */ value: InputProjectionReference<InputObjectValue<TFields>>; data: Readonly<{ [K in keyof TFields]: TFields[K] extends InputReference<infer TValue> ? InputValueProjection<TValue> : never }>; }>

deccf.InputScalarFilterInputScalarFilter describes a model value used by the Core model API editor functions.

Model value shape: { readonly [K in keyof TFields as TFields[K] extends InputReference<infer TValue> ? NonNullable<TValue> extends string | number | boolean ? K : never : never]?: TFields[K] extends InputReference<infer TValue> ? Extract<TValue,string | number | boolean> : never; }

deccf.InputStringFieldInputStringField describes a model value used by the Core model API editor functions.

Model value shape: Extract<{ [K in keyof TFields]: TFields[K] extends InputReference<string> ? K : never; }[keyof TFields],string>

deccf.InputUIOptionsDisplay metadata. For ordinary object, domain, section, aspect and group inputs, optional note text appears after the fields. Omitted, blank or non-string notes display nothing. Notes are plain text and add no input value. Optional initialValueFrom is an absolute saved-input object-field path used only when opening an input draft whose target field is absent. It copies a supplied source value before using the declared default; explicit target values, including zero, win. Omission, unknown/malformed paths, accessors, inherited properties and array-row paths use the normal default. Optional initialValueScale defaults to 1 and multiplies an inherited finite number or Money amount, preserving currency. Invalid scales (not finite and positive), unsupported source shapes and overflow use the declared default. Explicit target values are never scaled. A saved scenario's individually selected retired hidden leaf follows its unique editable replacement alias and scale; explicit replacement selections win. Reads do not mutate saved input data or change direct calculation input validation. See the callable input.rate example.

Model value shape: { label?: string; note?: string; initialValueFrom?: string; initialValueScale?: number; visibleWhen?: InputVisibilityRule; choicesFrom?: Readonly<{ readonly path: string; readonly key: string; readonly label: string; readonly where?: Readonly<Record<string, string | number | boolean>>; }>; choices?: readonly Readonly<{ readonly value: string; readonly label: string; }>[] }

deccf.InputValidationErrorInputValidationError describes a model value used by the Core model API editor functions.

Model value shape: { path: string; code: string; message: string }

deccf.InputValueInputValue describes a model value used by the Core model API editor functions.

Model value shape: number | boolean | Money | DateString | Currency | string | null | undefined | readonly InputValue[] | InputValueRecord

deccf.InputValueProjectionInputValueProjection describes a model value used by the Core model API editor functions.

Model value shape: T extends Money | Currency ? InputProjectionReference<T> : T extends readonly (infer TValue extends InputValue)[] ? InputProjectionReference<T> & { readonly item: InputValueProjection<TValue> } : T extends InputValueRecord ? Readonly<{ value: InputProjectionReference<T>; data: { readonly [K in keyof T]: InputValueProjection<T[K]> } }> : InputProjectionReference<T>

deccf.InputValueRecordInputValueRecord describes a model value used by the Core model API editor functions.

Model value shape: InputValueRecord

deccf.InputVisibilityInputVisibility describes a model value used by the Core model API editor functions.

Model value shape: boolean | Readonly<InputVisibilityRule>

deccf.InputVisibilityRuleInputVisibilityRule describes a model value used by the Core model API editor functions.

Model value shape: { field: string; values: readonly (string | number | boolean)[] }

deccf.LifecycleReferenceLifecycleReference describes a model value used by the Core model API editor functions.

Model value shape: Reference<"lifecycle">

deccf.LockableInputReferenceLockableInputReference describes a model value used by the Core model API editor functions.

Model value shape: InputReference<LockableValue<T extends InputReference<infer TValue> ? TValue : never>> & { readonly locked: InputReference<boolean>; readonly value: T; }

deccf.LockableValueLockableValue describes a model value used by the Core model API editor functions.

Model value shape: { readonly locked: boolean; readonly value: T }

deccf.LookupKeyLookupKey describes a model value used by the Core model API editor functions.

Model value shape: string | InputReference<string> | InputProjectionReference<string>

deccf.LookupOptionsLookupOptions describes a model value used by the Core model API editor functions.

Model value shape: { readonly fallback?: F; readonly fallbackKeys?: never } | { readonly fallback: F; readonly fallbackKeys: readonly [string, ...string[]] }

deccf.LookupReferenceA symbolic scalar or declaration selected by an explicit related-row key.

Model value shape: Reference<'keyed-lookup'> & { readonly __lookupType?: T }

deccf.MetricDeclarationMetricDeclaration describes a model value used by the Core model API editor functions.

Model value shape: { schedule?: ScheduleReference; kind: "metric"; valueType: "number" | "text"; label?: string; unit?: string; owner?: EntityReference; source?: Readonly<{ readonly type: "domain-pack"; readonly name: string; }>; calculate: MetricFunction | TextMetricFunction; periodLength: number; frequency: number; annualAggregation: "sum" | "last"; fiscalYearStartMonth: number }

deccf.MetricFunctionMetricFunction describes a model value used by the Core model API editor functions.

Model value shape: (context: CalculationContext) => number | Money | undefined

deccf.MetricOptionsMetricOptions describes a model value used by the Core model API editor functions.

Model value shape: { schedule?: ScheduleReference; calculate?: MetricFunction | TextMetricFunction; value?: string | number | AccountReference | FieldReference | InputReference<number> | Money | CashflowReference | CalculationProjectionReference<unknown> | ExpressionReference | CalculationReference<unknown>; label?: string; source?: Readonly<{ readonly type: "domain-pack"; readonly name: string; }>; valueType?: "number" | "text"; unit?: string; periodLength?: number; frequency?: number; annualAggregation?: "sum" | "last"; owner?: EntityReference; fiscalYearStartMonth?: number }

deccf.MetricsTimingMetricsTiming describes a model value used by the Core model API editor functions.

Model value shape: { totalTicks: number; engine: MetricTimingGroup; model: MetricTimingGroup; domainPacks: Readonly<Record<string, MetricTimingGroup>> }

deccf.MetricSummaryMetricSummary describes a model value used by the Core model API editor functions.

Model value shape: { trials: number; mean: number; standardDeviation: number; min: number; max: number; distribution?: Readonly<{ readonly sampleCount: number; readonly bins: readonly Readonly<{ min: number; max: number; count: number; probability: number; cumulativeProbability: number; }>[]; }>; percentiles: Readonly<{ readonly p5: number; readonly p25: number; readonly p50: number; readonly p75: number; readonly p95: number; }> }

deccf.MetricTimingGroupMetricTimingGroup describes a model value used by the Core model API editor functions.

Model value shape: { totalTicks: number; steps: Readonly<Record<string, number>> }

deccf.MetricTimingStepsMetricTimingSteps describes a model value used by the Core model API editor functions.

Model value shape: Readonly<Record<string, number>>

deccf.MetricValueMetricValue describes a model value used by the Core model API editor functions.

Model value shape: MetricFunction | MetricDeclaration

deccf.ModelAccountDefinitionModelAccountDefinition describes a model value used by the Core model API editor functions.

Model value shape: { name: string; reference: AccountReference; owner?: EntityReference; type?: "asset" | "liability" | "equity" | "income" | "expense" | "transfer"; categoryPath?: string }

deccf.ModelBindingsModelBindings describes a model value used by the Core model API editor functions.

Model value shape: Readonly<Record<string, BindingSource>>

deccf.ModelCurrencyA fixed denomination or a declared fixed local currency-code input; no FX.

Model value shape: Currency | InputReference<string | Currency>

deccf.ModelDefinitionOptional model setting monteCarlo:{execution:'indexed',baselineMetrics:[...]} selects strict indexed Monte Carlo. Omission preserves general execution and its existing summaries. baselineMetrics defaults to []; entries must be unique names of declared metrics. Remaining sampled metrics need declarative metric({value,...}); every scheduled context is evaluated and the final summary retains the last defined emitted value. periodLength:1 and frequency:1 remain defaults; schedule.once(finalDate) selects only a final outcome. Supported sampled value sources are number, text or Money literals and input, calculation, calculation-projection or account references; direct flow, field and expression sources are rejected. All sampled ledger dependencies must support static indexed execution. A nonempty timeline without additional projection periods is required. Events, options, agreements, entity fields/lifecycles, derived inputs, triggered flows, expression bindings/amounts and account initializers using callbacks, expressions or calculations are unsupported. Unsupported callbacks, dynamic dependencies or unsupported graph features cause an error; there is no fallback. Baseline-only calculations can remain dynamic when outside sampled dependencies. Each named baseline metric is evaluated during the complete ordinary unseeded base calculation; its numeric final value is repeated across trials, so standard deviation is zero and all percentiles equal that base value. This is an author-selected fixed baseline statistic, not a sampled uncertainty estimate. Indexed mode summarizes declared numeric metrics only; implicit total, npv, irr and wal sampled summaries are omitted while the complete baseline retains ordinary results. Monthly periods, declared financial operations, global seeded draws, Sobol coordinates and monetary output valuation remain in effect. Active approximate mode (approximate:true with more than 1000 trials) is rejected; at most 1000 trials retain exact execution and inactive approximation metadata. Optional monteCarlo.series selects unique existing account.<name>.balance, flow.<name> or metric.<name> series in general or indexed execution. seriesSummaries[id] contains exact model dates and points of SampledSeriesPointSummary (trials, mean, standardDeviation, min, max and empirical percentiles) or null for missing observations; temporal points omit histograms while existing scalar MetricSummary retains distribution. Series metadata includes optional currency/unit and valuation metadata. Matching baseline arrays preserve the ordinary unseeded curve before annual amount storage. annual:{dates,points,baseline} aggregates each trial before statistics: flows sum, accounts use last balance, metrics follow annualAggregation and fiscalYearStartMonth. Money valuation precedes grouping; amountStorage never discards sampled original dates. Omitted series preserves the existing result shape and avoids temporal summary work. Baseline metric selection is also available in general execution. See Simulate uncertainty and Valuation and uncertainty for a complete callable example, supported values and validation. Optional monteCarlo.samplingLayout accepts only static-first when supplied; omission preserves the original Sobol layout. It preserves model-wide ctx.draw coordinates, promotes every declared bind.sample model-wide period slot before other ctx.sample owner/period slots, and removes promoted slots from the remaining namespace to avoid aliasing. Annual bindings promote the first represented period of each calendar year, including partial years; period bindings promote every period. Inputs sort by declared name and periods chronologically; duplicate consumers share their existing logical sample. Slots are reserved for unused bindings, branches and overridden inputs before execution, so call order and worker partitioning cannot change streams. The opt-in changes Sobol sample streams but leaves pseudorandom streams unchanged; it works in general and indexed execution. The 21,201 actual-coordinate limit still applies and out-of-range dynamic samples fail explicitly. samplingDimensions retains the full potential namespace size, including unused owner/period slots; static-first reorders it rather than limiting supported sampling identities. Structural model changes may change stream assignments.

Model value shape: { calculator?: Readonly<CalculatorOptions>; monteCarlo?: Readonly<ModelMonteCarloOptions>; scenarios?: readonly ModelScenarioSuggestion[]; kind: "model"; name: string; currency: TCurrency; inflation?: number | InputReference<number>; timeline: Timeline; preconditions: Readonly<Record<string, InputReference<number>>>; entities: Readonly<Record<string, EntityReference>>; accounts: Readonly<Record<string, AccountReference>>; phases: Readonly<Record<string, PhaseReference>>; flows: Readonly<Record<string, CashflowReference>>; agreements: Readonly<Record<string, AgreementReference>>; events: Readonly<Record<string, EventReference>>; options: Readonly<Record<string, OptionReference>>; … 4 more fields }

deccf.ModelDescriptionModelDescription describes a model value used by the Core model API editor functions.

Model value shape: { inflation?: number; calculator?: Readonly<CalculatorOptions>; scenarios?: readonly ModelScenarioSuggestion[]; preconditions: readonly InputDescription[]; currency?: string; dates?: readonly DateString[] }

deccf.ModelMonteCarloOptionsExplicit fast trial contract. The full ordinary baseline is still published. Optional model setting monteCarlo:{execution:'indexed',baselineMetrics:[...]} selects strict indexed Monte Carlo. Omission preserves general execution and its existing summaries. baselineMetrics defaults to []; entries must be unique names of declared metrics. Remaining sampled metrics need declarative metric({value,...}); every scheduled context is evaluated and the final summary retains the last defined emitted value. periodLength:1 and frequency:1 remain defaults; schedule.once(finalDate) selects only a final outcome. Supported sampled value sources are number, text or Money literals and input, calculation, calculation-projection or account references; direct flow, field and expression sources are rejected. All sampled ledger dependencies must support static indexed execution. A nonempty timeline without additional projection periods is required. Events, options, agreements, entity fields/lifecycles, derived inputs, triggered flows, expression bindings/amounts and account initializers using callbacks, expressions or calculations are unsupported. Unsupported callbacks, dynamic dependencies or unsupported graph features cause an error; there is no fallback. Baseline-only calculations can remain dynamic when outside sampled dependencies. Each named baseline metric is evaluated during the complete ordinary unseeded base calculation; its numeric final value is repeated across trials, so standard deviation is zero and all percentiles equal that base value. This is an author-selected fixed baseline statistic, not a sampled uncertainty estimate. Indexed mode summarizes declared numeric metrics only; implicit total, npv, irr and wal sampled summaries are omitted while the complete baseline retains ordinary results. Monthly periods, declared financial operations, global seeded draws, Sobol coordinates and monetary output valuation remain in effect. Active approximate mode (approximate:true with more than 1000 trials) is rejected; at most 1000 trials retain exact execution and inactive approximation metadata. Optional monteCarlo.series selects unique existing account.<name>.balance, flow.<name> or metric.<name> series in general or indexed execution. seriesSummaries[id] contains exact model dates and points of SampledSeriesPointSummary (trials, mean, standardDeviation, min, max and empirical percentiles) or null for missing observations; temporal points omit histograms while existing scalar MetricSummary retains distribution. Series metadata includes optional currency/unit and valuation metadata. Matching baseline arrays preserve the ordinary unseeded curve before annual amount storage. annual:{dates,points,baseline} aggregates each trial before statistics: flows sum, accounts use last balance, metrics follow annualAggregation and fiscalYearStartMonth. Money valuation precedes grouping; amountStorage never discards sampled original dates. Omitted series preserves the existing result shape and avoids temporal summary work. Baseline metric selection is also available in general execution. See Simulate uncertainty and Valuation and uncertainty for a complete callable example, supported values and validation. Optional monteCarlo.samplingLayout accepts only static-first when supplied; omission preserves the original Sobol layout. It preserves model-wide ctx.draw coordinates, promotes every declared bind.sample model-wide period slot before other ctx.sample owner/period slots, and removes promoted slots from the remaining namespace to avoid aliasing. Annual bindings promote the first represented period of each calendar year, including partial years; period bindings promote every period. Inputs sort by declared name and periods chronologically; duplicate consumers share their existing logical sample. Slots are reserved for unused bindings, branches and overridden inputs before execution, so call order and worker partitioning cannot change streams. The opt-in changes Sobol sample streams but leaves pseudorandom streams unchanged; it works in general and indexed execution. The 21,201 actual-coordinate limit still applies and out-of-range dynamic samples fail explicitly. samplingDimensions retains the full potential namespace size, including unused owner/period slots; static-first reorders it rather than limiting supported sampling identities. Structural model changes may change stream assignments.

Model value shape: { samplingLayout?: "static-first"; execution?: "indexed"; series?: readonly string[]; baselineMetrics?: readonly string[] }

deccf.ModelOptionsOptional model setting monteCarlo:{execution:'indexed',baselineMetrics:[...]} selects strict indexed Monte Carlo. Omission preserves general execution and its existing summaries. baselineMetrics defaults to []; entries must be unique names of declared metrics. Remaining sampled metrics need declarative metric({value,...}); every scheduled context is evaluated and the final summary retains the last defined emitted value. periodLength:1 and frequency:1 remain defaults; schedule.once(finalDate) selects only a final outcome. Supported sampled value sources are number, text or Money literals and input, calculation, calculation-projection or account references; direct flow, field and expression sources are rejected. All sampled ledger dependencies must support static indexed execution. A nonempty timeline without additional projection periods is required. Events, options, agreements, entity fields/lifecycles, derived inputs, triggered flows, expression bindings/amounts and account initializers using callbacks, expressions or calculations are unsupported. Unsupported callbacks, dynamic dependencies or unsupported graph features cause an error; there is no fallback. Baseline-only calculations can remain dynamic when outside sampled dependencies. Each named baseline metric is evaluated during the complete ordinary unseeded base calculation; its numeric final value is repeated across trials, so standard deviation is zero and all percentiles equal that base value. This is an author-selected fixed baseline statistic, not a sampled uncertainty estimate. Indexed mode summarizes declared numeric metrics only; implicit total, npv, irr and wal sampled summaries are omitted while the complete baseline retains ordinary results. Monthly periods, declared financial operations, global seeded draws, Sobol coordinates and monetary output valuation remain in effect. Active approximate mode (approximate:true with more than 1000 trials) is rejected; at most 1000 trials retain exact execution and inactive approximation metadata. Optional monteCarlo.series selects unique existing account.<name>.balance, flow.<name> or metric.<name> series in general or indexed execution. seriesSummaries[id] contains exact model dates and points of SampledSeriesPointSummary (trials, mean, standardDeviation, min, max and empirical percentiles) or null for missing observations; temporal points omit histograms while existing scalar MetricSummary retains distribution. Series metadata includes optional currency/unit and valuation metadata. Matching baseline arrays preserve the ordinary unseeded curve before annual amount storage. annual:{dates,points,baseline} aggregates each trial before statistics: flows sum, accounts use last balance, metrics follow annualAggregation and fiscalYearStartMonth. Money valuation precedes grouping; amountStorage never discards sampled original dates. Omitted series preserves the existing result shape and avoids temporal summary work. Baseline metric selection is also available in general execution. See Simulate uncertainty and Valuation and uncertainty for a complete callable example, supported values and validation. Optional monteCarlo.samplingLayout accepts only static-first when supplied; omission preserves the original Sobol layout. It preserves model-wide ctx.draw coordinates, promotes every declared bind.sample model-wide period slot before other ctx.sample owner/period slots, and removes promoted slots from the remaining namespace to avoid aliasing. Annual bindings promote the first represented period of each calendar year, including partial years; period bindings promote every period. Inputs sort by declared name and periods chronologically; duplicate consumers share their existing logical sample. Slots are reserved for unused bindings, branches and overridden inputs before execution, so call order and worker partitioning cannot change streams. The opt-in changes Sobol sample streams but leaves pseudorandom streams unchanged; it works in general and indexed execution. The 21,201 actual-coordinate limit still applies and out-of-range dynamic samples fail explicitly. samplingDimensions retains the full potential namespace size, including unused owner/period slots; static-first reorders it rather than limiting supported sampling identities. Structural model changes may change stream assignments.

Model value shape: { calculator?: Readonly<CalculatorOptions>; monteCarlo?: Readonly<ModelMonteCarloOptions>; scenarios?: readonly ModelScenarioSuggestion[]; name?: string; currency: TCurrency; inflation?: number | InputReference<number>; timeline: Timeline; preconditions?: Readonly<Record<string, InputReference<InputValue>>> | DomainInputReference<Readonly<Record<string, InputReference<InputValue>>>>; entities?: Readonly<Record<string, EntityReference>>; accounts?: Readonly<Record<string, AccountReference>>; calculations?: Readonly<Record<string, CalculationReference<unknown>>>; phases?: Readonly<Record<string, PhaseReference>>; flows?: readonly CashflowReference[] | Readonly<Record<string, CashflowReference | FlowGroupReference>>; agreements?: Readonly<Record<string, AgreementReference>>; events?: Readonly<Record<string, EventReference>>; options?: Readonly<Record<string, OptionReference>>; … 3 more fields }

deccf.ModelScenarioSuggestionOptional editable calculator starting points. Arrays and monetary leaves are complete values.

Model value shape: { name: string; input: Readonly<Record<string, InputValue>> }

deccf.MoneyMoney describes a model value used by the Core model API editor functions.

Model value shape: { kind: "money"; amount: number; currency: Currency; date?: DateString }

deccf.MoneyValueSelects output purchasing power for run(), runMonteCarlo() and runScenarios(). The supported string values are 'nominal' (default) and 'today'. 'today' expresses declared monetary outputs at the first resolved timeline date using the model's annual inflation; plain numbers, rates and text retain their values. Other strings are rejected. Results record the selection as moneyValue, alongside inflation and moneyValueBaseDate.

Model value shape: "nominal" | "today"

deccf.MonteCarloControlsOptional third runMonteCarlo argument, defaulting to {}. onProgress receives a readonly MonteCarloProgress snapshot synchronously. Observer errors are ignored and return values are not awaited. Omission disables observation. Keep this callback separate from options; it is absent from results, receipts and cache identities. The financial model does not own progress UI. See runMonteCarlo for a complete callable example.

Model value shape: { onProgress?: (progress: Readonly<MonteCarloProgress>) => void }

deccf.MonteCarloOptionsMonteCarloOptions describes a model value used by the Core model API editor functions.

Model value shape: { trials: number; seed: number; sampling?: "pseudo-random" | "sobol"; approximate?: boolean; approximationBins?: number; parameters?: Readonly<Record<string, unknown>>; moneyValue?: MoneyValue; amountStorage?: AmountStorage; currency?: Currency; discountRate?: number; trial?: number; overrides?: ReadonlyMap<InputReference<number>, InlineRunInput>; deterministic?: DeterministicRunConfig }

deccf.MonteCarloProgressImmutable completed-work snapshot supplied to the optional runMonteCarlo third-argument observer. phase is preparing, baseline, trials, finalizing or complete. completedTrials and totalTrials count trials; completedWork and totalWork also count one baseline and one final summary (N + 2). baselineComplete records whether the ordinary base calculation has finished. Baseline order follows the execution strategy. Counts measure actual completed units, not elapsed time; snapshots may be coalesced. complete is emitted only on success. See runMonteCarlo for a callable observation example and Calculation progress for automatic Calculator feedback.

Model value shape: { phase: "preparing" | "baseline" | "trials" | "finalizing" | "complete"; completedTrials: number; totalTrials: number; completedWork: number; totalWork: number; baselineComplete: boolean }

deccf.MonteCarloResultMonteCarloResult describes a model value used by the Core model API editor functions.

Model value shape: { seriesSummaries?: Readonly<Record<string, SampledSeriesSummary>>; currency: string; monte_carlo: Readonly<{ readonly status: "ok"; readonly trials: number; readonly seed: number; readonly metrics: Readonly<Record<string, MetricSummary>>; readonly trial_summaries: readonly never[]; }>; seed: number; trials: number; sampling: "pseudo-random" | "sobol"; samplingDimensions?: number; approximate: boolean; approximation?: Readonly<{ readonly active: boolean; readonly minimumTrials: 1001; readonly bins: number; readonly warnings?: readonly string[]; readonly curvesChecked?: number; readonly curvesInsufficient?: number; readonly amountCacheHits?: number; readonly amountCacheEntries?: number; readonly histogramHits?: number; readonly histogramChecks?: number; readonly histogramInvalidated?: number; readonly curvesSkipped?: number; readonly slicesChecked?: number; readonly status?: "insufficient-data" | "partial" | "observed"; readonly note?: string; }>; summaries: Readonly<Record<string, MetricSummary>>; timings: MonteCarloTimings; events: readonly Readonly<Record<string, unknown>>[]; metrics: Readonly<{ readonly [name: string]: number; readonly total: number; readonly npv: number; readonly irr: number | null; readonly wal: number | null; }>; flow: (reference: CashflowReference) => readonly number[]; calculation: (reference: CalculationReference | CalculationProjectionReference) => readonly unknown[]; deterministic: DeterministicResults; … 24 more fields }

deccf.MonteCarloTimingsMonteCarloTimings describes a model value used by the Core model API editor functions.

Model value shape: { unit: "microseconds"; clock: "performance.now"; mainTicks: number; metrics: MetricsTiming; baselineRun: ResultTimings; trialRuns: readonly Readonly<{ readonly trial: number; readonly mainTicks: number; readonly metricsTicks: number; readonly resultConstructionTicks: number; readonly totalTicks: number; readonly totalMs: number; }>[]; summaryTicks: number; totalTicks: number; totalMs: number }

deccf.NumericDomainNumericDomain describes a model value used by the Core model API editor functions.

Model value shape: readonly [minimum: number, maximum: number]

deccf.ObjectArrayInputReferenceObjectArrayInputReference describes a model value used by the Core model API editor functions.

Model value shape: InputReference<readonly InputObjectValue<TFields>[]> & { readonly item: InputRowProjection<TFields> }

deccf.ObjectArrayOptionsObjectArrayOptions describes a model value used by the Core model API editor functions.

Model value shape: { ui?: Readonly<{ readonly [key: string]: unknown; readonly label?: string; readonly addLabel?: string; }>; title?: string; key?: Extract<keyof TFields, string>; item?: ObjectInputReference<TFields>; dynamic?: boolean; type?: "table" | "cards"; connectedSource?: ObjectArrayInputReference<Readonly<Record<string, InputReference<InputValue>>>>; connectedWhere?: Readonly<Record<string, string | number | boolean>>; required?: boolean; visible?: InputVisibility }

deccf.ObjectConstraintOptionsObjectConstraintOptions describes a model value used by the Core model API editor functions.

Model value shape: { constraints?: readonly ObjectInputConstraint[]; required?: boolean; visible?: InputVisibility; ui?: Readonly<InputUIOptions> }

deccf.ObjectInputConstraintA relation between compatible numeric, same-currency Money, or date leaves of one object.

Model value shape: { left: string; relation: "<" | "<=" | ">" | ">=" | "==" | "!="; right: string; message?: string }

deccf.ObjectInputOptionsObjectInputOptions describes a model value used by the Core model API editor functions.

Model value shape: { type?: "sumdropdown"; label?: string; title?: string; constraints?: readonly ObjectInputConstraint[]; required?: boolean; visible?: InputVisibility; ui?: Readonly<InputUIOptions> }

deccf.ObjectInputReferenceObjectInputReference describes a model value used by the Core model API editor functions.

Model value shape: InputReference<InputObjectValue<TFields>>

deccf.ObjectVariantArrayInputReferenceObjectVariantArrayInputReference describes a model value used by the Core model API editor functions.

Model value shape: InputReference<readonly (ObjectVariantValue<TVariants> & Readonly<Record<TKey, string>>)[]> & { readonly item: InputValueProjection<ObjectVariantValue<TVariants> & Readonly<Record<TKey, string>>>; }

deccf.ObjectVariantArrayOptionsObjectVariantArrayOptions describes a model value used by the Core model API editor functions.

Model value shape: { type: ObjectVariantSelectionMode; title?: string; key?: TKey; required?: boolean; visible?: InputVisibility; ui?: Readonly<InputUIOptions> }

deccf.ObjectVariantCatalogueObjectVariantCatalogue describes a model value used by the Core model API editor functions.

Model value shape: readonly InputReference<InputValueRecord>[]

deccf.ObjectVariantInputReferenceObjectVariantInputReference describes a model value used by the Core model API editor functions.

Model value shape: InputReference<ObjectVariantValue<TVariants>>

deccf.ObjectVariantOptionsObjectVariantOptions describes a model value used by the Core model API editor functions.

Model value shape: { title?: string; label?: string; required?: boolean; visible?: InputVisibility; ui?: Readonly<InputUIOptions> }

deccf.ObjectVariantSelectionModeObjectVariantSelectionMode describes a model value used by the Core model API editor functions.

Model value shape: 'manyOfAnyChangeable' | 'manyOfAny' | 'anyOf'

deccf.ObjectVariantValueObjectVariantValue describes a model value used by the Core model API editor functions.

Model value shape: TVariants[number] extends InputReference<infer TValue> ? TValue : never

deccf.OnceBindingReferenceOnceBindingReference describes a model value used by the Core model API editor functions.

Model value shape: BindingReference<T, "once">

deccf.OnceContextInitialization context for bind.once: configuration inputs and declared bindings only, without time or ledger reads.

Model value shape: { get: { <T extends InputValue>(reference: InputReference<T>): T; <T>(reference: BindingReference<T>): T; }; draw: (reference: InputReference<number>) => number; sample: (reference: InputReference<number>) => number }

deccf.OnceDataData-only configuration snapshots preserve model references but reject functions at every nesting level.

Model value shape: T extends (...args: never[]) => unknown ? never : T extends Reference<ReferenceKind> ? T : T extends object ? { readonly [K in keyof T]: OnceData<T[K]> } : T

deccf.OptionReferenceOptionReference describes a model value used by the Core model API editor functions.

Model value shape: Reference<"option">

deccf.ParameterBindingReferenceParameterBindingReference describes a model value used by the Core model API editor functions.

Model value shape: BindingReference<T, "parameter">

deccf.PhaseReferencePhaseReference describes a model value used by the Core model API editor functions.

Model value shape: Reference<"phase">

deccf.PlacementPlacement describes a model value used by the Core model API editor functions.

Model value shape: "start" | "mid" | "end"

deccf.PreparedModelPreparedModel describes a model value used by the Core model API editor functions.

Model value shape: { run: (options?: PreparedRunOptions) => TResult; withParameters: (parameters: Readonly<Record<string, unknown>>) => PreparedModel<TResult> }

deccf.PreparedOutputReferencePreparedOutputReference describes a model value used by the Core model API editor functions.

Model value shape: AccountReference | CalculationReference | CalculationProjectionReference

deccf.PreparedOutputsPreparedOutputs describes a model value used by the Core model API editor functions.

Model value shape: Readonly<Record<string, PreparedOutputReference>>

deccf.PreparedOutputValuesPreparedOutputValues describes a model value used by the Core model API editor functions.

Model value shape: { readonly [K in keyof TOutputs]: BindingValue<TOutputs[K]> }

deccf.PreparedRunOptionsValues allowed to change without preparing model structure again. Other options are rejected by prepared.run().

Model value shape: { parameters?: Readonly<Record<string, unknown>>; seed?: number; trial?: number }

deccf.PresentationCalculationReferenceOne actual published calculation or projection.

Model value shape: CalculationReference | CalculationProjectionReference | { readonly kind: "presentation-calculation"; readonly id: string } | { readonly $ref: "calculation"; readonly id: string; readonly path?: string | readonly string[] }

deccf.PresentationCalculationSourcePresentationCalculationSource describes a model value used by the Core model API editor functions.

Model value shape: PresentationCalculationReference | PresentationSampledCalculationSource

deccf.PresentationDataCardPresentationDataCard describes a model value used by the Core model API editor functions.

Model value shape: { label: string; value?: string | number | Money; detail?: string; tone?: "positive" | "negative" | "warning" | "neutral"; format?: "number" | "money" | "percent" | "yesNo"; unit?: string }

deccf.PresentationDataOptionsPresentationDataOptions describes a model value used by the Core model API editor functions.

Model value shape: { title?: string | false; visible?: boolean | "auto"; scenario?: string | number | readonly (string | number)[] }

deccf.PresentationDeclaredDataCardPresentation-owned display metadata; no callbacks or executable properties.

Model value shape: { value: PresentationCalculationReference | PresentationMetricExpression; unit?: string; label: string; detail?: string; tone?: "positive" | "negative" | "warning" | "neutral"; format?: "number" | "money" | "percent" | "yesNo" }

deccf.PresentationInputNumberExpressionA display coordinate only: finite numbers, numeric inputs, or two-operand addition. Addition may nest to depth 32 and must produce a finite result.

Model value shape: number | PresentationInputSelector<number> | { readonly add: readonly [PresentationInputNumberExpression, PresentationInputNumberExpression] }

deccf.PresentationInputNumberListPresentationInputNumberList describes a model value used by the Core model API editor functions.

Model value shape: readonly PresentationInputNumberExpression[] | PresentationInputSelector<readonly number[]>

deccf.PresentationInputRowsSelectionPresentationInputRowsSelection describes a model value used by the Core model API editor functions.

Model value shape: { source: PresentationInputSelector<InputValue>; path?: string | readonly string[]; field: string; when?: { readonly path: string | readonly string[]; readonly equals: number | string | boolean | null; }; otherwise?: PresentationInputNumberList }

deccf.PresentationInputSelectorDeclared inputs bind to the effective input value in each selected scenario.

Model value shape: InputReference<T> | InputProjectionReference<T> | { readonly $ref: "input"; readonly id: string; readonly path?: readonly string[] }

deccf.PresentationMetricExpressionSelected sampled metric percentile, finite numeric constant, or bounded arithmetic expression. Subtract requires equal units/currencies; multiply accepts at most one Money operand. Divide supports number/number, Money/number and same-currency Money/Money. Missing sampled observations propagate null. Zero division defaults to null. Clamps are finite amounts in the expression's resulting unit; nesting is limited to 32 levels. nullAbove selects a same-unit sampled limit; after clamps, values above it or with a missing limit become null.

Model value shape: number | PresentationMetricSelector | ({ readonly subtract: readonly [PresentationMetricExpression, PresentationMetricExpression] } & { readonly minimum?: number; readonly maximum?: number; readonly nullAbove?: PresentationMetricExpression }) | ({ readonly multiply: readonly [PresentationMetricExpression, PresentationMetricExpression] } & { readonly minimum?: number; readonly maximum?: number; readonly nullAbove?: PresentationMetricExpression }) | ({ readonly divide: readonly [PresentationMetricExpression, PresentationMetricExpression]; readonly onZero?: number | null | PresentationZeroDivisionPolicy } & { readonly minimum?: number; readonly maximum?: number; readonly nullAbove?: PresentationMetricExpression })

deccf.PresentationMetricSelectorPresentationMetricSelector describes a model value used by the Core model API editor functions.

Model value shape: { readonly kind: "presentation-metric"; readonly id: string } | { readonly $ref: "metric"; readonly id: string }

deccf.PresentationSampledCalculationSourceOverlay actual sampled percentile expressions onto existing declared numeric/Money fields. Paths are safe dot-separated own-property paths relative to values; absent rows are skipped. Ordinary runs retain the published values. In Monte Carlo, unavailable sampled percentiles become null. Money retains the published target currency/date; expression units must match. values must be one ordinary calculation reference/projection; nested wrappers are unsupported.

Model value shape: { values: PresentationCalculationReference; percentile?: number; metrics: Readonly<Record<string, PresentationMetricExpression>> }

deccf.PresentationSnapshotOptionsPresentationSnapshotOptions describes a model value used by the Core model API editor functions.

Model value shape: { date?: string; periodIndex?: number; year?: string | number; title?: string | false; visible?: boolean | "auto"; scenario?: string | number | readonly (string | number)[] }

deccf.PresentationStandardSeriesColumnPresentationStandardSeriesColumn describes a model value used by the Core model API editor functions.

Model value shape: { source: PresentationStandardSeriesSource; key?: string; label?: string }

deccf.PresentationStandardSeriesOptionsPresentationStandardSeriesOptions describes a model value used by the Core model API editor functions.

Model value shape: { period?: "monthly" | "months" | "years" | "yearly"; percentile?: number; xAxis?: { readonly kind: "date" | "year" | "age"; readonly currentAge?: number | PresentationInputSelector<number>; readonly startDate?: DateString; }; years?: PresentationInputNumberList; range?: { readonly from?: PresentationInputNumberExpression; readonly to?: PresentationInputNumberExpression; }; ages?: PresentationInputNumberList | PresentationInputRowsSelection; date?: string; periodIndex?: number; year?: string | number; title?: string | false; visible?: boolean | "auto"; scenario?: string | number | readonly (string | number)[] }

deccf.PresentationStandardSeriesSourcePresentationStandardSeriesSource describes a model value used by the Core model API editor functions.

Model value shape: AccountReference | CashflowReference | PresentationMetricSelector | string | { readonly $ref: "account" | "flow"; readonly id: string }

deccf.PresentationZeroDivisionPolicyOn a zero divisor, choose by whether the numerator is also zero. Both outcomes are required.

Model value shape: { whenZero: number; otherwise: number }

deccf.PreviousBindingReferenceA prior calculation value; project selects a validated result field and preserves the first-period zero sentinel.

Model value shape: BindingReference<T | 0, "previous"> & { project<TPath extends string | readonly string[]>(path: TPath): PreviousBindingReference<CalculationFieldValue<T, TPath>>; }

deccf.PriorityOptionsPriorityOptions describes a model value used by the Core model API editor functions.

Model value shape: { order: readonly string[]; requests?: AllocationKeyedValues }

deccf.ProportionalOptionsProportionalOptions describes a model value used by the Core model API editor functions.

Model value shape: { weights: AllocationKeyedValues; overrides?: AllocationKeyedValues; zeroBasis?: "error" | "equal" }

deccf.PublishedCalculationRecordPublishedCalculationRecord describes a model value used by the Core model API editor functions.

Model value shape: PublishedCalculationRecord

deccf.PublishedCalculationSeriesPublishedCalculationSeries describes a model value used by the Core model API editor functions.

Model value shape: { index: ResultSeriesIndex; values: readonly PublishedCalculationValue[]; resultType: CalculationResultType; owner?: string; unit?: string }

deccf.PublishedCalculationValuePublishedCalculationValue describes a model value used by the Core model API editor functions.

Model value shape: number | string | boolean | ResultMoney | null | PublishedCalculationRecord

deccf.RecordChartOptionsRecordChartOptions describes a model value used by the Core model API editor functions.

Model value shape: { showPoints?: boolean; uncertainty?: { readonly lower: PresentationSampledCalculationSource; readonly upper: PresentationSampledCalculationSource; readonly opacity?: number; readonly fade?: boolean; }; source?: PresentationCalculationSource; xKey?: string; series: readonly (PresentationStandardSeriesColumn | { readonly key: string; readonly label?: string; })[]; kind?: "line" | "horizontalBar" | "stackedBar"; horizontal?: boolean; normalize?: boolean; highlightKey?: string; unit?: "percent"; period?: "monthly" | "months" | "years" | "yearly"; percentile?: number; xAxis?: { readonly kind: "date" | "year" | "age"; readonly currentAge?: number | PresentationInputSelector<number>; readonly startDate?: DateString; }; years?: PresentationInputNumberList; range?: { readonly from?: PresentationInputNumberExpression; readonly to?: PresentationInputNumberExpression; }; ages?: PresentationInputNumberList | PresentationInputRowsSelection; … 6 more fields }

deccf.RecurringScheduleOptionsRecurringScheduleOptions describes a model value used by the Core model API editor functions.

Model value shape: { from?: DateString | InputReference<DateString>; to?: DateString | InputReference<DateString>; interval?: number; placement?: Placement; dayOfMonth?: number; endOfMonth?: boolean; except?: readonly (DateString | InputReference<DateString>)[]; also?: readonly (DateString | InputReference<DateString>)[] }

deccf.ReferenceReference describes a model value used by the Core model API editor functions.

Model value shape: { kind: K; token: symbol }

deccf.ReferenceKindReferenceKind describes a model value used by the Core model API editor functions.

Model value shape: "keyed-lookup" | "input" | "input-projection" | "input-collection-column" | "repeat-output-projection" | "repeat-column" | "repeated-component" | "repeat-view" | "entity" | "account" | "field" | "flow" | "flow-group" | "component" | "calculation" | "calculation-projection" | "binding" | "expression" | "allocation-method" | "derived" | "state" | "lifecycle" | "event" | "agreement" | "term" | "option" | "phase" | "category" | "trigger"

deccf.RepeatColumnReferenceRepeatColumnReference describes a model value used by the Core model API editor functions.

Model value shape: Reference<'repeat-column'> & { readonly __valueType?: T }

deccf.RepeatedComponentReferenceRepeatedComponentReference describes a model value used by the Core model API editor functions.

Model value shape: { item: RepeatItem<TFields, TOutputs>; outputs: Readonly<{ [K in keyof TOutputs]: RepeatOutputProjection<TOutputs[K]>; }>; where: (filters: RepeatFilter<TFields>) => RepeatViewReference<TFields, TOutputs>; column: <K extends keyof TFields & string>(field: K) => RepeatColumnReference<TFields[K] extends InputReference<infer TValue> ? TValue : InputValue>; kind: "repeated-component"; token: symbol }

deccf.RepeatFilterRepeatFilter describes a model value used by the Core model API editor functions.

Model value shape: Partial<{ readonly [K in keyof TFields]: TFields[K] extends InputReference<infer TValue> ? Extract<TValue, string | number | boolean | null> : never }>

deccf.RepeatItemRepeatItem describes a model value used by the Core model API editor functions.

Model value shape: { data: Readonly<{ [K in keyof TFields]: TFields[K] extends InputReference<infer TValue extends InputValue> ? InputValueProjection<TValue> : never; }>; outputs: Readonly<{ [K in keyof TOutputs]: RepeatOutputProjection<TOutputs[K]>; }> }

deccf.RepeatOutputProjectionRepeatOutputProjection describes a model value used by the Core model API editor functions.

Model value shape: Reference<"repeat-output-projection"> & { readonly __outputType?: T }

deccf.RepeatViewReferenceRepeatViewReference describes a model value used by the Core model API editor functions.

Model value shape: { item: RepeatItem<TFields, TOutputs>; outputs: Readonly<{ [K in keyof TOutputs]: RepeatOutputProjection<TOutputs[K]>; }>; where: (filters: RepeatFilter<TFields>) => RepeatViewReference<TFields, TOutputs>; column: <K extends keyof TFields & string>(field: K) => RepeatColumnReference<TFields[K] extends InputReference<infer TValue> ? TValue : InputValue>; kind: "repeat-view"; token: symbol }

deccf.ReportGroupOptionsReportGroupOptions describes a model value used by the Core model API editor functions.

Model value shape: { id?: string; label?: string; owner?: EntityReference; accounts: readonly AccountReference[] }

deccf.ResolveCashflowAccountsResolveCashflowAccounts describes a model value used by the Core model API editor functions.

Model value shape: (context: { readonly owner?: EntityReference; readonly accounts: readonly ModelAccountDefinition[]; readonly currency: Currency; /** Read a declared fixed input, including its run-time override when provided. */ readonly getInput: (reference: InputReference) => unknown; }) => readonly AccountReference[]

deccf.ResolvedCashflowBookingsResolvedCashflowBookings describes a model value used by the Core model API editor functions.

Model value shape: { bookings?: readonly BookingRow[]; cashAccount?: AccountReference; readsAccountsFrom?: readonly AccountReference[]; readsHistoricalAccountsFrom?: readonly AccountReference[] }

deccf.ResultCategoryResultCategory describes a model value used by the Core model API editor functions.

Model value shape: { path: string; label: string; parent_path?: string }

deccf.ResultMoneyResultMoney describes a model value used by the Core model API editor functions.

Model value shape: { amount: number; currency: string; date?: DateString }

deccf.ResultScalarResultScalar describes a model value used by the Core model API editor functions.

Model value shape: number | ResultMoney | Currency | string | boolean | null

deccf.ResultSeriesResultSeries describes a model value used by the Core model API editor functions.

Model value shape: { index: ResultSeriesIndex; values: readonly ResultSeriesValue[]; offset?: number; entity?: string; category?: string; agreement?: string; account?: string; periodLength?: number; frequency?: number; annualAggregation?: "sum" | "last"; fiscalYearStartMonth?: number; label?: string; unit?: string }

deccf.ResultSeriesIndexDescribes this series' own observation periods. Annual monetary storage adds dates (actual first covered source date), inclusive periodEnds, periodLabels and sourceCalendar; calendar is annual or fiscal-year. Partial years retain actual bounds. Its values must be paired with these dates rather than the unchanged monthly result.dates. Different fiscal owners may have different indexes.

Model value shape: { calendar: Calendar | "fiscal-year"; start: DateString; periods: number; periodLabels?: readonly string[]; dates?: readonly DateString[]; periodEnds?: readonly DateString[]; sourceCalendar?: Calendar }

deccf.ResultSeriesValueResultSeriesValue describes a model value used by the Core model API editor functions.

Model value shape: number | ResultMoney | null

deccf.ResultsGraphAccountResultsGraphAccount describes a model value used by the Core model API editor functions.

Model value shape: { opening_balance?: ResultMoney; roles?: readonly string[]; tags?: readonly string[]; name: string; side: "owed" | "due"; type?: "asset" | "liability" | "equity" | "income" | "expense" | "transfer"; label?: string; owner?: string; category?: string; category_label?: string }

deccf.ResultsGraphAgreementResultsGraphAgreement describes a model value used by the Core model API editor functions.

Model value shape: { name: string; subject: string; parties: Readonly<Record<string, string>> }

deccf.ResultsGraphEntityResultsGraphEntity describes a model value used by the Core model API editor functions.

Model value shape: { label?: string; symbol: string; family: string; parent?: string; owner?: string }

deccf.ResultsInputPreconditionResultsInputPrecondition describes a model value used by the Core model API editor functions.

Model value shape: { constraints?: readonly ObjectInputConstraint[]; layout?: InputLayout; fields?: readonly InputDescription[]; item?: InputDescription; key?: string; name: string; shape: string; type: string; value: ResultScalar; defaultValue?: InputValue; series?: InlineSeriesInput; origin: "model" | "run" | "file"; source?: Readonly<Record<string, unknown>>; visible?: InputVisibility; hidden?: boolean; readOnly?: boolean; … 8 more fields }

deccf.ResultTimingsResultTimings describes a model value used by the Core model API editor functions.

Model value shape: { unit: "microseconds"; clock: "performance.now"; setupTicks: number; simulationTicks: number; mainTicks: number; metrics: MetricsTiming; resultConstructionTicks: number; totalTicks: number; totalMs: number }

deccf.RunOptionsOptional amountStorage accepts 'period' (default), 'calendar-year' or 'fiscal-year'; other values are rejected. Annual storage compacts published monetary series, compatibility cashflow series, account postings and report groups. Flows and postings sum after output valuation; account balances keep their last observation; Money-valued metrics and numeric metrics with unit:'money' use annualAggregation ('last' by default). Fiscal grouping follows each owner's attributes.fiscalYearStartMonth (integer 1–12); ownerless values use January, and a metric's explicit fiscal start takes precedence. Source periods belong to their start-date year and are never split or prorated. Each compacted series index publishes actual covered dates, inclusive periodEnds, periodLabels and sourceCalendar, including partial years. Account postings retain account, flow, side, owner, category and flow_role, with periodEnd and periodLabel; period remains the original first calculation-period index. Report groups have an equivalent annual index. The calculation timeline, result.dates, live reference accessors, nonmonetary series and authored structured calculation records retain their original detail. Final metrics and Monte Carlo summaries are unchanged; only the ordinary baseline's published money observations are compacted. Shared scenario options apply to every scenario, and prepare() fixes the option at preparation. Result metadata amountStorage appears only in annual modes. Native reports use annual views; differing fiscal calendars require an owner selection, and calendar-year-only views cannot split fiscal totals. See Store monetary results by year for a monthly model example and output limits.

Model value shape: { parameters?: Readonly<Record<string, unknown>>; moneyValue?: MoneyValue; amountStorage?: AmountStorage; currency?: Currency; discountRate?: number; seed?: number; trial?: number; overrides?: ReadonlyMap<InputReference<number>, InlineRunInput>; deterministic?: DeterministicRunConfig }

deccf.RuntimeParameterValueRuntimeParameterValue describes a model value used by the Core model API editor functions.

Model value shape: TType extends "number" ? number : TType extends "money" ? Money : TType extends "boolean" ? boolean : TType extends "text" ? string : unknown

deccf.SampledSeriesPointSummaryNumeric temporal uncertainty: moments and empirical percentiles. Histograms are retained in scalar MetricSummary results, rather than repeated at every date.

Model value shape: Omit<MetricSummary, "distribution">

deccf.SampledSeriesSummaryPointwise uncertainty in an explicitly selected standard result series. Amounts use the run's money valuation; missing observations remain null and each point's trials counts only defined numeric observations. Annual values aggregate within each trial before statistics (flow=sum, account=last, metrics use their declaration).

Model value shape: { dates: readonly DateString[]; points: readonly SampledSeriesPointSummary[]; baseline?: readonly number[]; annual: Readonly<{ readonly dates: readonly DateString[]; readonly points: readonly (SampledSeriesPointSummary | null)[]; readonly baseline?: readonly (number | null)[]; }>; annualAggregation: "sum" | "last"; fiscalYearStartMonth: number; currency?: string; unit?: string; valuation?: Readonly<{ readonly moneyValue: "nominal" | "today"; readonly inflation: number; readonly moneyValueBaseDate: DateString; }> }

deccf.ScenarioAnalysisOptionsScenarioAnalysisOptions describes a model value used by the Core model API editor functions.

Model value shape: { onInvalid?: "error" | "omit"; metric: string; changes?: readonly AnalysisChange[]; label?: string; unit?: string; compare?: (candidate: number | Money, baseline: CalculationContext) => number | Money | undefined }

deccf.ScenarioResultListScenarioResultList describes a model value used by the Core model API editor functions.

Model value shape: { timings: ScenarioTimings; length: number; toString: () => string; toLocaleString: { (): string; (locales: string | string[], options?: Intl.NumberFormatOptions & Intl.DateTimeFormatOptions): string; }; concat: { (...items: ConcatArray<Readonly<{ readonly name: string; readonly result: TResult; }>>[]): Readonly<{ readonly name: string; readonly result: TResult; }>[]; (...items: (Readonly<{ readonly name: string; readonly result: TResult; }> | ConcatArray<Readonly<{ readonly name: string; readonly result: TResult; }>>)[]): Readonly<{ readonly name: string; readonly result: TResult; }>[]; }; join: (separator?: string) => string; slice: (start?: number, end?: number) => Readonly<{ readonly name: string; readonly result: TResult; }>[]; indexOf: (searchElement: Readonly<{ readonly name: string; readonly result: TResult; }>, fromIndex?: number) => number; lastIndexOf: (searchElement: Readonly<{ readonly name: string; readonly result: TResult; }>, fromIndex?: number) => number; every: { <S extends Readonly<{ readonly name: string; readonly result: TResult; }>>(predicate: (value: Readonly<{ readonly name: string; readonly result: TResult; }>, index: number, array: readonly Readonly<{ readonly name: string; readonly result: TResult; }>[]) => value is S, thisArg?: any): this is readonly S[]; (predicate: (value: Readonly<{ readonly name: string; readonly result: TResult; }>, index: number, array: readonly Readonly<{ readonly name: string; readonly result: TResult; }>[]) => unknown, thisArg?: any): boolean; }; some: (predicate: (value: Readonly<{ readonly name: string; readonly result: TResult; }>, index: number, array: readonly Readonly<{ readonly name: string; readonly result: TResult; }>[]) => unknown, thisArg?: any) => boolean; forEach: (callbackfn: (value: Readonly<{ readonly name: string; readonly result: TResult; }>, index: number, array: readonly Readonly<{ readonly name: string; readonly result: TResult; }>[]) => void, thisArg?: any) => void; map: <U>(callbackfn: (value: Readonly<{ readonly name: string; readonly result: TResult; }>, index: number, array: readonly Readonly<{ readonly name: string; readonly result: TResult; }>[]) => U, thisArg?: any) => U[]; filter: { <S extends Readonly<{ readonly name: string; readonly result: TResult; }>>(predicate: (value: Readonly<{ readonly name: string; readonly result: TResult; }>, index: number, array: readonly Readonly<{ readonly name: string; readonly result: TResult; }>[]) => value is S, thisArg?: any): S[]; (predicate: (value: Readonly<{ readonly name: string; readonly result: TResult; }>, index: number, array: readonly Readonly<{ readonly name: string; readonly result: TResult; }>[]) => unknown, thisArg?: any): Readonly<{ readonly name: string; readonly result: TResult; }>[]; }; reduce: { (callbackfn: (previousValue: Readonly<{ readonly name: string; readonly result: TResult; }>, currentValue: Readonly<{ readonly name: string; readonly result: TResult; }>, currentIndex: number, array: readonly Readonly<{ readonly name: string; readonly result: TResult; }>[]) => Readonly<{ readonly name: string; readonly result: TResult; }>): Readonly<{ readonly name: string; readonly result: TResult; }>; (callbackfn: (previousValue: Readonly<{ readonly name: string; readonly result: TResult; }>, currentValue: Readonly<{ readonly name: string; readonly result: TResult; }>, currentIndex: number, array: readonly Readonly<{ readonly name: string; readonly result: TResult; }>[]) => Readonly<{ readonly name: string; readonly result: TResult; }>, initialValue: Readonly<{ readonly name: string; readonly result: TResult; }>): Readonly<{ readonly name: string; readonly result: TResult; }>; <U>(callbackfn: (previousValue: U, currentValue: Readonly<{ readonly name: string; readonly result: TResult; }>, currentIndex: number, array: readonly Readonly<{ readonly name: string; readonly result: TResult; }>[]) => U, initialValue: U): U; }; reduceRight: { (callbackfn: (previousValue: Readonly<{ readonly name: string; readonly result: TResult; }>, currentValue: Readonly<{ readonly name: string; readonly result: TResult; }>, currentIndex: number, array: readonly Readonly<{ readonly name: string; readonly result: TResult; }>[]) => Readonly<{ readonly name: string; readonly result: TResult; }>): Readonly<{ readonly name: string; readonly result: TResult; }>; (callbackfn: (previousValue: Readonly<{ readonly name: string; readonly result: TResult; }>, currentValue: Readonly<{ readonly name: string; readonly result: TResult; }>, currentIndex: number, array: readonly Readonly<{ readonly name: string; readonly result: TResult; }>[]) => Readonly<{ readonly name: string; readonly result: TResult; }>, initialValue: Readonly<{ readonly name: string; readonly result: TResult; }>): Readonly<{ readonly name: string; readonly result: TResult; }>; <U>(callbackfn: (previousValue: U, currentValue: Readonly<{ readonly name: string; readonly result: TResult; }>, currentIndex: number, array: readonly Readonly<{ readonly name: string; readonly result: TResult; }>[]) => U, initialValue: U): U; }; … 17 more fields }

deccf.ScenarioRunResultScenarioRunResult describes a model value used by the Core model API editor functions.

Model value shape: CashflowResult | MonteCarloResult

deccf.ScenarioTimingsScenarioTimings describes a model value used by the Core model API editor functions.

Model value shape: { unit: "microseconds"; clock: "performance.now"; mainTicks: number; metrics: MetricsTiming; scenarios: readonly Readonly<{ readonly name: string; readonly mainTicks: number; readonly metricsTicks: number; readonly resultConstructionTicks: number; readonly summaryTicks?: number; readonly totalTicks: number; readonly totalMs: number; }>[]; totalTicks: number; totalMs: number }

deccf.ScheduleFactoryScheduleFactory describes a model value used by the Core model API editor functions.

Model value shape: { once: (date: DateString | InputReference<DateString>, options?: { readonly placement?: Placement; }) => ScheduleReference; onceAfterNoOfDays: (days: number) => ScheduleReference; every: (frequency: { readonly unit: "day" | "month"; readonly size: number; }, options?: RecurringScheduleOptions) => ScheduleReference; daily: (options?: RecurringScheduleOptions) => ScheduleReference; weekly: (options?: RecurringScheduleOptions) => ScheduleReference; monthly: (options?: RecurringScheduleOptions) => ScheduleReference; quarterly: (options?: RecurringScheduleOptions) => ScheduleReference; annual: (options?: RecurringScheduleOptions) => ScheduleReference; yearEnd: (options?: Pick<RecurringScheduleOptions, "from" | "to" | "placement" | "except" | "also">) => ScheduleReference; phaseStart: (phase: PhaseReference) => ScheduleReference; phaseEnd: (phase: PhaseReference) => ScheduleReference; phaseEnter: (phase: PhaseReference) => ScheduleReference }

deccf.ScheduleReferenceScheduleReference describes a model value used by the Core model API editor functions.

Model value shape: { type: string; placement?: Placement; days?: number }

deccf.SniMainGroupSniMainGroup describes a model value used by the Core model API editor functions.

Model value shape: { code: string; label: string }

deccf.StandardSeriesTableOptionsTemporal mode; existing custom-record source/columns options remain supported separately.

Model value shape: { series: readonly PresentationStandardSeriesColumn[]; source?: never; allowEmpty?: boolean; period?: "monthly" | "months" | "years" | "yearly"; percentile?: number; xAxis?: { readonly kind: "date" | "year" | "age"; readonly currentAge?: number | PresentationInputSelector<number>; readonly startDate?: DateString; }; years?: PresentationInputNumberList; range?: { readonly from?: PresentationInputNumberExpression; readonly to?: PresentationInputNumberExpression; }; ages?: PresentationInputNumberList | PresentationInputRowsSelection; date?: string; periodIndex?: number; year?: string | number; title?: string | false; visible?: boolean | "auto"; scenario?: string | number | readonly (string | number)[] }

deccf.StatementBalanceStatementBalance describes a model value used by the Core model API editor functions.

Model value shape: { account: AccountReference; value: number | Money | InputReference<number | Money> }

deccf.StatementOptionsStatementOptions describes a model value used by the Core model API editor functions.

Model value shape: { name?: string; owner?: EntityReference; schedule: ScheduleReference; balances: readonly StatementBalance[]; balancingAccount?: AccountReference; dependsOn?: readonly CashflowReference[] }

deccf.StateReferenceStateReference describes a model value used by the Core model API editor functions.

Model value shape: Reference<"state">

deccf.StateTransitionStateTransition describes a model value used by the Core model API editor functions.

Model value shape: { from: StateReference; to: StateReference; when?: (context: CalculationContext) => boolean }

deccf.StaticBookingAmountStaticBookingAmount describes a model value used by the Core model API editor functions.

Model value shape: Exclude<BookingAmount, Function> | StaticCallback<TBindings, number | Money>

deccf.StaticBookingRowStaticBookingRow describes a model value used by the Core model API editor functions.

Model value shape: Readonly<{ readonly debit: AccountReference | LookupReference<AccountReference>; readonly amount?: StaticBookingAmount<TBindings> }> | Readonly<{ readonly credit: AccountReference | LookupReference<AccountReference>; readonly amount?: StaticBookingAmount<TBindings> }>

deccf.StaticCalculationContextFixed callback context for static calculations and flows. Read declared values from the first callback argument.

Model value shape: { time: TimeContext; currency: Currency }

deccf.StaticCalculationOptionsStaticCalculationOptions describes a model value used by the Core model API editor functions.

Model value shape: { dynamic?: false; bindings?: TBindings; calculate: ExpressionReference | StaticCallback<TBindings, TResult>; name: string; publish?: boolean; unit?: string; owner?: EntityReference | LookupReference<EntityReference>; dependsOn?: readonly (CashflowReference | CalculationProjectionReference<unknown> | CalculationReference<unknown>)[]; readsAccountsFrom?: readonly AccountReference[]; schedule?: ScheduleReference; phase?: "period" | "periodEnd"; resultType?: CalculationResultType; inactiveValue?: unknown; resolveAccounts?: (context: Readonly<{ readonly owner?: EntityReference; readonly accounts: readonly ModelAccountDefinition[]; }>) => readonly AccountReference[] }

deccf.StaticCallbackStaticCallback describes a model value used by the Core model API editor functions.

Model value shape: (values: BindingValues<TBindings>, context: StaticCalculationContext) => TResult

deccf.StaticCashflowOptionsStaticCashflowOptions describes a model value used by the Core model API editor functions.

Model value shape: { dynamic?: false; bindings?: TBindings; active?: StaticCallback<TBindings, boolean>; amount?: StaticBookingAmount<TBindings>; bookings?: readonly StaticBookingRow<TBindings>[]; name?: string; owner?: EntityReference | LookupReference<EntityReference>; agreement?: AgreementReference; direction?: CashflowDirection; category?: CategoryReference; currency?: Currency; schedule?: ScheduleReference; debit?: AccountReference | LookupReference<AccountReference>; credit?: AccountReference | LookupReference<AccountReference>; compileBookings?: CompileCashflowBookings; resolveAccounts?: ResolveCashflowAccounts; … 9 more fields }

deccf.TableToSieOptionsTableToSieOptions describes a model value used by the Core model API editor functions.

Model value shape: { dynamicAccounts?: boolean; personalAccounts?: boolean; businessAccounts?: boolean; splitResAndUb?: boolean; dynamicPeriods?: boolean; fileDrop?: boolean; domain?: NumericDomain; newItem?: string | Readonly<{ generate: "uuid"; }>; required?: boolean; visible?: InputVisibility; ui?: Readonly<InputUIOptions> }

deccf.TextMetricFunctionTextMetricFunction describes a model value used by the Core model API editor functions.

Model value shape: (context: CalculationContext) => string | undefined

deccf.ThresholdAnalysisOptionsThresholdAnalysisOptions describes a model value used by the Core model API editor functions.

Model value shape: { select?: "minimum" | "maximum"; tolerance?: AnalysisNumber; maxIterations?: AnalysisNumber; compare?: (candidate: number, baseline: CalculationContext) => number | Money | undefined; input: InputReference<number>; from: AnalysisNumber; to: AnalysisNumber; atLeast?: AnalysisNumber; atMost?: AnalysisNumber; unit?: string; metric: string; changes?: readonly AnalysisChange[]; label?: string }

deccf.TimeContextTimeContext describes a model value used by the Core model API editor functions.

Model value shape: { index: number; date: DateString; calendar: Calendar; periodsPerYear: number; daysInPeriod: number; phase: string }

deccf.TimelineTimeline describes a model value used by the Core model API editor functions.

Model value shape: { kind: "timeline"; calendar: Calendar; from: DateString | DerivedReference | InputReference<DateString>; count: number | DerivedReference; projection: number }

deccf.TimelineOptionsTimelineOptions describes a model value used by the Core model API editor functions.

Model value shape: { from: DateString | DerivedReference | InputReference<DateString>; count: number | DerivedReference; projection?: number }

deccf.TransferOptionsTransferOptions describes a model value used by the Core model API editor functions.

Model value shape: { name?: string; from: AccountReference | EntityReference | RepeatOutputProjection<AccountReference | EntityReference> | LookupReference<AccountReference | EntityReference>; to: AccountReference | EntityReference | RepeatOutputProjection<AccountReference | EntityReference> | LookupReference<AccountReference | EntityReference>; amount: number | Money | CashflowReference | CalculationProjectionReference<unknown> | ExpressionReference | CalculationReference<unknown> | InputReference<number | Money> | LookupReference<number | Money | CalculationProjectionReference<unknown> | CalculationReference<unknown> | InputReference<number | Money>> | InputProjectionReference<number | Money>; schedule: ScheduleReference; posting?: TransferPostingPolicy; dependsOn?: readonly (CashflowReference | CalculationProjectionReference<unknown> | CalculationReference<unknown>)[] }

deccf.TransferOutputsTransferOutputs describes a model value used by the Core model API editor functions.

Model value shape: { readonly sent: CalculationReference; readonly received: CalculationReference; readonly net: CalculationReference; }

deccf.TransferPostingPolicyTransferPostingPolicy describes a model value used by the Core model API editor functions.

Model value shape: { kind: "transfer-posting-policy"; resolve: (endpoints: { readonly from: EntityReference | AccountReference | LookupReference<EntityReference | AccountReference> | RepeatOutputProjection<EntityReference | AccountReference>; readonly to: EntityReference | AccountReference | LookupReference<EntityReference | AccountReference> | RepeatOutputProjection<EntityReference | AccountReference>; }) => Readonly<{ fromCash: AccountReference; toCash: AccountReference; fromOffset: AccountReference; toOffset: AccountReference; }> }

deccf.TriggerReferenceTriggerReference describes a model value used by the Core model API editor functions.

Model value shape: Reference<"trigger">

deccf.TriggerSourceTriggerSource describes a model value used by the Core model API editor functions.

Model value shape: { flow: CashflowReference; name: string; trigger?: string; amount: number; currency: string; date: DateString; period: number }

deccf.UncertaintyChartOptionsUncertaintyChartOptions describes a model value used by the Core model API editor functions.

Model value shape: { source?: PresentationStandardSeriesSource; metrics?: readonly { readonly metric: PresentationMetricSelector; readonly label: string; }[]; percentiles?: readonly number[]; successMetric?: PresentationMetricSelector; summaryScenario?: string | number | readonly (string | number)[]; maxScenarios?: number; overflowPercentiles?: readonly number[]; finalOutcome?: "curves" | "scenarioMedian"; showValues?: boolean; period?: "monthly" | "months" | "years" | "yearly"; percentile?: number; xAxis?: { readonly kind: "date" | "year" | "age"; readonly currentAge?: number | PresentationInputSelector<number>; readonly startDate?: DateString; }; years?: PresentationInputNumberList; range?: { readonly from?: PresentationInputNumberExpression; readonly to?: PresentationInputNumberExpression; }; ages?: PresentationInputNumberList | PresentationInputRowsSelection; date?: string; … 5 more fields }

Swedish Income Tax module

Select this module in model settings to use its names in the portal model editor (modules["swedish-income-tax"]).

Model editor namePurpose and model value shape
modules["swedish-income-tax"].assessSwedishIncomeTax2025Assess already classified annual SEK bases with the established 2025 tax rules. dateOfBirth is required; taxBases/rules/derive/propertyAssessments use the existing 2025 contract and defaults, but all values must be resolved numbers/booleans; tax bases and assessmentValue also accept same-currency SEK Money. The result contains liability, grossIncome and the complete component map plus explicit country/currency/year/annual-period metadata. It declares no payment, tax card or timeline and performs no extrapolation or conversion to newer rules. Invalid dates, unknown bases/options/rules and unresolved monetary values fail.

(options: SwedishIncomeTax2025AssessmentOptions): SwedishIncomeTax2025Assessment

const assessment = modules['swedish-income-tax'].assessSwedishIncomeTax2025({
  dateOfBirth: '1980-01-01', taxBases: {employment: 480000},
  rules: {municipalRate: .32},
});

return deccf.defineModel({
  currency: deccf.currencies.SEK,
  timeline: deccf.periods.annual({from: '2025-01-01', count: 1}),
  metrics: {annualTax: deccf.metric({value: assessment.liability, unit: 'money'})},
});

modules["swedish-income-tax"].personalTaxpersonalTax provides personal tax in the Swedish Income Tax model editor. Use it when a model needs this operation.

<const Options extends PersonalTaxOptions>(options: Options): PersonalTaxComponent<Options>

const taxes = personalTax({
  person,
  rules,
  taxBases,
  propertyAssessments,
  publishAssessment: true,
  publishProfile: true,
  profileExcludedTaxBases: [B.INK1_8_1, B.INTEREST_ELIGIBLE],
});

modules["swedish-income-tax"].SWEDISH_INCOME_TAX_2025_BASESWEDISH_INCOME_TAX_2025_BASE is a model value for swedish income tax 2025 base in the Swedish Income Tax editor.

Readonly<Record<string, string>>

const { SWEDISH_INCOME_TAX_2025_BASE } = modules["swedish-income-tax"];

modules["swedish-income-tax"].SWEDISH_INCOME_TAX_2025_BASESSWEDISH_INCOME_TAX_2025_BASES is a model value for swedish income tax 2025 bases in the Swedish Income Tax editor.

readonly string[]

const { SWEDISH_INCOME_TAX_2025_BASES } = modules["swedish-income-tax"];

modules["swedish-income-tax"].SWEDISH_INCOME_TAX_2025_COMPONENTSSWEDISH_INCOME_TAX_2025_COMPONENTS is a model value for swedish income tax 2025 components in the Swedish Income Tax editor.

readonly string[]

const { SWEDISH_INCOME_TAX_2025_COMPONENTS } = modules["swedish-income-tax"];

modules["swedish-income-tax"].SWEDISH_INCOME_TAX_2025_PERSONAL_ACCOUNT_MAPPINGSSWEDISH_INCOME_TAX_2025_PERSONAL_ACCOUNT_MAPPINGS is a model value for swedish income tax 2025 personal account mappings in the Swedish Income Tax editor.

readonly SwedishIncomeTax2025PersonalAccountMapping[]

const { SWEDISH_INCOME_TAX_2025_PERSONAL_ACCOUNT_MAPPINGS } = modules["swedish-income-tax"];

modules["swedish-income-tax"].SWEDISH_INCOME_TAX_SETTLEMENT_DELAY_DAYSSWEDISH_INCOME_TAX_SETTLEMENT_DELAY_DAYS is a model value for swedish income tax settlement delay days in the Swedish Income Tax editor.

150

const { SWEDISH_INCOME_TAX_SETTLEMENT_DELAY_DAYS } = modules["swedish-income-tax"];

modules["swedish-income-tax"].swedishIncomeTaxswedishIncomeTax provides swedish income tax in the Swedish Income Tax model editor. Use it when a model needs this operation.

(options: SwedishIncomeTaxOptions): CashflowReference

const { cashflow, currencies, defineModel, entity, input, periods, schedule } = deccf;

const { personalAccountPlan, stdaccount } = modules.accountplan;

const { swedishIncomeTax, swedishIncomeTaxSettlement, swedishPreliminaryIncomeTax } = modules["swedish-income-tax"];

const anna = entity.party({ attributes: { dateOfBirth: "1990-05-21" } });

const salaryGrowth = input.rate(0.03);

const yearEnd = schedule.yearEnd();

const cash = stdaccount({ owner: anna, code: "assets.cash.bank", initial: 25_000 });

const salaryAccount = stdaccount({ owner: anna, code: "income.employment.salary" });

const salary = cashflow({
  dynamic:true,
  schedule: schedule.monthly({ from: "2026-01", to: "2028-12" }),
  debit: cash,
  credit: salaryAccount,
  amount: (ctx) => 50_000 * Math.pow(1 + ctx.get(salaryGrowth), Math.floor(ctx.time.index / 12)),
});

const preliminaryTax = swedishPreliminaryIncomeTax({ person: anna });

const tax = swedishIncomeTax({ person: anna });

const taxSettlement = swedishIncomeTaxSettlement(tax);

const closing = personalAccountPlan.bookClosing({ owner: anna, schedule: yearEnd, dependsOn: [tax] });

return defineModel({
  currency: currencies.SEK,
  // The extra five periods show the final settlement for tax year 2028 in May 2029.
  timeline: periods.monthly({ from: "2026-01", count: 41 }),
  preconditions: { salaryGrowth },
  entities: { anna },
  flows: { salary, preliminaryTax, tax, taxSettlement, closing },
});

modules["swedish-income-tax"].swedishIncomeTaxSettlementswedishIncomeTaxSettlement provides swedish income tax settlement in the Swedish Income Tax model editor. Use it when a model needs this operation.

(assessment: CashflowReference): CashflowReference

const { cashflow, currencies, defineModel, entity, input, periods, schedule } = deccf;

const { personalAccountPlan, stdaccount } = modules.accountplan;

const { swedishIncomeTax, swedishIncomeTaxSettlement, swedishPreliminaryIncomeTax } = modules["swedish-income-tax"];

const anna = entity.party({ attributes: { dateOfBirth: "1990-05-21" } });

const salaryGrowth = input.rate(0.03);

const yearEnd = schedule.yearEnd();

const cash = stdaccount({ owner: anna, code: "assets.cash.bank", initial: 25_000 });

const salaryAccount = stdaccount({ owner: anna, code: "income.employment.salary" });

const salary = cashflow({
  dynamic:true,
  schedule: schedule.monthly({ from: "2026-01", to: "2028-12" }),
  debit: cash,
  credit: salaryAccount,
  amount: (ctx) => 50_000 * Math.pow(1 + ctx.get(salaryGrowth), Math.floor(ctx.time.index / 12)),
});

const preliminaryTax = swedishPreliminaryIncomeTax({ person: anna });

const tax = swedishIncomeTax({ person: anna });

const taxSettlement = swedishIncomeTaxSettlement(tax);

const closing = personalAccountPlan.bookClosing({ owner: anna, schedule: yearEnd, dependsOn: [tax] });

return defineModel({
  currency: currencies.SEK,
  // The extra five periods show the final settlement for tax year 2028 in May 2029.
  timeline: periods.monthly({ from: "2026-01", count: 41 }),
  preconditions: { salaryGrowth },
  entities: { anna },
  flows: { salary, preliminaryTax, tax, taxSettlement, closing },
});

modules["swedish-income-tax"].swedishPreliminaryIncomeTaxswedishPreliminaryIncomeTax provides swedish preliminary income tax in the Swedish Income Tax model editor. Use it when a model needs this operation.

(options: SwedishPreliminaryIncomeTaxOptions): CashflowReference

const taxes = personalTax({
  person,
  preliminaryBasis: "current-period",
  preliminaryBuffer: 0,
});

const preliminary = swedishPreliminaryIncomeTax({
  person,
  basis: "current-period",
  monthlyBuffer: 0,
});

modules["swedish-income-tax"].swedishPropertyAssessments2025Keyed assessment records using explicit January 1 ownership, accepted by all tax wrappers.

(options: SwedishPropertyAssessments2025Options): CalculationReference

const { swedishPropertyAssessments2025 } = modules["swedish-income-tax"];

modules["swedish-income-tax"].swedishPropertyCharges2025Gross annual SEK Money charges by preserved property ID; unkeyed bases remain unallocated.

(options: SwedishPropertyCharges2025Options): CalculationReference

const { swedishPropertyCharges2025 } = modules["swedish-income-tax"];

modules["swedish-income-tax"].PersonalTaxComponentPersonalTaxComponent describes a model value used by the Swedish Income Tax editor functions.

Model value shape: Omit<ComponentReference<PersonalTaxOutputs>, "outputs"> & { readonly outputs: PersonalTaxOutputs & TaxPublicationOutput<"publishAssessment" extends keyof Options ? Options["publishAssessment"] : false, "assessmentDetail"> & TaxPublicationOutput<"publishProfile" extends keyof Options ? Options["publishProfile"] : false, "projectedProfile">; }

modules["swedish-income-tax"].PersonalTaxOptionsPersonalTaxOptions describes a model value used by the Swedish Income Tax editor functions.

Model value shape: { preliminaryBasis?: SwedishPreliminaryTaxBasis; preliminaryBuffer?: AmountSource; preliminaryTableNumber?: NumberSource; preliminaryTableColumn?: NumberSource; publishAssessment?: boolean; publishProfile?: boolean; profileExcludedTaxBases?: readonly string[]; person: EntityReference | RepeatOutputProjection<EntityReference>; preliminarySchedule?: ScheduleReference; assessmentSchedule?: ScheduleReference; settlementDelayDays?: number; cashAccount?: AccountReference | RepeatOutputProjection<AccountReference>; settlementSchedule?: ScheduleReference; rules?: SwedishIncomeTax2025Rules; taxBases?: Readonly<Record<string, SwedishTaxBasisSource>>; propertyAssessments?: InputReference<deccf.InputValue> | InputProjectionReference<deccf.InputValue> | ExpressionReference | CalculationReference<unknown> | CalculationProjectionReference | readonly SwedishPropertyAssessment[] }

modules["swedish-income-tax"].PersonalTaxOutputsPersonalTaxOutputs describes a model value used by the Swedish Income Tax editor functions.

Model value shape: Readonly<{ preliminary: CashflowReference; assessment: CashflowReference; settlement: CashflowReference; }>

modules["swedish-income-tax"].SwedishIncomeTax2025AssessmentSwedishIncomeTax2025Assessment describes a model value used by the Swedish Income Tax editor functions.

Model value shape: { country: "SE"; currency: "SEK"; ruleYear: 2025; period: "annual"; liability: number; grossIncome: number; components: Readonly<Record<string, number>> }

modules["swedish-income-tax"].SwedishIncomeTax2025AssessmentOptionsSwedishIncomeTax2025AssessmentOptions describes a model value used by the Swedish Income Tax editor functions.

Model value shape: { dateOfBirth: string; taxBases?: Readonly<Record<string, number | Money>>; rules?: Readonly<{ residentMonths?: number; municipalRate?: number; stateThreshold?: number; burialFeeRate?: number; communityMember?: boolean; communityFeeRate?: number; }>; derive?: Readonly<{ pensionFee?: boolean; specialPayrollTax?: boolean; yieldTax?: boolean; expansionFundTax?: boolean; }>; propertyAssessments?: readonly Readonly<{ assessmentValue: number | Money; buildingYear: number; valueYear?: number; ownershipShare?: number; }>[] }

modules["swedish-income-tax"].SwedishIncomeTax2025PersonalAccountMappingSwedishIncomeTax2025PersonalAccountMapping describes a model value used by the Swedish Income Tax editor functions.

Model value shape: { accountCode: string; category: deccf.CategoryReference; basis: string; direction: "inflow" | "outflow"; multiplier: number }

modules["swedish-income-tax"].SwedishIncomeTax2025RulesSwedishIncomeTax2025Rules describes a model value used by the Swedish Income Tax editor functions.

Model value shape: { residentMonths?: NumberSource; municipalRate?: NumberSource; stateThreshold?: NumberSource; burialFeeRate?: NumberSource; communityMember?: SwedishTaxBooleanSource; communityFeeRate?: NumberSource }

modules["swedish-income-tax"].SwedishIncomeTaxOptionsSwedishIncomeTaxOptions describes a model value used by the Swedish Income Tax editor functions.

Model value shape: { person: EntityReference | RepeatOutputProjection<EntityReference>; schedule?: ScheduleReference; settlementDelayDays?: number; cashAccount?: AccountReference | RepeatOutputProjection<AccountReference>; rules?: SwedishIncomeTax2025Rules; taxBases?: Readonly<Record<string, SwedishTaxBasisSource>>; propertyAssessments?: InputReference<deccf.InputValue> | InputProjectionReference<deccf.InputValue> | ExpressionReference | CalculationReference<unknown> | CalculationProjectionReference | readonly SwedishPropertyAssessment[] }

modules["swedish-income-tax"].SwedishPreliminaryIncomeTaxOptionsSwedishPreliminaryIncomeTaxOptions describes a model value used by the Swedish Income Tax editor functions.

Model value shape: { basis?: SwedishPreliminaryTaxBasis; monthlyBuffer?: AmountSource; tableNumber?: NumberSource; tableColumn?: NumberSource; person: EntityReference | RepeatOutputProjection<EntityReference>; schedule?: ScheduleReference; cashAccount?: AccountReference | RepeatOutputProjection<AccountReference>; rules?: SwedishIncomeTax2025Rules; taxBases?: Readonly<Record<string, SwedishTaxBasisSource>>; propertyAssessments?: InputReference<deccf.InputValue> | InputProjectionReference<deccf.InputValue> | ExpressionReference | CalculationReference<unknown> | CalculationProjectionReference | readonly SwedishPropertyAssessment[] }

modules["swedish-income-tax"].SwedishPreliminaryTaxBasisSwedishPreliminaryTaxBasis describes a model value used by the Swedish Income Tax editor functions.

Model value shape: 'history' | 'current-period'

modules["swedish-income-tax"].SwedishPropertyAssessmentSwedishPropertyAssessment describes a model value used by the Swedish Income Tax editor functions.

Model value shape: { assessmentValue: AmountSource; buildingYear: NumberSource; valueYear?: NumberSource; ownershipShare?: NumberSource }

modules["swedish-income-tax"].SwedishPropertyAssessments2025OptionsSwedishPropertyAssessments2025Options describes a model value used by the Swedish Income Tax editor functions.

Model value shape: { owner?: EntityReference | RepeatOutputProjection<EntityReference>; properties: SwedishPropertyCollectionSource | deccf.LookupReference<SwedishPropertyCollectionSource>; ownershipAtJanuary1: SwedishPropertyCollectionSource | deccf.LookupReference<SwedishPropertyCollectionSource>; people: Readonly<Record<string, EntityReference>> | RepeatOutputProjection<EntityReference>; personId: string | ExpressionReference | InputReference<string> | InputProjectionReference<string>; publishDetail?: boolean; fields?: Partial<Readonly<Record<"id" | "name" | "assessmentValue" | "buildingYear" | "valueYear", string>>>; ownershipFields?: Partial<Readonly<Record<"propertyId" | "personId" | "share", string>>> }

modules["swedish-income-tax"].SwedishPropertyChargeProfile2025SwedishPropertyChargeProfile2025 describes a model value used by the Swedish Income Tax editor functions.

Model value shape: { ruleYear: 2025; taxYear?: number; dateOfBirth: string; rules?: Readonly<{ residentMonths?: number; municipalRate?: number; stateThreshold?: number; burialFeeRate?: number; communityMember?: boolean; communityFeeRate?: number; }>; taxBases?: Readonly<Record<string, number>>; propertyAssessments: Readonly<Record<string, { readonly assessmentValue: number; readonly buildingYear: number; readonly valueYear?: number; readonly ownershipShare?: number; }>> }

modules["swedish-income-tax"].SwedishPropertyCharges2025OptionsSwedishPropertyCharges2025Options describes a model value used by the Swedish Income Tax editor functions.

Model value shape: { owner?: EntityReference | RepeatOutputProjection<EntityReference>; profiles: InputReference<deccf.InputValue> | InputProjectionReference<deccf.InputValue> | ExpressionReference | CalculationReference<unknown> | CalculationProjectionReference | Readonly<Record<string, CalculationReference<unknown> | CalculationProjectionReference | SwedishPropertyChargeProfile2025>> | RepeatOutputProjection<CalculationReference<unknown> | CalculationProjectionReference> }

modules["swedish-income-tax"].SwedishPropertyCollectionSourceSwedishPropertyCollectionSource describes a model value used by the Swedish Income Tax editor functions.

Model value shape: readonly Readonly<Record<string, unknown>>[] | deccf.InputReference<readonly deccf.InputValue[]> | deccf.InputProjectionReference<readonly deccf.InputValue[]>

modules["swedish-income-tax"].SwedishTaxBasisSourceAn explicit year basis is added to the mapped account-read bases at calculation time.

Model value shape: AmountSource | Readonly<{ amount: AmountSource; period?: 'annual' | 'monthly' }>

modules["swedish-income-tax"].SwedishTaxBooleanSourceSwedishTaxBooleanSource describes a model value used by the Swedish Income Tax editor functions.

Model value shape: boolean | InputReference<boolean> | InputProjectionReference<boolean> | CalculationReference | CalculationProjectionReference | ExpressionReference

modules["swedish-income-tax"].SwedishTaxSourceOptionsSwedishTaxSourceOptions describes a model value used by the Swedish Income Tax editor functions.

Model value shape: { rules?: SwedishIncomeTax2025Rules; taxBases?: Readonly<Record<string, SwedishTaxBasisSource>>; propertyAssessments?: InputReference<deccf.InputValue> | InputProjectionReference<deccf.InputValue> | ExpressionReference | CalculationReference<unknown> | CalculationProjectionReference | readonly SwedishPropertyAssessment[] }

modules["swedish-income-tax"].TaxPublicationOutputTaxPublicationOutput describes a model value used by the Swedish Income Tax editor functions.

Model value shape: true extends Flag ? boolean extends Flag ? Readonly<Partial<Record<Name, CalculationReference>>> : Readonly<Record<Name, CalculationReference>> : {}

Danish Income Tax module

Select this module in model settings to use its names in the portal model editor (modules["danish-income-tax"]).

Model editor namePurpose and model value shape
modules["danish-income-tax"].assessDanishIncomeTaxPure national assessment with the same required profile, defaults, units and result as danishIncomeTax. Uses explicit 2026/full-year data; no timeline, owner, references, callbacks or payments. Amount Money must use the local currency. birthYear/rates/children must be plain finite numbers. Unknown options and every unsupported native profile fail explicitly.

(options: DanishIncomeTaxAssessmentOptions): DanishIncomeTaxResult

const assessment = modules['danish-income-tax'].assessDanishIncomeTax({ruleYear: 2026, residency: 'full-year', birthYear: 1980, salary: 200000, municipalRate: .25, civilStatus: 'single', seniorSupplement: false, singleParentSupplement: false});

return deccf.defineModel({
  currency: deccf.currencies.DKK,
  timeline: deccf.periods.monthly({from: '2026-05', count: 1}),
  metrics: {assessedAmount: deccf.metric({value: assessment.incomeTax, unit: 'money', annualAggregation: 'last'})},
});

modules["danish-income-tax"].DANISH_INCOME_TAX_2026Official 2026 rule parameters and primary-source provenance, reviewed 2026-10-16.

IncomeTaxRuleSet

const { DANISH_INCOME_TAX_2026 } = modules["danish-income-tax"];

modules["danish-income-tax"].danishIncomeTaxDeclares published Danish income tax for a single, full-year resident in 2026, in DKK. Register the reference in model calculations; .project("incomeTax") selects total tax. Requires ruleYear:2026, residency:"full-year", birthYear, municipalRate, civilStatus:"single", seniorSupplement:false and singleParentSupplement:false. birthYear can be an input. salary is the year's AM-assessable salary after ATP and without pension-premium deductions; pension is ordinary taxable pension income. netCapitalIncome is positive net capital income; shareIncome is separately classified share income. Amounts and churchRate default to 0. municipalRate/churchRate are actual local rates as decimals, not percentages. The AM contribution, progressive national taxes, local taxes, employment/job deductions, tax value of the personal allowance and both tax ceilings are calculated. components are before credits; incomeTax is after credits. totalBurden counts the AM contribution once; socialContributions is 0. All result amounts are DKK. prepaidTax defaults to 0; balanceAfterPrepayments compares tax with the actual annual prepayment. owner/name are optional. Final authority rounding, tax cards, payment dates and interest are not calculated; roundingScope is before-payment-rounding. The timeline and currency must be 2026 and DKK. Negative capital bases, spouses, special supplements, pension-premium deductions and salary profiles for people born before 1966 are rejected. Unknown options and unsupported regimes are rejected without fallback rules.

(options: DanishIncomeTaxOptions): CalculationReference

const { currencies, defineModel, input, money, periods } = deccf;

const { danishIncomeTax } = modules["danish-income-tax"];

const salary = input.money(200000, currencies.DKK, {ui:{label:"Annual salary subject to AM contribution"}});

const tax = danishIncomeTax({
  ruleYear:2026, residency:"full-year", birthYear:1986,
  civilStatus:"single", seniorSupplement:false, singleParentSupplement:false,
  salary, municipalRate:0.25, churchRate:0, prepaidTax:0,
});

return defineModel({currency:currencies.DKK,
  timeline:periods.monthly({from:"2026-01",count:1}),preconditions:{salary},
  calculations:{tax},metrics:{tax:ctx=>money(ctx.get(tax).incomeTax,currencies.DKK)}});

modules["danish-income-tax"].DanishIncomeTaxAssessmentOptionsResolved native options: numeric sources are numbers (or same-currency Money for amounts); no references/callbacks.

Model value shape: { readonly [K in keyof Omit<DanishIncomeTaxOptions, 'owner' | 'name'>]: Exclude<DanishIncomeTaxOptions[K], undefined> extends TaxNumberSource ? number : Exclude<DanishIncomeTaxOptions[K], undefined> extends TaxAmountSource ? number | Money : DanishIncomeTaxOptions[K]; }

modules["danish-income-tax"].DanishIncomeTaxOptionsDanishIncomeTaxOptions describes a model value used by the Danish Income Tax editor functions.

Model value shape: { ruleYear: 2026; residency: "full-year"; birthYear: TaxNumberSource; name?: string; owner?: EntityReference; prepaidTax?: TaxAmountSource; salary?: TaxAmountSource; pension?: TaxAmountSource; netCapitalIncome?: TaxAmountSource; shareIncome?: TaxAmountSource; municipalRate: TaxNumberSource; churchRate?: TaxNumberSource; civilStatus: "single"; seniorSupplement: false; singleParentSupplement: false }

modules["danish-income-tax"].DanishIncomeTaxResultDanishIncomeTaxResult describes a model value used by the Danish Income Tax editor functions.

Model value shape: { country: string; currency: "DKK"; ruleYear: 2026; period: "monthly" | "annual"; roundingScope: string; bases: Readonly<Record<string, number>>; deductions: Readonly<Record<string, number>>; credits: Readonly<Record<string, number>>; components: Readonly<Record<string, number>>; incomeTax: number; socialContributions: number; totalBurden: number; prepaidTax: number; balanceAfterPrepayments: number }

modules["danish-income-tax"].IncomeTaxRuleSetIncomeTaxRuleSet describes a model value used by the Danish Income Tax editor functions.

Model value shape: { country: string; currency: "DKK"; ruleYear: 2026; version: string; validFrom: "2026-01-01"; validTo: "2026-12-31"; reviewedOn: string; parameters: Readonly<Record<string, Readonly<{ source: Readonly<{ url: string; ruleYear: 2026; reviewedOn: string; }>; } & Record<string, unknown>>>> }

modules["danish-income-tax"].TaxAmountSourceTaxAmountSource describes a model value used by the Danish Income Tax editor functions.

Model value shape: number | Money | InputReference<number | Money> | InputProjectionReference<number | Money> | CalculationReference | CalculationProjectionReference | ExpressionReference | ((context:CalculationContext)=>number | Money)

modules["danish-income-tax"].TaxNumberSourceTaxNumberSource describes a model value used by the Danish Income Tax editor functions.

Model value shape: number | InputReference<number> | InputProjectionReference<number> | CalculationReference | CalculationProjectionReference | ExpressionReference | ((context:CalculationContext)=>number)

Finnish Income Tax module

Select this module in model settings to use its names in the portal model editor (modules["finnish-income-tax"]).

Model editor namePurpose and model value shape
modules["finnish-income-tax"].assessFinnishIncomeTaxPure national assessment with the same required profile, defaults, units and result as finnishIncomeTax. Uses explicit 2026/full-year data; no timeline, owner, references, callbacks or payments. Amount Money must use the local currency. birthYear/rates/children must be plain finite numbers. Unknown options and every unsupported native profile fail explicitly.

(options: FinnishIncomeTaxAssessmentOptions): FinnishIncomeTaxResult

const assessment = modules['finnish-income-tax'].assessFinnishIncomeTax({ruleYear: 2026, residency: 'full-year', birthYear: 1980, salary: 60000, municipalRate: .053, territory: 'mainland'});

return deccf.defineModel({
  currency: deccf.currencies.EUR,
  timeline: deccf.periods.monthly({from: '2026-05', count: 1}),
  metrics: {assessedAmount: deccf.metric({value: assessment.incomeTax, unit: 'money', annualAggregation: 'last'})},
});

modules["finnish-income-tax"].FINNISH_INCOME_TAX_2026Official 2026 rule parameters and primary-source provenance, reviewed 2026-10-16.

IncomeTaxRuleSet

const { FINNISH_INCOME_TAX_2026 } = modules["finnish-income-tax"];

modules["finnish-income-tax"].finnishIncomeTaxDeclares published Finnish income tax in EUR for a full-year mainland resident in 2026. Register the reference in calculations; .project("incomeTax") returns total tax. Requires ruleYear:2026, residency:"full-year", birthYear, territory:"mainland" and municipalRate. birthYear, amounts, rates and children can be named inputs or references. Choose one annual income class: salary, pension or ordinary taxable benefits; each defaults to 0. churchRate is 0 for non-members. taxableCapitalIncome is an already classified net basis, not interest subject to separate withholding. productionExpenses can provide actual employment expenses above the EUR 750 standard allowance, capped at salary. children defaults to 0 and singleParent to false. National, municipal, church and public-health taxes, daily allowance contribution, broadcasting tax, additional pension-income tax, capital tax and automatic deductions/credits are calculated. The earned-income credit reduces national tax first and then other applicable taxes proportionally. incomeTax follows the official cent-rounded tax components; socialContributions shows employee pension and unemployment insurance separately; totalBurden counts them once. All result amounts are EUR; roundingScope is euro-cents. prepaidTax defaults to 0; balanceAfterPrepayments is tax minus actual prepayments. owner/name are optional. The timeline and currency must be 2026 and EUR. Salary profiles are supported for people born from 1962 through 2007. Mixed income classes, Åland, capital deficits, expense losses, special deductions and unknown options are rejected. Tax cards, interest, due dates and bank payments are not created.

(options: FinnishIncomeTaxOptions): CalculationReference

const { currencies, defineModel, input, money, periods } = deccf;

const { finnishIncomeTax } = modules["finnish-income-tax"];

const salary = input.money(30000, currencies.EUR, {ui:{label:"Annual salary"}});

const tax = finnishIncomeTax({
  ruleYear:2026, residency:"full-year", birthYear:1986, territory:"mainland",
  salary, municipalRate:0.053, churchRate:0.01, prepaidTax:0,
});

return defineModel({currency:currencies.EUR,
  timeline:periods.monthly({from:"2026-01",count:1}),preconditions:{salary},
  calculations:{tax},metrics:{tax:ctx=>money(ctx.get(tax).incomeTax,currencies.EUR)}});

modules["finnish-income-tax"].FinnishIncomeTaxAssessmentOptionsResolved native options: numeric sources are numbers (or same-currency Money for amounts); no references/callbacks.

Model value shape: { readonly [K in keyof Omit<FinnishIncomeTaxOptions, 'owner' | 'name'>]: Exclude<FinnishIncomeTaxOptions[K], undefined> extends TaxNumberSource ? number : Exclude<FinnishIncomeTaxOptions[K], undefined> extends TaxAmountSource ? number | Money : FinnishIncomeTaxOptions[K]; }

modules["finnish-income-tax"].FinnishIncomeTaxOptionsFinnishIncomeTaxOptions describes a model value used by the Finnish Income Tax editor functions.

Model value shape: { ruleYear: 2026; residency: "full-year"; birthYear: TaxNumberSource; name?: string; owner?: EntityReference; prepaidTax?: TaxAmountSource; salary?: TaxAmountSource; pension?: TaxAmountSource; benefits?: TaxAmountSource; taxableCapitalIncome?: TaxAmountSource; productionExpenses?: TaxAmountSource; municipalRate: TaxNumberSource; churchRate?: TaxNumberSource; children?: TaxNumberSource; singleParent?: boolean; territory: "mainland" }

modules["finnish-income-tax"].FinnishIncomeTaxResultFinnishIncomeTaxResult describes a model value used by the Finnish Income Tax editor functions.

Model value shape: { country: string; currency: "EUR"; ruleYear: 2026; period: "monthly" | "annual"; roundingScope: string; bases: Readonly<Record<string, number>>; deductions: Readonly<Record<string, number>>; credits: Readonly<Record<string, number>>; components: Readonly<Record<string, number>>; incomeTax: number; socialContributions: number; totalBurden: number; prepaidTax: number; balanceAfterPrepayments: number }

modules["finnish-income-tax"].IncomeTaxRuleSetIncomeTaxRuleSet describes a model value used by the Finnish Income Tax editor functions.

Model value shape: { country: string; currency: "EUR"; ruleYear: 2026; version: string; validFrom: "2026-01-01"; validTo: "2026-12-31"; reviewedOn: string; parameters: Readonly<Record<string, Readonly<{ source: Readonly<{ url: string; ruleYear: 2026; reviewedOn: string; }>; } & Record<string, unknown>>>> }

modules["finnish-income-tax"].TaxAmountSourceTaxAmountSource describes a model value used by the Finnish Income Tax editor functions.

Model value shape: number | Money | InputReference<number | Money> | InputProjectionReference<number | Money> | CalculationReference | CalculationProjectionReference | ExpressionReference | ((context:CalculationContext)=>number | Money)

modules["finnish-income-tax"].TaxNumberSourceTaxNumberSource describes a model value used by the Finnish Income Tax editor functions.

Model value shape: number | InputReference<number> | InputProjectionReference<number> | CalculationReference | CalculationProjectionReference | ExpressionReference | ((context:CalculationContext)=>number)

Icelandic Income Tax module

Select this module in model settings to use its names in the portal model editor (modules["icelandic-income-tax"]).

Model editor namePurpose and model value shape
modules["icelandic-income-tax"].assessIcelandicIncomeTaxPure national assessment with the same required profile, defaults, units and result as icelandicIncomeTax. Uses explicit 2026/full-year data; no timeline, owner, references, callbacks or payments. Amount Money must use the local currency. birthYear/rates/children must be plain finite numbers. Unknown options and every unsupported native profile fail explicitly.

(options: IcelandicIncomeTaxAssessmentOptions): IcelandicIncomeTaxResult

const assessment = modules['icelandic-income-tax'].assessIcelandicIncomeTax({ruleYear: 2026, residency: 'full-year', birthYear: 1980, salary: 12000000, municipalRate: .1494, period: 'annual'});

return deccf.defineModel({
  currency: deccf.currencies.ISK,
  timeline: deccf.periods.monthly({from: '2026-05', count: 1}),
  metrics: {assessedAmount: deccf.metric({value: assessment.incomeTax, unit: 'money', annualAggregation: 'last'})},
});

modules["icelandic-income-tax"].ICELANDIC_INCOME_TAX_2026Official 2026 rule parameters and primary-source provenance, reviewed 2026-10-16.

IncomeTaxRuleSet

const { ICELANDIC_INCOME_TAX_2026 } = modules["icelandic-income-tax"];

modules["icelandic-income-tax"].icelandicIncomeTaxDeclares published Icelandic income tax in ISK for an adult full-year resident in 2026. Register the reference in calculations; .project("incomeTax") returns total tax. Requires ruleYear:2026, residency:"full-year", birthYear and period:"annual" or "monthly". Annual mode requires the actual municipalRate. Monthly mode uses the official 14.94% average withholding rate and rejects municipalRate. Amounts are annual totals or current- month totals across all payers, respectively. salary/pension default to 0. Actual pensionContribution/additionalPensionContribution default to 0 and may each be at most 4% of salary. The annual credit is ISK 869898; the monthly availablePersonalCredit defaults to ISK 72492. Supply the substantiated monthly credit available; unused earlier credit is not assumed. qualifiedCapitalIncome shares an annual allowance for qualifying interest/listed shares; otherCapitalIncome is another classified capital basis. Both default to 0 and are rejected in monthly mode. Unused personal credit is not offset against capital tax in 2026. incomeTax is national/local/capital tax after credits; socialContributions contains the pension payments entered and totalBurden counts them once. All result amounts are ISK. prepaidTax defaults to 0; balanceAfterPrepayments is calculated tax minus actual prepayments for the same period. owner/name are optional. Amounts, rates and birthYear support inputs. roundingScope is before-payment-rounding: final payment rounding, interest, collection dates, spouse transfers, flat fees and special regimes are unsupported. The timeline and currency must be 2026 and ISK. Unknown options are rejected without fallback rules.

(options: IcelandicIncomeTaxOptions): CalculationReference

const { currencies, defineModel, input, money, periods } = deccf;

const { icelandicIncomeTax } = modules["icelandic-income-tax"];

const salary = input.money(6000000, currencies.ISK, {ui:{label:"Annual salary"}});

const tax = icelandicIncomeTax({
  ruleYear:2026, residency:"full-year", birthYear:1986, period:"annual",
  salary, pensionContribution:240000, municipalRate:0.1494, prepaidTax:0,
});

return defineModel({currency:currencies.ISK,
  timeline:periods.monthly({from:"2026-01",count:1}),preconditions:{salary},
  calculations:{tax},metrics:{tax:ctx=>money(ctx.get(tax).incomeTax,currencies.ISK)}});

modules["icelandic-income-tax"].IcelandicIncomeTaxAssessmentOptionsResolved native options: numeric sources are numbers (or same-currency Money for amounts); no references/callbacks.

Model value shape: { readonly [K in keyof Omit<IcelandicIncomeTaxOptions, 'owner' | 'name'>]: Exclude<IcelandicIncomeTaxOptions[K], undefined> extends TaxNumberSource ? number : Exclude<IcelandicIncomeTaxOptions[K], undefined> extends TaxAmountSource ? number | Money : IcelandicIncomeTaxOptions[K]; }

modules["icelandic-income-tax"].IcelandicIncomeTaxOptionsIcelandicIncomeTaxOptions describes a model value used by the Icelandic Income Tax editor functions.

Model value shape: { ruleYear: 2026; residency: "full-year"; birthYear: TaxNumberSource; name?: string; owner?: EntityReference; prepaidTax?: TaxAmountSource; salary?: TaxAmountSource; pension?: TaxAmountSource; pensionContribution?: TaxAmountSource; additionalPensionContribution?: TaxAmountSource; qualifiedCapitalIncome?: TaxAmountSource; otherCapitalIncome?: TaxAmountSource; municipalRate?: TaxNumberSource; availablePersonalCredit?: TaxAmountSource; period: "monthly" | "annual" }

modules["icelandic-income-tax"].IcelandicIncomeTaxResultIcelandicIncomeTaxResult describes a model value used by the Icelandic Income Tax editor functions.

Model value shape: { country: string; currency: "ISK"; ruleYear: 2026; period: "monthly" | "annual"; roundingScope: string; bases: Readonly<Record<string, number>>; deductions: Readonly<Record<string, number>>; credits: Readonly<Record<string, number>>; components: Readonly<Record<string, number>>; incomeTax: number; socialContributions: number; totalBurden: number; prepaidTax: number; balanceAfterPrepayments: number }

modules["icelandic-income-tax"].IncomeTaxRuleSetIncomeTaxRuleSet describes a model value used by the Icelandic Income Tax editor functions.

Model value shape: { country: string; currency: "ISK"; ruleYear: 2026; version: string; validFrom: "2026-01-01"; validTo: "2026-12-31"; reviewedOn: string; parameters: Readonly<Record<string, Readonly<{ source: Readonly<{ url: string; ruleYear: 2026; reviewedOn: string; }>; } & Record<string, unknown>>>> }

modules["icelandic-income-tax"].TaxAmountSourceTaxAmountSource describes a model value used by the Icelandic Income Tax editor functions.

Model value shape: number | Money | InputReference<number | Money> | InputProjectionReference<number | Money> | CalculationReference | CalculationProjectionReference | ExpressionReference | ((context:CalculationContext)=>number | Money)

modules["icelandic-income-tax"].TaxNumberSourceTaxNumberSource describes a model value used by the Icelandic Income Tax editor functions.

Model value shape: number | InputReference<number> | InputProjectionReference<number> | CalculationReference | CalculationProjectionReference | ExpressionReference | ((context:CalculationContext)=>number)

Norwegian Income Tax module

Select this module in model settings to use its names in the portal model editor (modules["norwegian-income-tax"]).

Model editor namePurpose and model value shape
modules["norwegian-income-tax"].assessNorwegianIncomeTaxPure national assessment with the same required profile, defaults, units and result as norwegianIncomeTax. Uses explicit 2026/full-year data; no timeline, owner, references, callbacks or payments. Amount Money must use the local currency. birthYear/rates/children must be plain finite numbers. Unknown options and every unsupported native profile fail explicitly.

(options: NorwegianIncomeTaxAssessmentOptions): NorwegianIncomeTaxResult

const assessment = modules['norwegian-income-tax'].assessNorwegianIncomeTax({ruleYear: 2026, residency: 'full-year', birthYear: 1980, salary: 600000, region: 'ordinary', youngWorkerTrialSelected: false});

return deccf.defineModel({
  currency: deccf.currencies.NOK,
  timeline: deccf.periods.monthly({from: '2026-05', count: 1}),
  metrics: {assessedAmount: deccf.metric({value: assessment.incomeTax, unit: 'money', annualAggregation: 'last'})},
});

modules["norwegian-income-tax"].NORWEGIAN_INCOME_TAX_2026Official 2026 rule parameters and primary-source provenance, reviewed 2026-10-16.

IncomeTaxRuleSet

const { NORWEGIAN_INCOME_TAX_2026 } = modules["norwegian-income-tax"];

modules["norwegian-income-tax"].norwegianIncomeTaxDeclares published Norwegian income tax in NOK for an ordinary adult full-year employee in 2026. Register the reference in calculations; .project("incomeTax") returns total tax. Requires ruleYear:2026, residency:"full-year", birthYear and region:"ordinary" or "intervention-zone". The zone requires substantiated residence in Finnmark/North-Troms. salary is ordinary taxable annual salary, capitalIncome is classified ordinary capital income, and interestExpenses is actual deductible interest; each defaults to 0. These amounts and birthYear support inputs. The minimum standard deduction, personal allowance, zone deduction/rate, progressive bracket tax and social-security contribution threshold and phase-in are calculated. Capital does not affect bracket tax on personal income. incomeTax includes the social-security contribution; totalBurden counts it once and socialContributions is 0. Result bases/deductions/credits/components are NOK. prepaidTax defaults to 0; balanceAfterPrepayments compares it with actual prepayments for that year. owner/name are optional. People born from 1991 through 2006 must provide the actual trial selection notice as youngWorkerTrialSelected:false. Selected trial participants, pensions, salary profiles for people born before 1960, PAYE, capital losses, the special uplift/shielding of share income, wealth tax and special deductions are unsupported. roundingScope is before-payment-rounding. Final authority rounding, tax cards, due dates, interest and bank payments are not calculated. The timeline and currency must be 2026 and NOK. Unknown options and regimes are rejected without Swedish or other fallback rules.

(options: NorwegianIncomeTaxOptions): CalculationReference

const { currencies, defineModel, input, money, periods } = deccf;

const { norwegianIncomeTax } = modules["norwegian-income-tax"];

const salary = input.money(600000, currencies.NOK, {ui:{label:"Annual salary"}});

const tax = norwegianIncomeTax({
  ruleYear:2026, residency:"full-year", birthYear:1986, region:"ordinary",
  salary, capitalIncome:0, interestExpenses:0, prepaidTax:0,
});

return defineModel({currency:currencies.NOK,
  timeline:periods.monthly({from:"2026-01",count:1}),preconditions:{salary},
  calculations:{tax},metrics:{tax:ctx=>money(ctx.get(tax).incomeTax,currencies.NOK)}});

modules["norwegian-income-tax"].IncomeTaxRuleSetIncomeTaxRuleSet describes a model value used by the Norwegian Income Tax editor functions.

Model value shape: { country: string; currency: "NOK"; ruleYear: 2026; version: string; validFrom: "2026-01-01"; validTo: "2026-12-31"; reviewedOn: string; parameters: Readonly<Record<string, Readonly<{ source: Readonly<{ url: string; ruleYear: 2026; reviewedOn: string; }>; } & Record<string, unknown>>>> }

modules["norwegian-income-tax"].NorwegianIncomeTaxAssessmentOptionsResolved native options: numeric sources are numbers (or same-currency Money for amounts); no references/callbacks.

Model value shape: { readonly [K in keyof Omit<NorwegianIncomeTaxOptions, 'owner' | 'name'>]: Exclude<NorwegianIncomeTaxOptions[K], undefined> extends TaxNumberSource ? number : Exclude<NorwegianIncomeTaxOptions[K], undefined> extends TaxAmountSource ? number | Money : NorwegianIncomeTaxOptions[K]; }

modules["norwegian-income-tax"].NorwegianIncomeTaxOptionsNorwegianIncomeTaxOptions describes a model value used by the Norwegian Income Tax editor functions.

Model value shape: { ruleYear: 2026; residency: "full-year"; birthYear: TaxNumberSource; name?: string; owner?: EntityReference; prepaidTax?: TaxAmountSource; salary?: TaxAmountSource; capitalIncome?: TaxAmountSource; interestExpenses?: TaxAmountSource; region: "ordinary" | "intervention-zone"; youngWorkerTrialSelected?: false }

modules["norwegian-income-tax"].NorwegianIncomeTaxResultNorwegianIncomeTaxResult describes a model value used by the Norwegian Income Tax editor functions.

Model value shape: { country: string; currency: "NOK"; ruleYear: 2026; period: "monthly" | "annual"; roundingScope: string; bases: Readonly<Record<string, number>>; deductions: Readonly<Record<string, number>>; credits: Readonly<Record<string, number>>; components: Readonly<Record<string, number>>; incomeTax: number; socialContributions: number; totalBurden: number; prepaidTax: number; balanceAfterPrepayments: number }

modules["norwegian-income-tax"].TaxAmountSourceTaxAmountSource describes a model value used by the Norwegian Income Tax editor functions.

Model value shape: number | Money | InputReference<number | Money> | InputProjectionReference<number | Money> | CalculationReference | CalculationProjectionReference | ExpressionReference | ((context:CalculationContext)=>number | Money)

modules["norwegian-income-tax"].TaxNumberSourceTaxNumberSource describes a model value used by the Norwegian Income Tax editor functions.

Model value shape: number | InputReference<number> | InputProjectionReference<number> | CalculationReference | CalculationProjectionReference | ExpressionReference | ((context:CalculationContext)=>number)

Swedish Amortization module

Select this module in model settings to use its names in the portal model editor (modules["swedish-amortization"]).

Model editor namePurpose and model value shape
modules["swedish-amortization"].swedishAmortizationOrdinary statutory amortization, including interest, for use as loanPlan.payment.

(options: { readonly value: LoanAmountSource; readonly principalBase: LoanAmountSource; readonly debtForLtv?: LoanAmountSource; readonly version?: "2026-04-01"; }): Formula<LoanContext>

const { swedishMortgagePolicy, swedishAmortization } = modules['swedish-amortization'];

const { loanPlan } = modules.loans;

const policy = swedishMortgagePolicy({ purpose: 'purchase', version: '2026-04-01' });

const loan = loanPlan({
  owner,
  openingBalance: principal,
  annualRate: mortgageRate,
  payment: swedishAmortization({ value: regulatoryValue, principalBase: highestCredit }),
});

modules["swedish-amortization"].swedishMortgagePolicyswedishMortgagePolicy provides swedish mortgage policy in the Swedish Amortization model editor. Use it when a model needs this operation.

(options?: SwedishMortgagePolicyOptions): SwedishMortgagePolicy

const { swedishMortgagePolicy, swedishAmortization } = modules['swedish-amortization'];

const { loanPlan } = modules.loans;

const policy = swedishMortgagePolicy({ purpose: 'purchase', version: '2026-04-01' });

const loan = loanPlan({
  owner,
  openingBalance: principal,
  annualRate: mortgageRate,
  payment: swedishAmortization({ value: regulatoryValue, principalBase: highestCredit }),
});

modules["swedish-amortization"].SwedishMortgagePolicySwedishMortgagePolicy describes a model value used by the Swedish Amortization editor functions.

Model value shape: { version: "2026-04-01"; purpose: "purchase" | "extension"; maxLtv: number; tiers: readonly Readonly<{ above: number; annualShare: number; }>[] }

modules["swedish-amortization"].SwedishMortgagePolicyOptionsSwedishMortgagePolicyOptions describes a model value used by the Swedish Amortization editor functions.

Model value shape: { version?: "2026-04-01"; purpose?: "purchase" | "extension"; maxLtv?: number; tiers?: readonly Readonly<{ above: number; annualShare: number; }>[] }

Accountplan module

Select this module in model settings to use its names in the portal model editor (modules.accountplan).

Model editor namePurpose and model value shape
modules.accountplan.businessAccountPlanbusinessAccountPlan is a model value for business account plan in the Accountplan editor.

AccountPlan

const { businessAccountPlan } = modules.accountplan;

modules.accountplan.businessAccountPlan.bookClosingbusinessAccountPlan.bookClosing provides book closing in the Accountplan model editor. Use it when a model needs this operation.

(options: BookClosingOptions): CashflowReference

const { cashflow, currencies, defineModel, entity, periods, schedule } = deccf;

const { businessAccountPlan, stdaccount } = modules.accountplan;

const company = entity.asset();

const bank = stdaccount({ code: "1930", owner: company, initial: 100_000 });

const shareCapital = stdaccount({ code: "2081", owner: company, initial: -100_000 });

const revenueAccount = stdaccount({ code: "3000", owner: company });

const taxExpenseAccount = stdaccount({ code: "8910", owner: company });

const revenue = cashflow({ owner: company, debit: bank, credit: revenueAccount, schedule: schedule.monthly(), amount: 20_000 });

const taxPayment = cashflow({
  dynamic:true,
  owner: company,
  dependsOn: [revenue],
  debit: taxExpenseAccount,
  credit: bank,
  schedule: schedule.monthly(),
  amount: (ctx) => ctx.get(revenue).amount * 0.2,
});

const taxExpense = taxPayment;

const yearEnd = businessAccountPlan.bookClosing({
  owner: company,
  schedule: schedule.annual({ from: "2027-12", to: "2030-12" }),
  dependsOn: [taxExpense],
});

const model = defineModel({
  name: "business-book-closing",
  currency: currencies.SEK,
  timeline: periods.monthly({ from: "2026-01", count: 60 }),
  entities: { company },
  accounts: { shareCapital },
  flows: { revenue, taxPayment, yearEnd },
});

return model;

modules.accountplan.businessAccountPlan.categoryForAccepts an account code, a category node code, or a full category path.

(codeOrPath: string): CategoryReference

const { categoryFor } = modules.accountplan.businessAccountPlan;

modules.accountplan.businessAccountPlan.categoryForClassbusinessAccountPlan.categoryForClass provides category for class in the Accountplan model editor. Use it when a model needs this operation.

(code: string): CategoryReference

const { categoryForClass } = modules.accountplan.businessAccountPlan;

modules.accountplan.businessAccountPlan.categoryForGroupbusinessAccountPlan.categoryForGroup provides category for group in the Accountplan model editor. Use it when a model needs this operation.

(code: string): CategoryReference

const { categoryForGroup } = modules.accountplan.businessAccountPlan;

modules.accountplan.businessAccountPlan.findForAccountReturn the plan entry associated with an account carrying that entry's category.

(reference: AccountReference): AccountPlanAccount | undefined

const { findForAccount } = modules.accountplan.businessAccountPlan;

modules.accountplan.businessAccountPlan.fiscalYearForResolve the fiscal year containing a date for the owner entity.

(owner: EntityReference, date: DateString): Readonly<{ start: DateString; end: DateString; startYear: number; endYear: number; label: string; }>

const { currencies, defineModel, entity, periods } = deccf;

const { businessAccountPlan, stdaccount } = modules.accountplan;

const company = entity.asset({ attributes: { fiscalYearStartMonth: 7 } });

const fiscalYear = businessAccountPlan.fiscalYearFor(company, "2026-09");

const bank = stdaccount({ code: "1930", owner: company, initial: 50_000 });

const model = defineModel({
  name: "company-fiscal-year",
  currency: currencies.SEK,
  timeline: periods.monthly({ from: "2026-07", count: 12 }),
  entities: { company },
  accounts: { bank },
});

console.log(fiscalYear);

return model;

modules.accountplan.businessAccountPlan.fiscalYearStartMonthRead fiscalYearStartMonth from the owner entity attributes; defaults to January.

(owner: EntityReference): number

const { fiscalYearStartMonth } = modules.accountplan.businessAccountPlan;

modules.accountplan.businessAccountPlan.getbusinessAccountPlan.get provides get in the Accountplan model editor. Use it when a model needs this operation.

(code: string): AccountPlanAccount

const { get } = modules.accountplan.businessAccountPlan;

modules.accountplan.businessAccountPlan.ownerForAccountReturn the account owner's entity reference.

(reference: AccountReference): EntityReference | undefined

const { ownerForAccount } = modules.accountplan.businessAccountPlan;

modules.accountplan.businessAccountPlan.roleAccountsFind actual owner-specific accounts that match a role's labels or account-code prefixes.

(options: { readonly owner: EntityReference; readonly role: string; readonly accounts: readonly (AccountReference | ModelAccountDefinition)[]; readonly overrides?: readonly AccountReference[]; }): readonly AccountRoleAccount[]

const { roleAccounts } = modules.accountplan.businessAccountPlan;

modules.accountplan.defineAccountPlandefineAccountPlan creates or declares define account plan in the Accountplan model editor. Use it when a model needs this operation.

(options: { readonly id: string; readonly name: string; readonly version: string; readonly source?: string; readonly accounts: readonly AccountPlanAccountDefinition[]; readonly categoryDefinitions?: readonly AccountPlanCategoryDefinition[]; readonly roles?: Readonly<Record<string, AccountPlanRoleDefinition>>; readonly closing?: Readonly<{ readonly retainedEarningsCode: string; }>; }): AccountPlan

const { defineAccountPlan } = modules.accountplan;

modules.accountplan.InputInput is a model value for input in the Accountplan editor.

Readonly<InputFactory & { stdAccountValues: typeof stdAccountValues; }>

const { Input } = modules.accountplan;

modules.accountplan.Input.aspectInput.aspect provides aspect in the Accountplan model editor. Use it when a model needs this operation.

<TFields extends InputObjectFields>(fields: TFields, options?: ObjectConstraintOptions): ObjectInputReference<TFields>

const { aspect } = modules.accountplan.Input;

modules.accountplan.Input.booleanInput.boolean provides boolean in the Accountplan model editor. Use it when a model needs this operation.

(value: boolean, options?: BooleanInputOptions): InputReference<boolean>

const { boolean } = modules.accountplan.Input;

modules.accountplan.Input.boolenAlias of boolean, retained for existing models.

(value: boolean, options?: BooleanInputOptions): InputReference<boolean>

const { boolen } = modules.accountplan.Input;

modules.accountplan.Input.curveInput.curve provides curve in the Accountplan model editor. Use it when a model needs this operation.

(points: readonly { readonly date: DateString; readonly value: number; }[], options?: CurveOptions): InputReference<number>

const { curve } = modules.accountplan.Input;

modules.accountplan.Input.dateInput.date provides date in the Accountplan model editor. Use it when a model needs this operation.

(value: DateString | null, options?: InputOptions<DateString | null>): InputReference<DateString | null>

const { date } = modules.accountplan.Input;

modules.accountplan.Input.decimalInput.decimal provides decimal in the Accountplan model editor. Use it when a model needs this operation.

(value: number, options?: InputOptions<number>): InputReference<number>

const { decimal } = modules.accountplan.Input;

modules.accountplan.Input.domainInput.domain provides domain in the Accountplan model editor. Use it when a model needs this operation.

<TFields extends InputObjectFields>(fields: TFields, options?: ObjectConstraintOptions): DomainInputReference<TFields>

const { domain } = modules.accountplan.Input;

modules.accountplan.Input.enumInput.enum provides enum in the Accountplan model editor. Use it when a model needs this operation.

<T extends string>(value: T, options: EnumInputOptions<T>): InputReference<T>

const { enum } = modules.accountplan.Input;

modules.accountplan.Input.familyRoleInput.familyRole provides family role in the Accountplan model editor. Use it when a model needs this operation.

(value: "adult" | "child", options?: InputOptions<"adult" | "child">): InputReference<"adult" | "child">

const { familyRole } = modules.accountplan.Input;

modules.accountplan.Input.fractionInput.fraction provides fraction in the Accountplan model editor. Use it when a model needs this operation.

(value: number, options?: InputOptions<number>): InputReference<number>

const { fraction } = modules.accountplan.Input;

modules.accountplan.Input.groupInput.group provides group in the Accountplan model editor. Use it when a model needs this operation.

<TFields extends InputObjectFields>(fields: TFields, options?: ObjectConstraintOptions): ObjectInputReference<TFields>

const { group } = modules.accountplan.Input;

modules.accountplan.Input.groupsCreates one connected group per matching keyed source row. Returns an ordinary object-array input with hidden, protected id and name fields. Source rename/reorder preserves surviving nested editable data by source key; additions use field defaults and removals remove the associated group. id/name are reserved in fields. Source must be an ordinary object array; label must name a source string field and filters must match scalar types. Example: deccf.input.groups(businesses, {projects:deccf.input.objectArray(projectRows)}, {where:{active:true}}).

<TSource extends InputObjectFields, TFields extends InputObjectFields>(source: ObjectArrayInputReference<TSource>, fields: TFields & { readonly id?: never; readonly name?: never; }, options?: GroupsInputOptions<TSource, TFields>): ObjectArrayInputReference<TFields & { readonly id: InputReference<string>; readonly name: InputReference<string>; }>

const { groups } = modules.accountplan.Input;

modules.accountplan.Input.hiddenInput.hidden provides hidden in the Accountplan model editor. Use it when a model needs this operation.

<T extends InputReference<InputValue>>(value: T, options?: InputMetadataOptions): T
<T extends InputValue>(value: InputProjectionReference<T> | T, options?: InputMetadataOptions): InputReference<T>

const { hidden } = modules.accountplan.Input;

modules.accountplan.Input.idInput.id provides id in the Accountplan model editor. Use it when a model needs this operation.

(value: string, options?: InputOptions<string>): InputReference<string>
(options: Readonly<{ generate: "uuid"; }>, metadata?: Omit<InputOptions<string>, "newItem">): InputReference<string | undefined>

const { id } = modules.accountplan.Input;

modules.accountplan.Input.integerInput.integer provides integer in the Accountplan model editor. Use it when a model needs this operation.

(value: number, options?: InputOptions<number>): InputReference<number>

const { integer } = modules.accountplan.Input;

modules.accountplan.Input.lockableInput.lockable provides lockable in the Accountplan model editor. Use it when a model needs this operation.

<T extends InputReference<InputValue>>(locked: boolean, value: T, options?: InputMetadataOptions): LockableInputReference<T>

const { lockable } = modules.accountplan.Input;

modules.accountplan.Input.logNormalInput.logNormal provides log normal in the Accountplan model editor. Use it when a model needs this operation.

(parameters: { readonly mu: number; readonly sigma: number; readonly clip?: NumericDomain; }, options?: DistributionOptions): InputReference<number>

const { logNormal } = modules.accountplan.Input;

modules.accountplan.Input.moneyInput.money provides money in the Accountplan model editor. Use it when a model needs this operation.

(amount: number, denomination: Currency, options?: InputOptions<Money>): InputReference<Money>

const { money } = modules.accountplan.Input;

modules.accountplan.Input.normalInput.normal provides normal in the Accountplan model editor. Use it when a model needs this operation.

(parameters: { readonly mean: number; readonly stdev: number; readonly clip?: NumericDomain; }, options?: DistributionOptions): InputReference<number>

const { normal } = modules.accountplan.Input;

modules.accountplan.Input.objectInput.object provides object in the Accountplan model editor. Use it when a model needs this operation.

<const TVariants extends ObjectVariantCatalogue>(variants: TVariants, options?: ObjectVariantOptions): ObjectVariantInputReference<TVariants>
<TFields extends InputObjectFields>(fields: TFields, options?: ObjectInputOptions): ObjectInputReference<TFields>

const { object } = modules.accountplan.Input;

modules.accountplan.Input.ObjectInput.Object provides object in the Accountplan model editor. Use it when a model needs this operation.

<const TVariants extends ObjectVariantCatalogue>(variants: TVariants, options?: ObjectVariantOptions): ObjectVariantInputReference<TVariants>
<TFields extends InputObjectFields>(fields: TFields, options?: ObjectInputOptions): ObjectInputReference<TFields>

const { Object } = modules.accountplan.Input;

modules.accountplan.Input.objectArrayCreates mixed rows from object variants. `type` is `manyOfAnyChangeable`, `manyOfAny` or `anyOf`. Example: `deccf.input.objectArray([isk, vp], {type: "manyOfAnyChangeable", title: "Sparande"})`.

<const TVariants extends ObjectVariantCatalogue, TKey extends string = "id">(variants: TVariants, options: ObjectVariantArrayOptions<TKey>): ObjectVariantArrayInputReference<TVariants, TKey>
<TFields extends InputObjectFields>(rows: readonly TFields[] | readonly ObjectInputReference<TFields>[], options?: ObjectArrayOptions<TFields>): ObjectArrayInputReference<TFields>

const { objectArray } = modules.accountplan.Input;

modules.accountplan.Input.rateInput.rate provides rate in the Accountplan model editor. Use it when a model needs this operation.

(value: number, options?: InputOptions<number>): InputReference<number>

const { rate } = modules.accountplan.Input;

modules.accountplan.Input.readonlyInput.readonly provides readonly in the Accountplan model editor. Use it when a model needs this operation.

<T extends InputReference<InputValue>>(value: T, options?: InputMetadataOptions): T
<T extends InputValue>(value: InputProjectionReference<T> | T, options?: InputMetadataOptions): InputReference<T>

const { readonly } = modules.accountplan.Input;

modules.accountplan.Input.readOnlyInput.readOnly provides read only in the Accountplan model editor. Use it when a model needs this operation.

<T extends InputReference<InputValue>>(value: T, options?: InputMetadataOptions): T
<T extends InputValue>(value: InputProjectionReference<T> | T, options?: InputMetadataOptions): InputReference<T>

const { readOnly } = modules.accountplan.Input;

modules.accountplan.Input.sectionInput.section provides section in the Accountplan model editor. Use it when a model needs this operation.

<TFields extends InputObjectFields>(fields: TFields, options?: ObjectConstraintOptions): ObjectInputReference<TFields>

const { section } = modules.accountplan.Input;

modules.accountplan.Input.sniAn empty value asks domain methods to infer the industry from account history.

(mainGroup?: string, options?: InputOptions<string>): InputReference<string>

const { sni } = modules.accountplan.Input;

modules.accountplan.Input.stdAccountValuesInput.stdAccountValues provides std account values in the Accountplan model editor. Use it when a model needs this operation.

(options: StdAccountValuesOptions, ...rows: readonly (readonly (string | number)[])[]): StdAccountValuesReference

const { currencies, defineModel, entity, periods } = deccf;

const { Input } = modules.accountplan;

const company = entity.asset();

const accounts = Input.stdAccountValues({
  owner: company,
  dynamicAccounts: true,
  dynamicPeriods: true,
  monthStartEnd: [7, 6],
  ui: { label: "Historical account balances" },
},
  ["years", 2023, 2024, 2025],
  ["10", 50000, 51000, 52000],
  ["11", 60000, 61000, 62000],
);

return defineModel({
  currency: currencies.SEK,
  timeline: periods.monthly({ from: "2022-07", count: 36 }),
  entities: { company },
  preconditions: { accounts },
});

modules.accountplan.Input.strInput.str provides str in the Accountplan model editor. Use it when a model needs this operation.

(value?: string, options?: InputOptions<string>): InputReference<string>

const { str } = modules.accountplan.Input;

modules.accountplan.Input.tableToSieInput.tableToSie provides table to sie in the Accountplan model editor. Use it when a model needs this operation.

(defaultContent?: string, options?: TableToSieOptions): InputReference<string>

const { tableToSie } = modules.accountplan.Input;

modules.accountplan.Input.textfileInput.textfile provides textfile in the Accountplan model editor. Use it when a model needs this operation.

(defaultText?: string, options?: InputOptions<string>): InputReference<string>

const { textfile } = modules.accountplan.Input;

modules.accountplan.Input.triangularInput.triangular provides triangular in the Accountplan model editor. Use it when a model needs this operation.

(parameters: { readonly min: number; readonly mode: number; readonly max: number; readonly clip?: NumericDomain; }, options?: DistributionOptions): InputReference<number>

const { triangular } = modules.accountplan.Input;

modules.accountplan.Input.uniformInput.uniform provides uniform in the Accountplan model editor. Use it when a model needs this operation.

(parameters: { readonly min: number; readonly max: number; readonly clip?: NumericDomain; }, options?: DistributionOptions): InputReference<number>

const { uniform } = modules.accountplan.Input;

modules.accountplan.loanAccountingBook loan movements without duplicating the cashflows generated by loanPlan. Opening balances remain explicit.

(options: LoanAccountingOptions): ComponentReference

const accounting = loanAccounting({
  owner: household,
  loan,
  debtAccount: mortgageDebt,
  interestAccount: mortgageInterest,
  cashAccount: bank,
});

modules.accountplan.paymentAttributionpaymentAttribution provides payment attribution in the Accountplan model editor. Use it when a model needs this operation.

(options: modules.accountplan.PaymentAttributionOptions): CalculationReference

const { paymentAttribution } = modules.accountplan;

modules.accountplan.personalAccountPlanpersonalAccountPlan is a model value for personal account plan in the Accountplan editor.

PersonalAccountPlan

const { personalAccountPlan } = modules.accountplan;

modules.accountplan.personalAccountPlan.bookClosingpersonalAccountPlan.bookClosing provides book closing in the Accountplan model editor. Use it when a model needs this operation.

(options: BookClosingOptions): CashflowReference

const { bookClosing } = modules.accountplan.personalAccountPlan;

modules.accountplan.personalAccountPlan.categoryForAccepts an account code, a category node code, or a full category path.

(codeOrPath: string): CategoryReference

const { categoryFor } = modules.accountplan.personalAccountPlan;

modules.accountplan.personalAccountPlan.categoryForClasspersonalAccountPlan.categoryForClass provides category for class in the Accountplan model editor. Use it when a model needs this operation.

(code: string): CategoryReference

const { categoryForClass } = modules.accountplan.personalAccountPlan;

modules.accountplan.personalAccountPlan.categoryForGrouppersonalAccountPlan.categoryForGroup provides category for group in the Accountplan model editor. Use it when a model needs this operation.

(code: string): CategoryReference

const { categoryForGroup } = modules.accountplan.personalAccountPlan;

modules.accountplan.personalAccountPlan.findForAccountReturn the plan entry associated with an account carrying that entry's category.

(reference: AccountReference): AccountPlanAccount | undefined

const { findForAccount } = modules.accountplan.personalAccountPlan;

modules.accountplan.personalAccountPlan.fiscalYearForResolve the fiscal year containing a date for the owner entity.

(owner: EntityReference, date: DateString): Readonly<{ start: DateString; end: DateString; startYear: number; endYear: number; label: string; }>

const { fiscalYearFor } = modules.accountplan.personalAccountPlan;

modules.accountplan.personalAccountPlan.fiscalYearStartMonthRead fiscalYearStartMonth from the owner entity attributes; defaults to January.

(owner: EntityReference): number

const { fiscalYearStartMonth } = modules.accountplan.personalAccountPlan;

modules.accountplan.personalAccountPlan.getpersonalAccountPlan.get provides get in the Accountplan model editor. Use it when a model needs this operation.

(code: string): AccountPlanAccount

const { account, currencies, defineModel, entity, periods } = deccf;

const { personalAccountPlan } = modules.accountplan;

const anna = entity.party();

const netWorthDefinition = personalAccountPlan.get("equity.retained_earnings");

const netWorth = account({
  owner: anna,
  type: netWorthDefinition.type,
  category: netWorthDefinition.category,
  initial: -250_000, // credit balance under the engine's sign convention
});

const cash = account({
  owner: anna,
  type: "asset",
  category: personalAccountPlan.get("assets.cash.bank").category,
  initial: 250_000,
});

const model = defineModel({
  name: "anna-net-worth-opening-balance",
  currency: currencies.SEK,
  timeline: periods.annual({ from: "2026-01", count: 1 }),
  entities: { anna },
  accounts: { cash, netWorth },
});

return model;

modules.accountplan.personalAccountPlan.incomepersonalAccountPlan.income provides income in the Accountplan model editor. Use it when a model needs this operation.

(options: { readonly owner: EntityReference | RepeatOutputProjection<EntityReference> | deccf.LookupReference<EntityReference>; readonly code?: string; readonly amount: number | Money | InputReference<number | Money> | InputProjectionReference<number | Money> | ExpressionReference | CalculationReference | CalculationProjectionReference | RepeatOutputProjection<CalculationReference | CalculationProjectionReference>; readonly schedule: ScheduleReference; readonly dependsOn?: readonly (CashflowReference | CalculationReference | CalculationProjectionReference)[]; readonly readsAccountsFrom?: readonly AccountReference[]; }): CashflowReference

const { income } = modules.accountplan.personalAccountPlan;

modules.accountplan.personalAccountPlan.ownerContributionpersonalAccountPlan.ownerContribution provides owner contribution in the Accountplan model editor. Use it when a model needs this operation.

(): deccf.TransferPostingPolicy

const { household, inputs } = modules.household;

const { personalAccountPlan } = modules.accountplan;

const input = Object.freeze({ ...deccf.input, ...inputs });

const members = input.objectArray([
  { id: input.id("anna"), name: input.str("Anna"), role: input.familyRole("adult"), dateOfBirth: input.date("1990-05-21"), salary: input.money(46_000, deccf.currencies.SEK) },
  { id: input.id("erik"), name: input.str("Erik"), role: input.familyRole("adult"), dateOfBirth: input.date("1989-08-12"), salary: input.money(39_000, deccf.currencies.SEK) },
]);

const family = household();

const member = deccf.entity.party({
  owner: family,
  attributes: { id: members.item.data.id, role: members.item.data.role, dateOfBirth: members.item.data.dateOfBirth },
});

const people = deccf.repeat(members, deccf.component({ entities: { member }, outputs: { person: member } }));

const adults = people.where({ role: "adult" });

const budget = household.householdBudget({
  household: family,
  members: people.outputs.person,
  funding: {
    from: adults.outputs.person,
    method: deccf.proportional({ weights: adults.column("salary") }),
    posting: personalAccountPlan.ownerContribution(),
  },
});

const model = deccf.defineModel({
  name: "Proportional household budget",
  currency: deccf.currencies.SEK,
  timeline: deccf.periods.monthly({ from: "2026-01", count: 24 }),
  preconditions: { members },
  entities: { family },
  components: { people, budget },
});

return model;

modules.accountplan.personalAccountPlan.ownerForAccountReturn the account owner's entity reference.

(reference: AccountReference): EntityReference | undefined

const { ownerForAccount } = modules.accountplan.personalAccountPlan;

modules.accountplan.personalAccountPlan.roleAccountsFind actual owner-specific accounts that match a role's labels or account-code prefixes.

(options: { readonly owner: EntityReference; readonly role: string; readonly accounts: readonly (AccountReference | ModelAccountDefinition)[]; readonly overrides?: readonly AccountReference[]; }): readonly AccountRoleAccount[]

const { roleAccounts } = modules.accountplan.personalAccountPlan;

modules.accountplan.reallocateExpensereallocateExpense({from,to,code,amount,weights?,schedule?}) returns a posting component; register it. from is an entity; to an entity, array, keyed entity map or repeated entity output. Recipients differ from source/each other. code is a personal-plan expense code; amount is nonnegative in model currency. Moves recognition through owners' net worth without payment. weights defaults equal: scalar sources for one recipient, ordered arrays, exact-key source maps, repeated numeric columns or numeric calculation output maps. Maps exactly match recipient IDs; register source repeats. Weights are finite/nonnegative; positive expense needs positive total, zero permits all-zero weights. schedule defaults monthly. Invalid entities/codes/shape/currency/amounts/weights reject. Tax eligibility stays separate; existing maps/arrays retain meaning.

(options: ReallocateExpenseOptions): ComponentReference

// Select Housing, Account plans and Swedish family benefits.
const members = deccf.input.objectArray([
  {id: deccf.input.id("anna"), share: deccf.input.fraction(0.5)},
  {id: deccf.input.id("erik"), share: deccf.input.fraction(0.5)},
]);
const owner = deccf.entity.party();
const cash = deccf.account({owner, type: "asset", initial: 10000});
const person = deccf.entity.party({owner});
const people = deccf.repeat(members, deccf.component({entities: {person}, outputs: {person}}));
const weight = deccf.calculation({
  name: "Ownership weight", calculate: deccf.expr.multiply(members.item.data.share, 1),
});
const allocations = deccf.repeat(members, deccf.component({calculations: {weight}, outputs: {weight}}));
const expense = modules.accountplan.reallocateExpense({
  from: owner, to: people.outputs.person, code: "expense.housing.mortgage_interest",
  amount: 100, weights: allocations.outputs.weight,
});
const benefits = modules["swedish-family-benefits"].swedishFamilyBenefits({
  owner, recipients: people.outputs.person, profile: "household",
  children: [{id: "kim", parent: "shared", benefitKind: "child", householdShare: "half"}],
});
const home = modules.housing.propertyPlan({
  owner, cashAccount: cash, openingValue: 1000000, monthlyCost: 100,
  ownership: {owners: people.outputs.person, weights: allocations.outputs.weight},
  paymentShares: {owners: people.outputs.person, weights: allocations.outputs.weight},
});
return deccf.defineModel({
  currency: deccf.currencies.SEK,
  timeline: deccf.periods.monthly({from: "2026-01", count: 1}),
  preconditions: {members}, entities: {owner}, accounts: {cash},
  components: {people, allocations, expense, benefits: benefits.component, home: home.component},
});
 

modules.accountplan.revalueAssetAdjust an asset's opening carrying value to the specified nonnegative target.

(options: RevalueAssetOptions): CashflowReference

const { revalueAsset } = modules.accountplan;

modules.accountplan.stdaccountCreate or reuse an account from the Business or Personal plan. Company, person, and household entities may be owners. All codes, including numeric-looking codes, are strings.

(options: StandardAccountOptions): AccountReference

const person = deccf.entity.party();

const netSalary = modules.accountplan.stdaccount({
  owner:person, code:'income.employment.net_salary',
});

const living = modules.accountplan.stdaccount({
  owner:person, code:'expense.other',
});

return deccf.defineModel({
  currency:deccf.currencies.SEK,
  timeline:deccf.periods.annual({from:'2026-01', count:1}),
  entities:{person}, accounts:{netSalary,living},
});

modules.accountplan.stdAccountValuesstdAccountValues provides std account values in the Accountplan model editor. Use it when a model needs this operation.

(options: StdAccountValuesOptions, ...rows: readonly (readonly (string | number)[])[]): StdAccountValuesReference

const { currencies, defineModel, entity, periods } = deccf;

const { Input } = modules.accountplan;

const company = entity.asset();

const accounts = Input.stdAccountValues({
  owner: company,
  dynamicAccounts: true,
  dynamicPeriods: true,
  monthStartEnd: [7, 6],
  ui: { label: "Historical account balances" },
},
  ["years", 2023, 2024, 2025],
  ["10", 50000, 51000, 52000],
  ["11", 60000, 61000, 62000],
);

return defineModel({
  currency: currencies.SEK,
  timeline: periods.monthly({ from: "2022-07", count: 36 }),
  entities: { company },
  preconditions: { accounts },
});

modules.accountplan.AccountingAmountSourceAccountingAmountSource describes a model value used by the Accountplan editor functions.

Model value shape: number | Money | AccountReference | InputReference<number | Money> | InputProjectionReference<number | Money> | ExpressionReference | CalculationReference | CalculationProjectionReference | ((context: deccf.CalculationContext) => number | Money)

modules.accountplan.AccountPlanAccountPlan describes a model value used by the Accountplan editor functions.

Model value shape: { id: string; name: string; version: string; source?: string; accounts: Readonly<Record<string, AccountPlanAccount>>; roles: Readonly<Record<string, AccountPlanRoleDefinition>>; categories: Readonly<Record<string, CategoryReference>>; categoryLabels: Readonly<Record<string, string>>; categoryTree: Readonly<Record<string, AccountPlanCategory>>; get: (code: string) => AccountPlanAccount; findForAccount: (reference: AccountReference) => AccountPlanAccount | undefined; ownerForAccount: (reference: AccountReference) => EntityReference | undefined; roleAccounts: (options: { readonly owner: EntityReference; readonly role: string; readonly accounts: readonly (AccountReference | ModelAccountDefinition)[]; readonly overrides?: readonly AccountReference[]; }) => readonly AccountRoleAccount[]; fiscalYearStartMonth: (owner: EntityReference) => number; fiscalYearFor: (owner: EntityReference, date: DateString) => Readonly<{ start: DateString; end: DateString; startYear: number; endYear: number; label: string; }>; categoryFor: (codeOrPath: string) => CategoryReference; … 4 more fields }

modules.accountplan.AccountPlanAccountAccountPlanAccount describes a model value used by the Accountplan editor functions.

Model value shape: { normalBalance?: NormalBalance; category: CategoryReference; categoryPath: string; label: string; type: AccountPlanType; code: string; accountClass?: string | number; parentCode?: string; notForK2?: boolean; aliases?: readonly string[]; tags?: readonly string[] }

modules.accountplan.AccountPlanAccountDefinitionAccountPlanAccountDefinition describes a model value used by the Accountplan editor functions.

Model value shape: { code: string; label: string; type: AccountPlanType; categoryPath: string; accountClass?: string | number; normalBalance?: NormalBalance; parentCode?: string; notForK2?: boolean; aliases?: readonly string[]; tags?: readonly string[] }

modules.accountplan.AccountPlanCategoryAccountPlanCategory describes a model value used by the Accountplan editor functions.

Model value shape: { parentPath?: string; path: string; label: string; code?: string }

modules.accountplan.AccountPlanCategoryDefinitionAccountPlanCategoryDefinition describes a model value used by the Accountplan editor functions.

Model value shape: { path: string; label: string; code?: string }

modules.accountplan.AccountPlanRoleDefinitionAccountPlanRoleDefinition describes a model value used by the Accountplan editor functions.

Model value shape: { tags?: readonly string[]; prefixes?: readonly string[]; excludePrefixes?: readonly string[] }

modules.accountplan.AccountPlanTypeAccountPlanType describes a model value used by the Accountplan editor functions.

Model value shape: "asset" | "liability" | "equity" | "income" | "expense" | "transfer"

modules.accountplan.AccountRoleAccountAccountRoleAccount describes a model value used by the Accountplan editor functions.

Model value shape: { reference: AccountReference; code?: string; label?: string; type?: AccountPlanType; normalBalance?: NormalBalance; tags: readonly string[]; source: "account-plan" | "account-code" }

modules.accountplan.AccountValuesMatrixOriginal matrix representation retained in saved input values.

Model value shape: readonly (readonly (string | number)[])[]

modules.accountplan.BookClosingOptionsBookClosingOptions describes a model value used by the Accountplan editor functions.

Model value shape: { owner: EntityReference | RepeatOutputProjection<EntityReference> | deccf.LookupReference<EntityReference>; schedule?: ScheduleReference; dependsOn?: readonly (CashflowReference | CalculationReference<unknown> | CalculationProjectionReference)[] }

modules.accountplan.BusinessAccountPlanBusinessAccountPlan describes a model value used by the Accountplan editor functions.

Model value shape: AccountPlan

modules.accountplan.LoanAccountingOptionsLoanAccountingOptions describes a model value used by the Accountplan editor functions.

Model value shape: { owner: EntityReference | RepeatOutputProjection<EntityReference> | deccf.LookupReference<EntityReference>; loan: modules.loans.LoanPlan; debtAccount: AccountReference | deccf.LookupReference<AccountReference>; interestAccount: AccountReference; cashAccount: AccountReference | deccf.LookupReference<AccountReference>; equityAccount?: AccountReference | deccf.LookupReference<AccountReference>; schedule?: ScheduleReference }

modules.accountplan.NormalBalanceNormalBalance describes a model value used by the Accountplan editor functions.

Model value shape: "debit" | "credit"

modules.accountplan.PaymentAttributionOptionsPaymentAttributionOptions describes a model value used by the Accountplan editor functions.

Model value shape: { owner?: EntityReference | deccf.LookupReference<EntityReference>; amount: Money | ExpressionReference | CalculationReference<unknown> | InputReference<Money> | CalculationProjectionReference | RepeatOutputProjection<CalculationReference<unknown> | CalculationProjectionReference> | InputProjectionReference<Money>; recipients: RepeatOutputProjection<EntityReference> | Readonly<Record<string, EntityReference | deccf.LookupReference<EntityReference>>>; weights: CalculationReference<unknown> | CalculationProjectionReference | RepeatOutputProjection<CalculationReference<unknown> | CalculationProjectionReference> | Readonly<Record<string, modules.accountplan.AttributionNumber>> | InputReference<Readonly<Record<string, number>>> | InputProjectionReference<Readonly<Record<string, number>>> | deccf.RepeatColumnReference<number> }

modules.accountplan.PaymentAttributionValuePaymentAttributionValue describes a model value used by the Accountplan editor functions.

Model value shape: { amounts: Readonly<Record<string, Money>>; total: Money }

modules.accountplan.PersonalAccountPlanPersonalAccountPlan describes a model value used by the Accountplan editor functions.

Model value shape: { bookClosing: (options: BookClosingOptions) => CashflowReference; income: (options: { readonly owner: EntityReference | RepeatOutputProjection<EntityReference> | deccf.LookupReference<EntityReference>; readonly code?: string; readonly amount: number | Money | InputReference<number | Money> | InputProjectionReference<number | Money> | ExpressionReference | CalculationReference | CalculationProjectionReference | RepeatOutputProjection<CalculationReference | CalculationProjectionReference>; readonly schedule: ScheduleReference; readonly dependsOn?: readonly (CashflowReference | CalculationReference | CalculationProjectionReference)[]; readonly readsAccountsFrom?: readonly AccountReference[]; }) => CashflowReference; ownerContribution: () => deccf.TransferPostingPolicy; id: string; name: string; version: string; source?: string; accounts: Readonly<Record<string, AccountPlanAccount>>; roles: Readonly<Record<string, AccountPlanRoleDefinition>>; categories: Readonly<Record<string, CategoryReference>>; categoryLabels: Readonly<Record<string, string>>; categoryTree: Readonly<Record<string, AccountPlanCategory>>; get: (code: string) => AccountPlanAccount; findForAccount: (reference: AccountReference) => AccountPlanAccount | undefined; ownerForAccount: (reference: AccountReference) => EntityReference | undefined; roleAccounts: (options: { readonly owner: EntityReference; readonly role: string; readonly accounts: readonly (AccountReference | ModelAccountDefinition)[]; readonly overrides?: readonly AccountReference[]; }) => readonly AccountRoleAccount[]; … 6 more fields }

modules.accountplan.ReallocateExpenseOptionsReallocateExpenseOptions describes a model value used by the Accountplan editor functions.

Model value shape: { from: EntityReference | RepeatOutputProjection<EntityReference>; to: EntityReference | Readonly<Record<string, EntityReference>> | RepeatOutputProjection<EntityReference> | readonly EntityReference[]; code: string; amount: AccountingAmountSource; weights?: deccf.Reference<"repeat-column"> | AccountingAmountSource | InputReference<Readonly<Record<string, deccf.InputValue>>> | InputProjectionReference<Readonly<Record<string, deccf.InputValue>>> | readonly AccountingAmountSource[] | Readonly<Record<string, AccountingAmountSource>> | RepeatOutputProjection<CalculationReference<number>>; schedule?: ScheduleReference }

modules.accountplan.RevalueAssetOptionsRevalueAssetOptions describes a model value used by the Accountplan editor functions.

Model value shape: { account: AccountReference; value: AccountingAmountSource; equityAccount: AccountReference; schedule?: ScheduleReference }

modules.accountplan.StandardAccountOptionsStandardAccountOptions describes a model value used by the Accountplan editor functions.

Model value shape: Pick<AccountOptions, "initial"> & { readonly code: string; readonly owner: EntityReference | RepeatOutputProjection<EntityReference> | deccf.LookupReference<EntityReference>; }

modules.accountplan.StdAccountValuesOptionsStdAccountValuesOptions describes a model value used by the Accountplan editor functions.

Model value shape: { owner: EntityReference; statement?: boolean; dynamicAccounts?: boolean; dynamicPeriods?: boolean; monthStartEnd?: readonly [number, number] | Readonly<{ start: number; end: number; }>; ui?: Readonly<{ label?: string; description?: string; }> }

modules.accountplan.StdAccountValuesReferenceStdAccountValuesReference describes a model value used by the Accountplan editor functions.

Model value shape: readonly AccountReference[] & InputReference<AccountValuesMatrix> & { get(code: string): Readonly<{ get(period: number | string): DerivedReference; readonly amount: DerivedReference }>; }

Business Metrics module

Select this module in model settings to use its names in the portal model editor (modules["business-metrics"]).

Model editor namePurpose and model value shape
modules["business-metrics"].businessMetricDefinitionsbusinessMetricDefinitions is a model value for business metric definitions in the Business Metrics editor.

readonly BusinessMetricDefinition[]

const { businessMetricDefinitions } = modules["business-metrics"];

modules["business-metrics"].BusinessMetricDefinitionBusinessMetricDefinition describes a model value used by the Business Metrics editor functions.

Model value shape: { id: string; name: string; label: string; kind: "number" | "money"; unit: "money" | "percent" | "ratio"; window: "year" | "snapshot" | "two_years"; frequency: number; annualAggregation: "sum" | "last"; accountTags: readonly string[] }

Household module

Select this module in model settings to use its names in the portal model editor (modules.household).

Model editor namePurpose and model value shape
modules.household.borrowingCapacityborrowingCapacity provides borrowing capacity in the Household model editor. Use it when a model needs this operation.

(options: modules.household.BorrowingCapacityOptions): CalculationReference

const family = household();

const members = householdInputs.members([
  { id: "anna", name: "Anna", dateOfBirth: "1990-01-01", salary: 45000 },
]);

const people = householdPeople({ household: family, members: members.input,
  taxAdapter: modules['swedish-income-tax'].personalTax });

const budget = householdBudget({
  household: family, members: people.outputs.persons, funding: people.funding,
});

const capacity = borrowingCapacity({
  owner: family, price: 2000000, capital: 400000,
  netIncome: people.outputs.netIncome, livingCosts: budget.outputs.total,
  annualRate: 0.04, stressRate: 0.07,
  policy: swedishMortgagePolicy(),
});

modules.household.householdCreate a household entity that party entities can reference through their owner option.

(options?: HouseholdOptions): EntityReference

const members = deccf.input.objectArray([{
  id: deccf.input.id('anna'), name: deccf.input.str('Anna'), role: deccf.input.str('adult'),
  dateOfBirth: deccf.input.date('1980-01-01'),
  salary: deccf.input.money(40000, deccf.currencies.SEK),
  pension: deccf.input.money(0, deccf.currencies.SEK), contributionWeight: deccf.input.decimal(1),
}]);

const family = modules.household.household();

const people = modules.household.householdPeople({
  household: family, members, taxAdapter: modules['swedish-income-tax'].personalTax,
});

return deccf.defineModel({
  currency: deccf.currencies.SEK, timeline: deccf.periods.monthly({from: '2026-05', count: 1}),
  preconditions: {members}, entities: {family}, components: {people: people.component},
});

modules.household.HOUSEHOLD_BUDGET_CATEGORIESHOUSEHOLD_BUDGET_CATEGORIES is a model value for household budget categories in the Household editor.

readonly Readonly<{ key: HouseholdBudgetCategoryKey; label: string; accountCode: string; }>[]

const { HOUSEHOLD_BUDGET_CATEGORIES } = modules.household;

modules.household.householdBudgetDeclare the monthly 2026 Consumer Agency budget need and ordinary expense postings.

(options: HouseholdBudgetOptions): ComponentReference<HouseholdBudgetOutputs>

const family = household();

const members = householdInputs.members([
  { id: "anna", name: "Anna", dateOfBirth: "1990-01-01", salary: 45000 },
]);

const people = householdPeople({ household: family, members: members.input,
  taxAdapter: modules['swedish-income-tax'].personalTax });

const budget = householdBudget({
  household: family, members: people.outputs.persons, funding: people.funding,
});

const capacity = borrowingCapacity({
  owner: family, price: 2000000, capital: 400000,
  netIncome: people.outputs.netIncome, livingCosts: budget.outputs.total,
  annualRate: 0.04, stressRate: 0.07,
  policy: swedishMortgagePolicy(),
});

modules.household.householdInputshouseholdInputs is a model value for household inputs in the Household editor.

Readonly<{ budgetOverrides(initial?: Partial<Record<modules.household.HouseholdBudgetCategoryKey, { readonly enabled?: boolean | 0 | 1; readonly amount?: number; }>>, options?: { readonly lockable?: boolean; }): { readonly input: deccf.ObjectInputReference<deccf.InputObjectFields>; readonly overrides: NonNullable<modules.household.HouseholdBudgetOptions["overrides"]>; }; person(row: modules.household.HouseholdPersonValues): modules.household.HouseholdPersonInputs; person<T extends deccf.InputObjectFields>(row: modules.household.HouseholdConfiguredValues<T>, options: { readonly fields: T; }): modules.household.HouseholdPersonInputs<modules.household.HouseholdConfiguredFields<T>>; members(rows?: readonly modules.household.HouseholdPersonValues[]): modules.household.HouseholdMembersInputs; members<T extends deccf.InputObjectFields>(rows: readonly (modules.household.HouseholdConfiguredValues<T>)[] | undefined, options: { readonly fields: T; }): modules.household.HouseholdMembersInputs<modules.household.HouseholdConfiguredFields<T>>; }>

const { householdInputs } = modules.household;

modules.household.householdInputs.budgetOverrideshouseholdInputs.budgetOverrides provides budget overrides in the Household model editor. Use it when a model needs this operation.

(initial?: Partial<Record<modules.household.HouseholdBudgetCategoryKey, { readonly enabled?: boolean | 0 | 1; readonly amount?: number; }>>, options?: { readonly lockable?: boolean; }): { readonly input: ObjectInputReference<InputObjectFields>; readonly overrides: NonNullable<modules.household.HouseholdBudgetOptions["overrides"]>; }

const { budgetOverrides } = modules.household.householdInputs;

modules.household.householdInputs.membershouseholdInputs.members provides members in the Household model editor. Use it when a model needs this operation.

(rows?: readonly HouseholdPersonValues[]): HouseholdMembersInputs
<T extends InputObjectFields>(rows: readonly (HouseholdConfiguredValues<T>)[] | undefined, options: { readonly fields: T; }): HouseholdMembersInputs<HouseholdConfiguredFields<T>>

const members = householdInputs.members([
  { id: "anna", name: "Anna", dateOfBirth: "1990-01-01", salary: 480000,
    withdrawal: 60000, taxableProfit: 100000 },
], { fields: {
  salary: input.money(0, currencies.SEK, { ui: { label: "Annual gross salary" } }),
  withdrawal: input.money(0, currencies.SEK),
  taxableProfit: input.money(0, currencies.SEK),
} });

const p = members.fields;

const people = householdPeople({
  household: family, members: members.input,
  incomes: {
    salary: { amount: p.salary, period: "annual", code: "income.employment.salary" },
    withdrawal: { amount: p.withdrawal, period: "annual", code: "equity.retained_earnings" },
  },
  tax: { taxBases: { [B.INK1_10_1]: { amount: p.taxableProfit, period: "annual" } } },
});

modules.household.householdInputs.personhouseholdInputs.person provides person in the Household model editor. Use it when a model needs this operation.

(row: HouseholdPersonValues): HouseholdPersonInputs
<T extends InputObjectFields>(row: HouseholdConfiguredValues<T>, options: { readonly fields: T; }): HouseholdPersonInputs<HouseholdConfiguredFields<T>>

const { person } = modules.household.householdInputs;

modules.household.householdPeoplehouseholdPeople provides household people in the Household model editor. Use it when a model needs this operation.

<TFields extends deccf.InputObjectFields>(options: Omit<modules.household.HouseholdPeopleOptions, "members"> & { readonly members: deccf.ObjectArrayInputReference<TFields> & modules.household.HouseholdPeopleOptions["members"]; }): modules.household.HouseholdPeople<TFields>
(options: modules.household.HouseholdPeopleOptions): modules.household.HouseholdPeople

const members = deccf.input.objectArray([{
  id: deccf.input.id('anna'), name: deccf.input.str('Anna'), role: deccf.input.str('adult'),
  dateOfBirth: deccf.input.date('1980-01-01'),
  salary: deccf.input.money(40000, deccf.currencies.SEK),
  pension: deccf.input.money(0, deccf.currencies.SEK), contributionWeight: deccf.input.decimal(1),
}]);

const family = modules.household.household();

const people = modules.household.householdPeople({
  household: family, members, taxAdapter: modules['swedish-income-tax'].personalTax,
});

return deccf.defineModel({
  currency: deccf.currencies.SEK, timeline: deccf.periods.monthly({from: '2026-05', count: 1}),
  preconditions: {members}, entities: {family}, components: {people: people.component},
});

modules.household.inputsInput factories shared by household model examples.

Readonly<{ familyRole(value?: "adult" | "child"): InputReference<"adult" | "child">; }>

const { inputs } = modules.household;

modules.household.inputs.familyRoleinputs.familyRole provides family role in the Household model editor. Use it when a model needs this operation.

(value?: "adult" | "child"): InputReference<"adult" | "child">

const { familyRole } = modules.household.inputs;

modules.household.KONSUMENTVERKET_BUDGET_YEARKONSUMENTVERKET_BUDGET_YEAR is a model value for konsumentverket budget year in the Household editor.

2026

const { KONSUMENTVERKET_BUDGET_YEAR } = modules.household;

modules.household.mortgageAffordabilitymortgageAffordability provides mortgage affordability in the Household model editor. Use it when a model needs this operation.

(options: Omit<modules.household.BorrowingCapacityOptions, "policy"> & { readonly policy?: modules.household.CapacityBorrowingPolicy; }): CalculationReference

const { mortgageAffordability } = modules.household;

modules.household.swedishMortgagePolicyswedishMortgagePolicy provides swedish mortgage policy in the Household model editor. Use it when a model needs this operation.

(options?: modules["swedish-amortization"].SwedishMortgagePolicyOptions): modules["swedish-amortization"].SwedishMortgagePolicy

const family = household();

const members = householdInputs.members([
  { id: "anna", name: "Anna", dateOfBirth: "1990-01-01", salary: 45000 },
]);

const people = householdPeople({ household: family, members: members.input,
  taxAdapter: modules['swedish-income-tax'].personalTax });

const budget = householdBudget({
  household: family, members: people.outputs.persons, funding: people.funding,
});

const capacity = borrowingCapacity({
  owner: family, price: 2000000, capital: 400000,
  netIncome: people.outputs.netIncome, livingCosts: budget.outputs.total,
  annualRate: 0.04, stressRate: 0.07,
  policy: swedishMortgagePolicy(),
});

modules.household.symProvides built-in numeric domains for common positive and percentage inputs.

Readonly<{ budgetMode(language?: "en" | "sv"): readonly EnumOption<"before" | "after" | "credit">[]; }>

const { sym } = modules.household;

modules.household.sym.budgetModesym.budgetMode provides budget mode in the Household model editor. Use it when a model needs this operation.

(language?: "en" | "sv"): readonly EnumOption<"before" | "after" | "credit">[]

const salary = input.money(480000, currencies.SEK, {domain: deccf.sym.pos});

const paymentWeight = input.decimal(1, {domain: deccf.sym.max100});

const share = input.fraction(.5, {domain: deccf.sym.max1});

const budgetMode = input.enum('after', {
  options: modules.household.sym.budgetMode('en'),
  ui: {label: 'Budget mode'},
});

modules.household.HouseholdBudgetBreakdownHouseholdBudgetBreakdown describes a model value used by the Household editor functions.

Model value shape: Readonly<Record<HouseholdBudgetCategoryKey | 'total', Readonly<{standard: number; actual: number}>>>

modules.household.HouseholdBudgetCategoryKeyHouseholdBudgetCategoryKey describes a model value used by the Household editor functions.

Model value shape: 'food' | 'clothing' | 'leisure' | 'personal_hygiene' | 'mobile_phone' | 'child_insurance' | 'child_equipment' | 'consumables' | 'home_equipment' | 'internet_subscription' | 'media' | 'electricity' | 'water_sewer' | 'home_insurance'

modules.household.HouseholdBudgetOptionsHouseholdBudgetOptions describes a model value used by the Household editor functions.

Model value shape: { name?: string; household: EntityReference; members: Readonly<Record<string, EntityReference>> | RepeatOutputProjection<EntityReference> | readonly EntityReference[]; overrides?: Partial<Readonly<Record<HouseholdBudgetCategoryKey, AmountSource | { readonly amount: AmountSource; readonly enabled: boolean | deccf.InputReference<boolean> | deccf.InputProjectionReference<boolean> | modules.household.NumberSource; }>>>; expenseAllocation?: Pick<modules.accountplan.ReallocateExpenseOptions, "to" | "weights">; funding?: { readonly from: Readonly<Record<string, EntityReference>> | RepeatOutputProjection<EntityReference>; readonly method: deccf.AllocationMethodReference; readonly posting: TransferPostingPolicy; readonly limits?: Readonly<Record<string, number>>; readonly redistribute?: boolean; readonly shortfall?: "error" | "report"; readonly unit?: number; readonly dependsOn?: readonly (deccf.CashflowReference | CalculationReference)[]; } }

modules.household.HouseholdBudgetOutputsHouseholdBudgetOutputs describes a model value used by the Household editor functions.

Model value shape: Readonly<{ readonly total: CalculationReference; readonly standardTotal: CalculationReference; readonly breakdown: CalculationReference; readonly payment: FlowGroupReference; readonly fundingShares?: CalculationProjectionReference; readonly fundingRequested?: CalculationProjectionReference; readonly fundingAllocated?: CalculationProjectionReference; readonly fundingShortfall?: CalculationProjectionReference; readonly fundingExplanation?: CalculationProjectionReference; readonly fundingTransfers?: CalculationReference; }>

modules.household.HouseholdOptionsHouseholdOptions describes a model value used by the Household editor functions.

Model value shape: Omit<EntityOptions, "family">

Nordic Household module

Select this module in model settings to use its names in the portal model editor (modules["nordic-household"]).

Model editor namePurpose and model value shape
modules["nordic-household"].nordicHouseholdReturn an ordinary monthly household model with country-selected native assessments. The full supported composition is limited to first-day monthly periods in 2026; selected mortgage effective dates also apply. No Swedish fallback, FX or cross-border tax. Native local profiles, versions and classified bases are mandatory; country gaps fail. Salary/pension cash, entered withholding/premiums, housing, living costs and loan payments are balanced ledger flows. The native annual tax and pension assessments are informational snapshots and are never posted as new monthly tax or income. Published monthly money metrics: grossIncome, taxPayments, pensionPayments, disposableIncome, housingPayments, loanPayments, interestPayments, principalPayments, otherExpenses, leftToLiveOn (sum annually), cashBalance and loanBalance (last annually). Pension valuePeriods/valueKinds retain timing and native operation kind per value; a mixed-period record reports period:'mixed'. nationalContext and each person's assessment publish units, periods, versions, primary sources and partial coverage. Mortgage policy is descriptive; entered contractual payments are not replaced with inferred bank terms or benefit awards. openingCash defaults to zero. Other cash/expense inputs require explicit amounts; Optional loanRateAdjustment is a number, numeric input or numeric calculation. It adds the same nominal annual decimal-point change to each loan's annualRate in each monthly period, with a zero floor. Omission preserves row rates exactly. Declare hidden distributions in preconditions and use a static calculation with bind.sample(shock,{calendar:'annual'}) to supply native Monte Carlo samples. The adjustment changes interest and principal allocation, not contractual payments, policy stress rates, tax rates or the supported 2026 monthly timeline. Negative adjusted rates floor at zero; nonfinite values and unsupported sources fail. expenses.source names user-entered amounts or verified applicable local evidence. All amounts are local units. Negative/nonfinite payments, foreign Money, missing local rates, unsupported profiles and conflicting identities/versions fail.

(options: NordicHouseholdOptions): ModelDefinition<ModelCurrency>

const {bind, calculation, input, periods} = deccf;

const members = input.objectArray([{
  id: input.id('anna'), name: input.str('Anna'), dateOfBirth: input.date('1980-01-01'),
  salary: input.decimal(20000), pension: input.decimal(0),
  taxPayment: input.decimal(5000), pensionPayment: input.decimal(99),
}]);

const loans = input.objectArray([{
  id: input.id('loan'), openingBalance: input.decimal(120000),
  annualRate: input.rate(0.04), payment: input.decimal(850),
}]);

const interestShock = input.normal({mean: 0, stdev: 0.01}, {visible: false});

const loanRateAdjustment = calculation({
  name: 'annualLoanRateAdjustment',
  bindings: {shock: bind.sample(interestShock, {calendar: 'annual'})},
  calculate: ({shock}) => shock,
});

return modules['nordic-household'].nordicHousehold({
  country: 'DK', currency: deccf.currencies.DKK,
  timeline: periods.monthly({from: '2026-05', count: 8}), members, loans,
  preconditions: {interestShock}, loanRateAdjustment,
  calculator: {defaultRun: {mode: 'monte-carlo', trials: 64, sampling: 'sobol'}},
  ruleVersions: {DK: {tax: '2026.1', pension: 'none', mortgage: '2025-11-18'}},
  tax: {DK: {residency: 'full-year', salary: 238812, pension: 0,
    municipalRate: .25, civilStatus: 'single', seniorSupplement: false,
    singleParentSupplement: false}},
  pension: {DK: null},
  housing: {value: 0, monthlyCost: 3000, conditions: {DK: {propertyType: 'owner-occupied'}}},
  expenses: {amount: 4000, source: 'user-entered local amounts'},
});

modules["nordic-household"].nordicHouseholdSupportInspect immutable support, versions, native required fields and partial coverage for five countries. Does not choose rules, calculate eligibility or create cashflows. Swedish tax rules are explicitly 2025; use a stated planning projection for the common 2026 scenario.

(): Readonly<Record<NordicCountry, NordicHouseholdCountrySupport>>

const support = modules['nordic-household'].nordicHouseholdSupport();

return deccf.defineModel({
  currency: deccf.currencies.DKK,
  timeline: deccf.periods.monthly({from: '2026-05', count: 1}),
  metrics: {supportedCountries: deccf.metric({value: Object.keys(support).length})},
});

modules["nordic-household"].NordicCountryNordicCountry describes a model value used by the Nordic Household editor functions.

Model value shape: 'SE' | 'DK' | 'FI' | 'IS' | 'NO'

modules["nordic-household"].NordicHouseholdCountrySupportNordicHouseholdCountrySupport describes a model value used by the Nordic Household editor functions.

Model value shape: { country: NordicCountry; currency: string; calendar: "monthly"; tax: Readonly<{ version: string; validFrom: string; validToExclusive: string; coverage: "partial"; required: readonly string[]; note: string; }>; pension: Readonly<{ version: string; coverage: "partial"; required: readonly string[]; note: string; validFrom?: string; validToExclusive?: string; period?: string; scheme?: string; }>; mortgage: Readonly<{ version: string; coverage: "partial"; required: readonly string[]; }> }

modules["nordic-household"].NordicHouseholdOptionsNordicHouseholdOptions describes a model value used by the Nordic Household editor functions.

Model value shape: { name?: string; country: InputReference<string> | NordicCountry; currency: Currency | InputReference<string | Currency>; timeline: Timeline; preconditions?: Readonly<Record<string, InputReference<deccf.InputValue>>> | deccf.DomainInputReference<Readonly<Record<string, InputReference<deccf.InputValue>>>>; scenarios?: readonly deccf.ModelScenarioSuggestion[]; calculator?: Readonly<deccf.CalculatorOptions>; ruleVersions: Readonly<Partial<Record<NordicCountry, NordicRuleVersions>>>; members: ObjectArrayInputReference<Readonly<Record<string, InputReference<deccf.InputValue>>>>; loans: ObjectArrayInputReference<Readonly<Record<string, InputReference<deccf.InputValue>>>>; loanRateAdjustment?: number | InputReference<number> | CalculationReference<number>; tax: NordicHouseholdTaxProfiles; pension: NordicHouseholdPensionProfiles; housing: Readonly<{ value: AmountSource; monthlyCost: AmountSource; conditions: Readonly<{ SE?: Readonly<{ purpose: "purchase" | "extension" | InputReference<string>; }>; DK?: Readonly<{ propertyType: "owner-occupied" | "holiday-home" | InputReference<string>; }>; FI?: Readonly<{ firstHome: boolean | InputReference<boolean>; }>; IS?: Readonly<{ firstTimeBuyer: boolean | InputReference<boolean>; loanType: "indexed" | "non-indexed" | InputReference<string>; }>; NO?: Readonly<{ loanType: "repayment" | "credit-line" | InputReference<string>; }>; }>; }>; expenses: Readonly<{ amount: AmountSource; source: string | InputReference<string>; }>; openingCash?: AmountSource; … 1 more fields }

modules["nordic-household"].NordicHouseholdPensionProfilesNordicHouseholdPensionProfiles describes a model value used by the Nordic Household editor functions.

Model value shape: { SE?: Readonly<{ id: string; basisSource: string; inputs: Readonly<Record<string, unknown>>; }>; DK?: Omit<DanishPensionOptions, "owner" | "id" | "ruleYear">; FI?: Omit<FinnishPensionOptions, "owner" | "id" | "ruleYear">; IS?: Omit<IcelandicPensionOptions, "owner" | "id" | "ruleYear">; NO?: Omit<NorwegianPensionOptions, "owner" | "id" | "ruleYear" | "birthYear"> }

modules["nordic-household"].NordicHouseholdTaxProfilesNordicHouseholdTaxProfiles describes a model value used by the Nordic Household editor functions.

Model value shape: { SE?: Omit<SwedishTaxSourceOptions, "taxBases"> & { readonly taxBases?: Readonly<Record<string, AmountSource>>; readonly project2025Rules?: boolean | InputReference<boolean>; }; DK?: Omit<DanishIncomeTaxOptions, "owner" | "name" | "ruleYear" | "birthYear">; FI?: Omit<FinnishIncomeTaxOptions, "owner" | "name" | "ruleYear" | "birthYear">; IS?: Omit<IcelandicIncomeTaxOptions, "owner" | "name" | "ruleYear" | "birthYear">; NO?: Omit<NorwegianIncomeTaxOptions, "owner" | "name" | "ruleYear" | "birthYear"> }

modules["nordic-household"].NordicRuleVersionsNordicRuleVersions describes a model value used by the Nordic Household editor functions.

Model value shape: { tax: string | InputReference<string>; pension: string | InputReference<string>; mortgage: string | InputReference<string> }

Nordic Mortgage module

Select this module in model settings to use its names in the portal model editor (modules["nordic-mortgage"]).

Model editor namePurpose and model value shape
modules["nordic-mortgage"].danishMortgagePolicydanishMortgagePolicy provides danish mortgage policy in the Nordic Mortgage model editor. Use it when a model needs this operation.

(options: { readonly version: "2025-11-18"; readonly propertyType: "owner-occupied" | "holiday-home"; }): NordicMortgagePolicy

const { danishMortgagePolicy } = modules["nordic-mortgage"];

modules["nordic-mortgage"].finnishMortgagePolicyfinnishMortgagePolicy provides finnish mortgage policy in the Nordic Mortgage model editor. Use it when a model needs this operation.

(options: { readonly version: "2025-03-24"; readonly firstHome?: boolean; }): NordicMortgagePolicy

const { finnishMortgagePolicy } = modules["nordic-mortgage"];

modules["nordic-mortgage"].icelandicMortgagePolicyicelandicMortgagePolicy provides icelandic mortgage policy in the Nordic Mortgage model editor. Use it when a model needs this operation.

(options: { readonly version: "2025-11-04"; readonly firstTimeBuyer?: boolean; readonly loanType: "indexed" | "non-indexed"; }): NordicMortgagePolicy

const { icelandicMortgagePolicy } = modules["nordic-mortgage"];

modules["nordic-mortgage"].nordicMortgagePolicynordicMortgagePolicy provides nordic mortgage policy in the Nordic Mortgage model editor. Use it when a model needs this operation.

(options: { readonly country: NordicCountry; readonly version: string; readonly [condition: string]: unknown; }): NordicMortgagePolicy

const { household, borrowingCapacity } = modules.household;

const { nordicMortgagePolicy } = modules['nordic-mortgage'];

const policy = nordicMortgagePolicy({
  country: 'IS',
  version: '2025-11-04',
  firstTimeBuyer: true,
  loanType: 'non-indexed',
});

const home = household();

const capacity = borrowingCapacity({
  owner: home,
  price: 50000000,
  capital: 5000000,
  netIncome: 900000,
  livingCosts: 350000,
  debtPayments: 60000,
  annualRate: 0.08,
  stressRate: 0,
  minimumMargin: 0,
  policy,
});

return deccf.defineModel({
  currency: deccf.currencies.ISK,
  timeline: deccf.periods.monthly({ from: '2027-01', count: 1 }),
  entities: { home },
  calculations: { capacity },
});

modules["nordic-mortgage"].norwegianMortgagePolicynorwegianMortgagePolicy provides norwegian mortgage policy in the Nordic Mortgage model editor. Use it when a model needs this operation.

(options: { readonly version: "2024-12-31"; readonly loanType: "repayment" | "credit-line"; }): NordicMortgagePolicy

const { norwegianMortgagePolicy } = modules["nordic-mortgage"];

modules["nordic-mortgage"].swedishNordicMortgagePolicyswedishNordicMortgagePolicy provides swedish nordic mortgage policy in the Nordic Mortgage model editor. Use it when a model needs this operation.

(options: { readonly version: "2026-04-01"; readonly purpose?: "purchase" | "extension"; }): NordicMortgagePolicy

const { swedishNordicMortgagePolicy } = modules["nordic-mortgage"];

modules["nordic-mortgage"].MortgageSupportEntryMortgageSupportEntry describes a model value used by the Nordic Mortgage editor functions.

Model value shape: { name: string; type: MortgageSupportType; cashflowTreatment: "non-cash" | "separate-loan" | "external-grant-only" | "separate-interest-credit"; source: string; sourceReviewedOn: string; scope: string }

modules["nordic-mortgage"].MortgageSupportTypeMortgageSupportType describes a model value used by the Nordic Mortgage editor functions.

Model value shape: 'grant' | 'repayable-loan' | 'guarantee' | 'interest-subsidy'

modules["nordic-mortgage"].NordicCountryNordicCountry describes a model value used by the Nordic Mortgage editor functions.

Model value shape: 'DK' | 'FI' | 'IS' | 'NO' | 'SE'

modules["nordic-mortgage"].NordicMortgagePolicyNordicMortgagePolicy describes a model value used by the Nordic Mortgage editor functions.

Model value shape: NordicMortgagePolicyData & (BorrowingPolicy | CollateralBorrowingPolicy)

modules["nordic-mortgage"].NordicMortgagePolicyDataNordicMortgagePolicyData describes a model value used by the Nordic Mortgage editor functions.

Model value shape: { country: NordicCountry; version: string; effectiveFrom?: string; reviewedOn: string; sources: readonly Readonly<{ title: string; url: string; }>[]; support: readonly MortgageSupportEntry[]; scope: string; assumptions: readonly string[]; supportInventory: "not-verified" | "verified-selected-programs"; maxDebtToIncome?: number; maxDebtServiceToIncome?: number; stressRateIncrease?: number; stressRateFloor?: number; stressRepayment?: Readonly<{ method: "annuity"; termMonths: number; }>; purpose?: "purchase" | "extension" }

Sie Import module

Select this module in model settings to use its names in the portal model editor (modules["sie-import"]).

Model editor namePurpose and model value shape
modules["sie-import"].parseLatestSieSnapshotParse the newest balance snapshot from classic SIE account and period balance records.

(content: string): SieSnapshot

const { parseLatestSieSnapshot } = modules["sie-import"];

modules["sie-import"].sieStatementCreate a monthly statement that applies the latest SIE balances at that month's end.

(options: SieStatementOptions): FlowGroupReference

const { currencies, defineModel, entity, input, periods } = deccf;

const { stdaccount } = modules.accountplan;

const { sieStatement, thisYear } = modules["sie-import"];

const year = thisYear();

const compactDate = date => date.replaceAll("-", "");

const sampleSie = [
  "#SIETYP 1",
  `#RAR 0 ${compactDate(year.start)} ${compactDate(year.end)}`,
  '#KONTO 1930 "Cash at bank"',
  '#KONTO 2091 "Retained earnings"',
  "#UB 0 1930 100.00",
  "#UB 0 2091 -100.00",
].join("\n");

const company = entity.asset();

const sieContent = input.tableToSie(sampleSie, {
  dynamicAccounts: true,
  personalAccounts: true,
  businessAccounts: true,
  splitResAndUb: true,
  dynamicPeriods: true,
  fileDrop: true,
});

const bank = stdaccount({ code: "1930", owner: company });

const retainedEarnings = stdaccount({ code: "2091", owner: company });

const importedBalances = sieStatement({
  owner: company,
  sieContent,
});

const model = defineModel({
  name: "sie-balance-import",
  currency: currencies.SEK,
  timeline: periods.monthly({ from: "2025-01", count: 36 }),
  preconditions: { sieContent },
  entities: { company },
  accounts: { bank, retainedEarnings },
  flows: { importedBalances },
});

return model;

modules["sie-import"].thisYearReturn the full-calendar-year dates for the current year plus an integer offset.

(offset?: number, today?: Date): Readonly<{ year: number; start: `${number}-01-01`; end: `${number}-12-31`; }>

const { currencies, defineModel, entity, input, periods } = deccf;

const { stdaccount } = modules.accountplan;

const { sieStatement, thisYear } = modules["sie-import"];

const year = thisYear();

const compactDate = date => date.replaceAll("-", "");

const sampleSie = [
  "#SIETYP 1",
  `#RAR 0 ${compactDate(year.start)} ${compactDate(year.end)}`,
  '#KONTO 1930 "Cash at bank"',
  '#KONTO 2091 "Retained earnings"',
  "#UB 0 1930 100.00",
  "#UB 0 2091 -100.00",
].join("\n");

const company = entity.asset();

const sieContent = input.tableToSie(sampleSie, {
  dynamicAccounts: true,
  personalAccounts: true,
  businessAccounts: true,
  splitResAndUb: true,
  dynamicPeriods: true,
  fileDrop: true,
});

const bank = stdaccount({ code: "1930", owner: company });

const retainedEarnings = stdaccount({ code: "2091", owner: company });

const importedBalances = sieStatement({
  owner: company,
  sieContent,
});

const model = defineModel({
  name: "sie-balance-import",
  currency: currencies.SEK,
  timeline: periods.monthly({ from: "2025-01", count: 36 }),
  preconditions: { sieContent },
  entities: { company },
  accounts: { bank, retainedEarnings },
  flows: { importedBalances },
});

return model;

modules["sie-import"].SieSnapshotSieSnapshot describes a model value used by the Sie Import editor functions.

Model value shape: { period: `${number}-${number}`; date: `${number}-${number}-${number}`; currency: string; balances: ReadonlyMap<string, number>; historyStart: `${number}-${number}`; monthlyActivity: readonly Readonly<{ period: `${number}-${number}`; accountCode: string; amount: number; source: "period" | "transaction"; }>[]; openingResultAdjustment?: Readonly<{ amount: number; previousYearEnd: string; }>; bookedCurrentResultAdjustment?: Readonly<{ amount: number; financialYearEnd: string; }> }

modules["sie-import"].SieStatementOptionsSieStatementOptions describes a model value used by the Sie Import editor functions.

Model value shape: { name?: string; owner: EntityReference; sieContent: InputReference<string>; dependsOn?: readonly CashflowReference[]; triggers?: TriggerReference | readonly TriggerReference[] }

Business Base Forecast module

Select this module in model settings to use its names in the portal model editor (modules["business-base-forecast"]).

Model editor namePurpose and model value shape
modules["business-base-forecast"].annualGrowthannualGrowth provides annual growth in the Business Base Forecast model editor. Use it when a model needs this operation.

(options: { readonly annualRate: number | InputReference<number> | ((context: ForecastMethodContext) => number); readonly role?: string; }): ForecastAmountMethod

const { annualGrowth } = modules["business-base-forecast"];

modules["business-base-forecast"].businessBaseForecastbusinessBaseForecast provides business base forecast in the Business Base Forecast model editor. Use it when a model needs this operation.

(options: BusinessBaseForecastOptions): FlowGroupReference

const { currencies, defineModel, entity, input, periods, schedule } = deccf;

const { stdaccount } = modules.accountplan;

const { businessBaseForecast, forecastSales, formulas } = modules["business-base-forecast"];

const company = entity.asset({ label: "Northwind Tools" });

const salesGrowth = input.rate(0.04);

const revenue = stdaccount({ code: "3000", owner: company });

const receivables = stdaccount({ code: "1510", owner: company });

const forecast = businessBaseForecast({
  owner: company,
  schedule: schedule.monthly(),
  sections: {
    sales: forecastSales({
      method: formulas.growth.annual({ rate: salesGrowth, role: "revenue" }),
    }),
  },
});

return defineModel({
  name: "Northwind sales forecast",
  currency: currencies.SEK,
  timeline: periods.monthly({ from: "2026-01", count: 36 }),
  entities: { company },
  accounts: { revenue, receivables },
  flows: { forecast },
  preconditions: { salesGrowth },
});

modules["business-base-forecast"].businessForecastbusinessForecast provides business forecast in the Business Base Forecast model editor. Use it when a model needs this operation.

(options: BusinessForecastOptions): ComponentReference

const { input } = deccf;

const forecast = businessForecast({
  owner: company,
  schedule: schedule.monthly(),
  template: "industry",
  sni: input.sni("47"), // Retail trade
});

modules["business-base-forecast"].businessForecastTemplatesbusinessForecastTemplates is a model value for business forecast templates in the Business Base Forecast editor.

Readonly<Record<BusinessForecastTemplate, Readonly<{ readonly label: string; readonly description: string; }>>>

const { businessForecastTemplates } = modules["business-base-forecast"];

modules["business-base-forecast"].forecastInvestmentforecastInvestment provides forecast investment in the Business Base Forecast model editor. Use it when a model needs this operation.

(options?: ForecastInvestmentOptions): FlowGroupReference

const { currencies, defineModel, entity, periods, schedule } = deccf;

const { stdaccount } = modules.accountplan;

const { businessBaseForecast, forecastInvestment, formulas } = modules["business-base-forecast"];

const company = entity.asset({ label: "Northwind Tools" });

const equipment = stdaccount({ code: "1221", owner: company, initial: 100_000 });

const accumulatedDepreciation = stdaccount({ code: "1229", owner: company, initial: -20_000 });

const depreciationExpense = stdaccount({ code: "7830", owner: company });

const forecast = businessBaseForecast({
  owner: company,
  schedule: schedule.monthly(),
  sections: {
    equipment: forecastInvestment({
      openingAssets: {
        remainingLifeYears: formulas.investment.remainingLifeFromHistoricalDepreciation({
          fallbackYears: 5,
          minimumYears: 1,
          maximumYears: 25,
        }),
      },
    }),
  },
});

return defineModel({
  name: "Northwind equipment forecast",
  currency: currencies.SEK,
  timeline: periods.monthly({ from: "2026-01", count: 36 }),
  entities: { company },
  accounts: { equipment, accumulatedDepreciation, depreciationExpense },
  flows: { forecast },
});

modules["business-base-forecast"].forecastOperatingCostsforecastOperatingCosts provides forecast operating costs in the Business Base Forecast model editor. Use it when a model needs this operation.

(options: ForecastAccrualOptions): FlowGroupReference

const { currencies, defineModel, entity, input, periods, schedule } = deccf;

const { stdaccount } = modules.accountplan;

const { businessBaseForecast, formulas, forecastSales, forecastOperatingCosts } = modules["business-base-forecast"];

const company = entity.asset({ label: "Northwind Tools" });

const salesGrowth = input.rate(0.04);

const costGrowth = input.rate(0.025);

const revenue = stdaccount({ code: "3000", owner: company });

const receivables = stdaccount({ code: "1510", owner: company });

const premisesExpense = stdaccount({ code: "5010", owner: company });

const payables = stdaccount({ code: "2440", owner: company });

const forecast = businessBaseForecast({
  owner: company,
  schedule: schedule.monthly(),
  sections: {
    sales: forecastSales({
      method: formulas.growth.annual({ rate: salesGrowth, role: "revenue" }),
    }),
    premises: forecastOperatingCosts({
      activityRole: "premises",
      accountChoices: { expenses: premisesExpense, payables },
      method: formulas.growth.annual({ rate: costGrowth, role: "premises" }),
    }),
  },
});

return defineModel({
  name: "Northwind forecast methods",
  currency: currencies.SEK,
  timeline: periods.monthly({ from: "2026-01", count: 36 }),
  entities: { company },
  accounts: { revenue, receivables, premisesExpense, payables },
  flows: { forecast },
  preconditions: { salesGrowth, costGrowth },
});

modules["business-base-forecast"].forecastSalesforecastSales provides forecast sales in the Business Base Forecast model editor. Use it when a model needs this operation.

(options: ForecastAccrualOptions): FlowGroupReference

const { currencies, defineModel, entity, input, periods, schedule } = deccf;

const { stdaccount } = modules.accountplan;

const { businessBaseForecast, forecastSales, formulas } = modules["business-base-forecast"];

const company = entity.asset({ label: "Northwind Tools" });

const salesGrowth = input.rate(0.04);

const revenue = stdaccount({ code: "3000", owner: company });

const receivables = stdaccount({ code: "1510", owner: company });

const forecast = businessBaseForecast({
  owner: company,
  schedule: schedule.monthly(),
  sections: {
    sales: forecastSales({
      method: formulas.growth.annual({ rate: salesGrowth, role: "revenue" }),
    }),
  },
});

return defineModel({
  name: "Northwind sales forecast",
  currency: currencies.SEK,
  timeline: periods.monthly({ from: "2026-01", count: 36 }),
  entities: { company },
  accounts: { revenue, receivables },
  flows: { forecast },
  preconditions: { salesGrowth },
});

modules["business-base-forecast"].formulasformulas is a model value for formulas in the Business Base Forecast editor.

BusinessForecastFormulas

const { formulas } = modules["business-base-forecast"];

modules["business-base-forecast"].formulas.financing.drawToMinimumCashformulas.financing.drawToMinimumCash provides draw to minimum cash in the Business Base Forecast model editor. Use it when a model needs this operation.

(options: { readonly minimumCash: ForecastFormulaValue; readonly creditLimit: ForecastFormulaValue; }): ForecastAmountMethod

const { drawToMinimumCash } = modules["business-base-forecast"].formulas.financing;

modules["business-base-forecast"].formulas.financing.interestOnOpeningBalanceformulas.financing.interestOnOpeningBalance provides interest on opening balance in the Business Base Forecast model editor. Use it when a model needs this operation.

(options: { readonly annualRate: ForecastNumericFormulaValue; readonly balance?: ForecastFormulaValue; }): ForecastAmountMethod

const { interestOnOpeningBalance } = modules["business-base-forecast"].formulas.financing;

modules["business-base-forecast"].formulas.financing.repayAboveMinimumCashformulas.financing.repayAboveMinimumCash provides repay above minimum cash in the Business Base Forecast model editor. Use it when a model needs this operation.

(options: { readonly minimumCash: ForecastFormulaValue; }): ForecastAmountMethod

const { repayAboveMinimumCash } = modules["business-base-forecast"].formulas.financing;

modules["business-base-forecast"].formulas.growth.annualformulas.growth.annual provides annual in the Business Base Forecast model editor. Use it when a model needs this operation.

(options: { readonly rate: ForecastNumericFormulaValue; readonly role?: string; }): ForecastAmountMethod

const { currencies, defineModel, entity, input, periods, schedule } = deccf;

const { stdaccount } = modules.accountplan;

const { businessBaseForecast, forecastSales, formulas } = modules["business-base-forecast"];

const company = entity.asset({ label: "Northwind Tools" });

const salesGrowth = input.rate(0.04);

const revenue = stdaccount({ code: "3000", owner: company });

const receivables = stdaccount({ code: "1510", owner: company });

const forecast = businessBaseForecast({
  owner: company,
  schedule: schedule.monthly(),
  sections: {
    sales: forecastSales({
      method: formulas.growth.annual({ rate: salesGrowth, role: "revenue" }),
    }),
  },
});

return defineModel({
  name: "Northwind sales forecast",
  currency: currencies.SEK,
  timeline: periods.monthly({ from: "2026-01", count: 36 }),
  entities: { company },
  accounts: { revenue, receivables },
  flows: { forecast },
  preconditions: { salesGrowth },
});

modules["business-base-forecast"].formulas.growth.historicalMonthlyAverageformulas.growth.historicalMonthlyAverage provides historical monthly average in the Business Base Forecast model editor. Use it when a model needs this operation.

(options?: { readonly role?: string; }): ForecastAmountMethod

const { historicalMonthlyAverage } = modules["business-base-forecast"].formulas.growth;

modules["business-base-forecast"].formulas.investment.capexFromRevenueformulas.investment.capexFromRevenue provides capex from revenue in the Business Base Forecast model editor. Use it when a model needs this operation.

(options: { readonly rate: ForecastNumericFormulaValue; readonly revenue?: ForecastFormulaValue; }): ForecastAmountMethod

const { capexFromRevenue } = modules["business-base-forecast"].formulas.investment;

modules["business-base-forecast"].formulas.investment.remainingLifeFromHistoricalDepreciationformulas.investment.remainingLifeFromHistoricalDepreciation provides remaining life from historical depreciation in the Business Base Forecast model editor. Use it when a model needs this operation.

(options?: { readonly fallbackYears?: number | InputReference<number>; readonly minimumYears?: number; readonly maximumYears?: number; }): RemainingLifeMethod

const { currencies, defineModel, entity, periods, schedule } = deccf;

const { stdaccount } = modules.accountplan;

const { businessBaseForecast, forecastInvestment, formulas } = modules["business-base-forecast"];

const company = entity.asset({ label: "Northwind Tools" });

const equipment = stdaccount({ code: "1221", owner: company, initial: 100_000 });

const accumulatedDepreciation = stdaccount({ code: "1229", owner: company, initial: -20_000 });

const depreciationExpense = stdaccount({ code: "7830", owner: company });

const forecast = businessBaseForecast({
  owner: company,
  schedule: schedule.monthly(),
  sections: {
    equipment: forecastInvestment({
      openingAssets: {
        remainingLifeYears: formulas.investment.remainingLifeFromHistoricalDepreciation({
          fallbackYears: 5,
          minimumYears: 1,
          maximumYears: 25,
        }),
      },
    }),
  },
});

return defineModel({
  name: "Northwind equipment forecast",
  currency: currencies.SEK,
  timeline: periods.monthly({ from: "2026-01", count: 36 }),
  entities: { company },
  accounts: { equipment, accumulatedDepreciation, depreciationExpense },
  flows: { forecast },
});

modules["business-base-forecast"].formulas.sales.splitGrossInvoiceformulas.sales.splitGrossInvoice provides split gross invoice in the Business Base Forecast model editor. Use it when a model needs this operation.

(options: { readonly rate: ForecastNumericFormulaValue; readonly amount?: ForecastFormulaValue; }): ((context: ForecastMethodContext) => Readonly<{ netSales: number; vat: number; }>) & { readonly preconditions?: Readonly<Record<string, InputReference<InputValue>>>; }

const { splitGrossInvoice } = modules["business-base-forecast"].formulas.sales;

modules["business-base-forecast"].formulas.tax.payAtYearEndformulas.tax.payAtYearEnd provides pay at year end in the Business Base Forecast model editor. Use it when a model needs this operation.

(): ForecastAmountMethod

const { payAtYearEnd } = modules["business-base-forecast"].formulas.tax;

modules["business-base-forecast"].formulas.tax.positiveProfitformulas.tax.positiveProfit provides positive profit in the Business Base Forecast model editor. Use it when a model needs this operation.

(options: { readonly rate: ForecastNumericFormulaValue; }): ForecastAmountMethod

const { positiveProfit } = modules["business-base-forecast"].formulas.tax;

modules["business-base-forecast"].formulas.trend.exponentialSmoothingformulas.trend.exponentialSmoothing provides exponential smoothing in the Business Base Forecast model editor. Use it when a model needs this operation.

(options: { readonly role: string; readonly alpha?: number; readonly periods?: number; readonly minimumObservations?: number; }): ForecastAmountMethod

const { exponentialSmoothing } = modules["business-base-forecast"].formulas.trend;

modules["business-base-forecast"].formulas.trend.linearOrWeightedAverageformulas.trend.linearOrWeightedAverage provides linear or weighted average in the Business Base Forecast model editor. Use it when a model needs this operation.

(options: { readonly role: string; readonly periods?: number; readonly weights?: readonly number[]; readonly minimumObservations?: number; readonly minimumWeightedObservations?: number; readonly maximumNormalizedRmse?: number; }): ForecastAmountMethod

const { currencies, defineModel, entity, periods, schedule } = deccf;

const { stdaccount } = modules.accountplan;

const { businessBaseForecast, forecastSales, formulas } = modules["business-base-forecast"];

const company = entity.asset({ label: "Northwind Tools" });

const revenue = stdaccount({ code: "3000", owner: company });

const receivables = stdaccount({ code: "1510", owner: company });

const forecast = businessBaseForecast({
  owner: company,
  schedule: schedule.monthly(),
  sections: {
    sales: forecastSales({
      method: formulas.trend.linearOrWeightedAverage({
        role: "revenue",
        periods: 12,
        minimumObservations: 6,
        maximumNormalizedRmse: 0.2,
      }),
    }),
  },
});

return defineModel({
  name: "Northwind trend forecast",
  currency: currencies.SEK,
  timeline: periods.monthly({ from: "2026-01", count: 36 }),
  entities: { company },
  accounts: { revenue, receivables },
  flows: { forecast },
});

modules["business-base-forecast"].formulas.trend.linearRegressionformulas.trend.linearRegression provides linear regression in the Business Base Forecast model editor. Use it when a model needs this operation.

(options: { readonly role: string; readonly periods?: number; readonly minimumObservations?: number; readonly floorAtZero?: boolean; }): ForecastAmountMethod

const { linearRegression } = modules["business-base-forecast"].formulas.trend;

modules["business-base-forecast"].formulas.trend.seasonalSameMonthAverageformulas.trend.seasonalSameMonthAverage provides seasonal same month average in the Business Base Forecast model editor. Use it when a model needs this operation.

(options: { readonly role: string; readonly years?: number; readonly minimumObservations?: number; }): ForecastAmountMethod

const { seasonalSameMonthAverage } = modules["business-base-forecast"].formulas.trend;

modules["business-base-forecast"].formulas.trend.weightedMovingAverageformulas.trend.weightedMovingAverage provides weighted moving average in the Business Base Forecast model editor. Use it when a model needs this operation.

(options: { readonly role: string; readonly periods?: number; readonly weights?: readonly number[]; readonly minimumObservations?: number; }): ForecastAmountMethod

const { weightedMovingAverage } = modules["business-base-forecast"].formulas.trend;

modules["business-base-forecast"].formulas.workingCapital.balanceFromDaysformulas.workingCapital.balanceFromDays provides balance from days in the Business Base Forecast model editor. Use it when a model needs this operation.

(options: { readonly amount: ForecastFormulaValue; readonly days: ForecastNumericFormulaValue; }): ForecastAmountMethod

const { balanceFromDays } = modules["business-base-forecast"].formulas.workingCapital;

modules["business-base-forecast"].formulas.workingCapital.collectReceivablesformulas.workingCapital.collectReceivables provides collect receivables in the Business Base Forecast model editor. Use it when a model needs this operation.

(): ForecastAmountMethod

const { collectReceivables } = modules["business-base-forecast"].formulas.workingCapital;

modules["business-base-forecast"].formulas.workingCapital.payPayablesformulas.workingCapital.payPayables provides pay payables in the Business Base Forecast model editor. Use it when a model needs this operation.

(): ForecastAmountMethod

const { payPayables } = modules["business-base-forecast"].formulas.workingCapital;

modules["business-base-forecast"].formulas.workingCapital.targetsFromDaysformulas.workingCapital.targetsFromDays provides targets from days in the Business Base Forecast model editor. Use it when a model needs this operation.

(targets: Readonly<Record<string, { readonly amount: ForecastFormulaValue; readonly days: ForecastNumericFormulaValue; }>>): ((context: ForecastMethodContext) => Readonly<Record<string, number>>) & { readonly preconditions?: Readonly<Record<string, InputReference<InputValue>>>; }

const { targetsFromDays } = modules["business-base-forecast"].formulas.workingCapital;

modules["business-base-forecast"].historicalMonthlyAveragehistoricalMonthlyAverage provides historical monthly average in the Business Base Forecast model editor. Use it when a model needs this operation.

(options?: { readonly role?: string; }): ForecastAmountMethod

const { historicalMonthlyAverage } = modules["business-base-forecast"];

modules["business-base-forecast"].remainingLifeFromHistoricalDepreciationremainingLifeFromHistoricalDepreciation provides remaining life from historical depreciation in the Business Base Forecast model editor. Use it when a model needs this operation.

(options?: { readonly fallbackYears?: number | InputReference<number>; readonly minimumYears?: number; readonly maximumYears?: number; }): RemainingLifeMethod

const { currencies, defineModel, entity, periods, schedule } = deccf;

const { stdaccount } = modules.accountplan;

const { businessBaseForecast, forecastInvestment, formulas } = modules["business-base-forecast"];

const company = entity.asset({ label: "Northwind Tools" });

const equipment = stdaccount({ code: "1221", owner: company, initial: 100_000 });

const accumulatedDepreciation = stdaccount({ code: "1229", owner: company, initial: -20_000 });

const depreciationExpense = stdaccount({ code: "7830", owner: company });

const forecast = businessBaseForecast({
  owner: company,
  schedule: schedule.monthly(),
  sections: {
    equipment: forecastInvestment({
      openingAssets: {
        remainingLifeYears: formulas.investment.remainingLifeFromHistoricalDepreciation({
          fallbackYears: 5,
          minimumYears: 1,
          maximumYears: 25,
        }),
      },
    }),
  },
});

return defineModel({
  name: "Northwind equipment forecast",
  currency: currencies.SEK,
  timeline: periods.monthly({ from: "2026-01", count: 36 }),
  entities: { company },
  accounts: { equipment, accumulatedDepreciation, depreciationExpense },
  flows: { forecast },
});

modules["business-base-forecast"].BusinessBaseForecastOptionsBusinessBaseForecastOptions describes a model value used by the Business Base Forecast editor functions.

Model value shape: { name?: string; owner?: EntityReference; schedule?: ScheduleReference; triggeredBy?: TriggerReference; sections: FlowGroupItem | Readonly<Record<string, FlowGroupItem>> }

modules["business-base-forecast"].BusinessForecastFormulasBusinessForecastFormulas describes a model value used by the Business Base Forecast editor functions.

Model value shape: { growth: { annual(options: { readonly rate: ForecastNumericFormulaValue; readonly role?: string; }): ForecastAmountMethod; historicalMonthlyAverage(options?: { readonly role?: string; }): ForecastAmountMethod; }; trend: { weightedMovingAverage(options: { readonly role: string; readonly periods?: number; readonly weights?: readonly number[]; readonly minimumObservations?: number; }): ForecastAmountMethod; linearRegression(options: { readonly role: string; readonly periods?: number; readonly minimumObservations?: number; readonly floorAtZero?: boolean; }): ForecastAmountMethod; linearOrWeightedAverage(options: { readonly role: string; readonly periods?: number; readonly weights?: readonly number[]; readonly minimumObservations?: number; readonly minimumWeightedObservations?: number; readonly maximumNormalizedRmse?: number; }): ForecastAmountMethod; exponentialSmoothing(options: { readonly role: string; readonly alpha?: number; readonly periods?: number; readonly minimumObservations?: number; }): ForecastAmountMethod; seasonalSameMonthAverage(options: { readonly role: string; readonly years?: number; readonly minimumObservations?: number; }): ForecastAmountMethod; }; sales: { splitGrossInvoice(options: { readonly rate: ForecastNumericFormulaValue; readonly amount?: ForecastFormulaValue; }): ((context: ForecastMethodContext) => Readonly<{ netSales: number; vat: number; }>) & { readonly preconditions?: Readonly<Record<string, InputReference<InputValue>>>; }; }; workingCapital: { balanceFromDays(options: { readonly amount: ForecastFormulaValue; readonly days: ForecastNumericFormulaValue; }): ForecastAmountMethod; targetsFromDays(targets: Readonly<Record<string, { readonly amount: ForecastFormulaValue; readonly days: ForecastNumericFormulaValue; }>>): ((context: ForecastMethodContext) => Readonly<Record<string, number>>) & { readonly preconditions?: Readonly<Record<string, InputReference<InputValue>>>; }; collectReceivables(): ForecastAmountMethod; payPayables(): ForecastAmountMethod; }; investment: { remainingLifeFromHistoricalDepreciation: typeof remainingLifeFromHistoricalDepreciation; capexFromRevenue(options: { readonly rate: ForecastNumericFormulaValue; readonly revenue?: ForecastFormulaValue; }): ForecastAmountMethod; }; financing: { interestOnOpeningBalance(options: { readonly annualRate: ForecastNumericFormulaValue; readonly balance?: ForecastFormulaValue; }): ForecastAmountMethod; drawToMinimumCash(options: { readonly minimumCash: ForecastFormulaValue; readonly creditLimit: ForecastFormulaValue; }): ForecastAmountMethod; repayAboveMinimumCash(options: { readonly minimumCash: ForecastFormulaValue; }): ForecastAmountMethod; }; tax: { positiveProfit(options: { readonly rate: ForecastNumericFormulaValue; }): ForecastAmountMethod; payAtYearEnd(): ForecastAmountMethod; } }

modules["business-base-forecast"].BusinessForecastOptionsBusinessForecastOptions describes a model value used by the Business Base Forecast editor functions.

Model value shape: { owner: EntityReference; schedule?: ScheduleReference; triggeredBy?: TriggerReference; template?: BusinessForecastTemplate; sni?: InputReference<string>; growth?: number | InputReference<number>; costGrowth?: number | InputReference<number>; fallbackGrowth?: number | InputReference<number>; sections?: Readonly<Record<string, FlowGroupItem>> }

modules["business-base-forecast"].BusinessForecastTemplateBusinessForecastTemplate describes a model value used by the Business Base Forecast editor functions.

Model value shape: "straightforward" | "growth" | "downside" | "historical" | "automatic" | "industry"

modules["business-base-forecast"].ForecastAccrualOptionsForecastAccrualOptions describes a model value used by the Business Base Forecast editor functions.

Model value shape: { name?: string; owner?: EntityReference; schedule?: ScheduleReference; triggeredBy?: TriggerReference; method: ForecastAmountMethod; preconditions?: Readonly<Record<string, InputReference<InputValue>>>; activityRole?: string; balanceRole?: string; accountChoices?: Readonly<Record<string, AccountReference | readonly AccountReference[]>>; defaultAccountCodes?: Readonly<{ readonly activity?: string; readonly balance?: string; }>; currencyUnit?: number }

modules["business-base-forecast"].ForecastAmountMethodForecastAmountMethod describes a model value used by the Business Base Forecast editor functions.

Model value shape: ((context: ForecastMethodContext) => number) & { readonly preconditions?: Readonly<Record<string, InputReference<InputValue>>>; }

modules["business-base-forecast"].ForecastDomainContextForecastDomainContext describes a model value used by the Business Base Forecast editor functions.

Model value shape: { owner?: EntityReference; section: Readonly<{ readonly name: string; readonly type: string; readonly activityRole?: string; readonly balanceRole?: string; readonly activitySide?: "debit" | "credit"; readonly balanceSide?: "debit" | "credit"; }>; accounts: Readonly<Record<string, readonly AccountReference[]>>; history: ForecastHistory; values: Readonly<Record<string, unknown>>; openingAssets?: Readonly<{ readonly remainingLifeYears: number | InputReference<number> | RemainingLifeMethod; readonly assetBalance: number; readonly accumulatedDepreciationBalance: number; }>; source?: deccf.TriggerSource; time: deccf.TimeContext }

modules["business-base-forecast"].ForecastFormulaValueForecastFormulaValue describes a model value used by the Business Base Forecast editor functions.

Model value shape: number | Money | string | InputReference<number | Money> | ((context: ForecastMethodContext) => number | Money)

modules["business-base-forecast"].ForecastHistoryForecastHistory describes a model value used by the Business Base Forecast editor functions.

Model value shape: { accounts: readonly Readonly<{ readonly reference: AccountReference; readonly code?: string; readonly label?: string; readonly type: string; readonly roles: readonly string[]; readonly amount: number; readonly balance: number; }>[]; latestPeriod: number; latestDate?: string; coveredMonths: number; total: number; balance: number; monthlyAverage: number; totalForRole: (role: string) => number; monthlyAverageForRole: (role: string) => number; shares: (role: string) => Readonly<Record<string, number>>; accountsForRole: (role: string) => readonly ForecastHistory["accounts"][number][]; amountFor: (account: AccountReference) => number; balanceFor: (account: AccountReference) => number; monthlyActivityForRole: (role: string) => readonly Readonly<{ readonly index: number; readonly date?: string; readonly amount: number; }>[] }

modules["business-base-forecast"].ForecastInvestmentOptionsForecastInvestmentOptions describes a model value used by the Business Base Forecast editor functions.

Model value shape: { name?: string; owner?: EntityReference; schedule?: ScheduleReference; triggeredBy?: TriggerReference; openingAssets?: { readonly remainingLifeYears?: number | InputReference<number> | RemainingLifeMethod; readonly preconditions?: Readonly<Record<string, InputReference<InputValue>>>; readonly accounts?: AccountReference | readonly AccountReference[]; }; accountChoices?: { readonly depreciableAssets?: AccountReference | readonly AccountReference[]; readonly depreciationExpense?: AccountReference | readonly AccountReference[]; readonly accumulatedDepreciation?: AccountReference | readonly AccountReference[]; }; currencyUnit?: number }

modules["business-base-forecast"].ForecastMethodContextThe engine context plus forecast facts; legacy aliases remain available.

Model value shape: { forecast: ForecastDomainContext; history: ForecastHistory; context: CalculationContext; assetAccounts?: readonly AccountReference[]; depreciationAccounts?: readonly AccountReference[]; accumulatedDepreciationAccounts?: readonly AccountReference[]; currency: deccf.Currency; sourceCurrency: deccf.Currency; time: deccf.TimeContext; metricPeriod?: Readonly<{ readonly startIndex: number; readonly endIndex: number; readonly startDate: deccf.DateString; readonly endDate: deccf.DateString; readonly length: number; }>; owner?: EntityReference; amount?: number; source?: deccf.TriggerSource; accountsFor: (owner?: EntityReference) => readonly AccountReference[]; sourceFor: (flow: deccf.CashflowReference) => deccf.TriggerSource | null; get: { <T extends InputValue>(reference: InputReference<T>): T; (reference: deccf.FieldReference): number; (reference: AccountReference): number; (reference: deccf.CashflowReference): Money; <T = number>(reference: deccf.CalculationReference): T; (reference: deccf.CalculationProjectionReference): unknown; (reference: deccf.ExpressionReference): number | Money; <T extends InputValue>(reference: deccf.AgreementTermReference<T>): T; }; … 17 more fields }

modules["business-base-forecast"].ForecastNumericFormulaValueForecastNumericFormulaValue describes a model value used by the Business Base Forecast editor functions.

Model value shape: number | InputReference<number> | ((context: ForecastMethodContext) => number)

modules["business-base-forecast"].RemainingLifeMethodRemainingLifeMethod describes a model value used by the Business Base Forecast editor functions.

Model value shape: ((context: ForecastMethodContext) => number) & { readonly preconditions?: Readonly<Record<string, InputReference<InputValue>>>; }

Financial Formulas module

Select this module in model settings to use its names in the portal model editor (modules["financial-formulas"]).

Model editor namePurpose and model value shape
modules["financial-formulas"].accountingaccounting is a model value for accounting in the Financial Formulas editor.

Readonly<{ openingDebit(options: { readonly account: AccountReference; }): Formula; openingCredit(options: { readonly account: AccountReference; }): Formula; }>

const { accounting } = modules["financial-formulas"];

modules["financial-formulas"].accounting.openingCreditaccounting.openingCredit provides opening credit in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly account: AccountReference; }): Formula

const { openingCredit } = modules["financial-formulas"].accounting;

modules["financial-formulas"].accounting.openingDebitaccounting.openingDebit provides opening debit in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly account: AccountReference; }): Formula

const { openingDebit } = modules["financial-formulas"].accounting;

modules["financial-formulas"].amountamount is a model value for amount in the Financial Formulas editor.

Readonly<{ shareOf<C = CalculationContext>(options: { readonly amount: AmountSource<C>; readonly share: NumberSource<C>; }): Formula<C>; atPeriods<C = CalculationContext>(options: { readonly values: Readonly<Record<number, AmountSource<C>>>; readonly otherwise?: AmountSource<C>; }): Formula<C>; during<C = CalculationContext>(options: { readonly amount: AmountSource<C>; readonly fromPeriod: number | InputReference<number> | InputProjectionReference<number>; readonly toPeriodExclusive: number | InputReference<number> | InputProjectionReference<number>; readonly otherwise?: AmountSource<C>; }): Formula<C>; }>

const { amount } = modules["financial-formulas"];

modules["financial-formulas"].amount.atPeriodsamount.atPeriods provides at periods in the Financial Formulas model editor. Use it when a model needs this operation.

<C = CalculationContext>(options: { readonly values: Readonly<Record<number, AmountSource<C>>>; readonly otherwise?: AmountSource<C>; }): Formula<C>

const { atPeriods } = modules["financial-formulas"].amount;

modules["financial-formulas"].amount.duringamount.during provides during in the Financial Formulas model editor. Use it when a model needs this operation.

<C = CalculationContext>(options: { readonly amount: AmountSource<C>; readonly fromPeriod: number | InputReference<number> | InputProjectionReference<number>; readonly toPeriodExclusive: number | InputReference<number> | InputProjectionReference<number>; readonly otherwise?: AmountSource<C>; }): Formula<C>

const { during } = modules["financial-formulas"].amount;

modules["financial-formulas"].amount.shareOfamount.shareOf provides share of in the Financial Formulas model editor. Use it when a model needs this operation.

<C = CalculationContext>(options: { readonly amount: AmountSource<C>; readonly share: NumberSource<C>; }): Formula<C>

const { formulas } = modules["financial-formulas"];

const paymentAmount = formulas.amount.shareOf({
  amount: monthlyIncome,
  share: paymentShare,
});

const payment = cashflow({
  dynamic:true,
  owner: borrower,
  direction: outflow,
  schedule: schedule.monthly(),
  amount: (ctx) => paymentAmount(ctx),
});

modules["financial-formulas"].businessbusiness is a model value for business in the Financial Formulas editor.

Readonly<{ operatingResult(options: { readonly units: NumberSource; readonly price: AmountSource; readonly variableCost: AmountSource; readonly fixedCost: AmountSource; }): Formula; breakEvenUnits(options: { readonly price: AmountSource; readonly variableCost: AmountSource; readonly fixedCost: AmountSource; }): MetricDeclaration; cashRunway(options: { readonly cash: AmountSource; readonly inflow: AmountSource; readonly outflow: AmountSource; }): MetricDeclaration; ratio(options: { readonly numerator: NumberSource; readonly denominator: NumberSource; }): MetricDeclaration; }>

const { business } = modules["financial-formulas"];

modules["financial-formulas"].business.breakEvenUnitsbusiness.breakEvenUnits provides break even units in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly price: AmountSource; readonly variableCost: AmountSource; readonly fixedCost: AmountSource; }): MetricDeclaration

const { breakEvenUnits } = modules["financial-formulas"].business;

modules["financial-formulas"].business.cashRunwaybusiness.cashRunway provides cash runway in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly cash: AmountSource; readonly inflow: AmountSource; readonly outflow: AmountSource; }): MetricDeclaration

const { cashRunway } = modules["financial-formulas"].business;

modules["financial-formulas"].business.operatingResultbusiness.operatingResult provides operating result in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly units: NumberSource; readonly price: AmountSource; readonly variableCost: AmountSource; readonly fixedCost: AmountSource; }): Formula

const { operatingResult } = modules["financial-formulas"].business;

modules["financial-formulas"].business.ratiobusiness.ratio provides ratio in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly numerator: NumberSource; readonly denominator: NumberSource; }): MetricDeclaration

const { ratio } = modules["financial-formulas"].business;

modules["financial-formulas"].financingfinancing is a model value for financing in the Financial Formulas editor.

Readonly<{ interestOnOpeningBalance<C = CalculationContext>(options: { readonly balance: AmountSource<C>; readonly annualRate: NumberSource<C>; }): Formula<C>; annuityPayment<C = CalculationContext>(options: { readonly principal: AmountSource<C>; readonly periodRate: NumberSource<C>; readonly payments: number | InputReference<number> | InputProjectionReference<number>; readonly frequency?: number; }): Formula<C>; principalFromBalance<C = CalculationContext>(options: { readonly balance: AmountSource<C>; readonly annualShare: NumberSource<C>; }): Formula<C>; }>

const { financing } = modules["financial-formulas"];

modules["financial-formulas"].financing.annuityPaymentfinancing.annuityPayment provides annuity payment in the Financial Formulas model editor. Use it when a model needs this operation.

<C = CalculationContext>(options: { readonly principal: AmountSource<C>; readonly periodRate: NumberSource<C>; readonly payments: number | InputReference<number> | InputProjectionReference<number>; readonly frequency?: number; }): Formula<C>

const { annuityPayment } = modules["financial-formulas"].financing;

modules["financial-formulas"].financing.interestOnOpeningBalancefinancing.interestOnOpeningBalance provides interest on opening balance in the Financial Formulas model editor. Use it when a model needs this operation.

<C = CalculationContext>(options: { readonly balance: AmountSource<C>; readonly annualRate: NumberSource<C>; }): Formula<C>

const { interestOnOpeningBalance } = modules["financial-formulas"].financing;

modules["financial-formulas"].financing.principalFromBalancefinancing.principalFromBalance provides principal from balance in the Financial Formulas model editor. Use it when a model needs this operation.

<C = CalculationContext>(options: { readonly balance: AmountSource<C>; readonly annualShare: NumberSource<C>; }): Formula<C>

const { principalFromBalance } = modules["financial-formulas"].financing;

modules["financial-formulas"].formulasformulas is a model value for formulas in the Financial Formulas editor.

Readonly<{ readonly amount: typeof amount; readonly accounting: typeof accounting; readonly business: typeof business; readonly dates: Readonly<{ readonly monthDistance: typeof monthDistance; readonly shiftMonth: typeof shiftMonth; }>; readonly financing: typeof financing; readonly growth: typeof growth; readonly metrics: typeof metrics; readonly rates: typeof rates; readonly savings: typeof savings; readonly snapshots: typeof snapshots; readonly series: typeof series; readonly solve: typeof solve; readonly usage: typeof usage; readonly valuation: typeof valuation; readonly workingCapital: typeof workingCapital; readonly withdrawals: typeof withdrawals; }>

const { formulas } = modules["financial-formulas"];

modules["financial-formulas"].formulas.accounting.openingCreditformulas.accounting.openingCredit provides opening credit in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly account: AccountReference; }): Formula

const { openingCredit } = modules["financial-formulas"].formulas.accounting;

modules["financial-formulas"].formulas.accounting.openingDebitformulas.accounting.openingDebit provides opening debit in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly account: AccountReference; }): Formula

const { openingDebit } = modules["financial-formulas"].formulas.accounting;

modules["financial-formulas"].formulas.amount.atPeriodsformulas.amount.atPeriods provides at periods in the Financial Formulas model editor. Use it when a model needs this operation.

<C = CalculationContext>(options: { readonly values: Readonly<Record<number, AmountSource<C>>>; readonly otherwise?: AmountSource<C>; }): Formula<C>

const { atPeriods } = modules["financial-formulas"].formulas.amount;

modules["financial-formulas"].formulas.amount.duringformulas.amount.during provides during in the Financial Formulas model editor. Use it when a model needs this operation.

<C = CalculationContext>(options: { readonly amount: AmountSource<C>; readonly fromPeriod: number | InputReference<number> | InputProjectionReference<number>; readonly toPeriodExclusive: number | InputReference<number> | InputProjectionReference<number>; readonly otherwise?: AmountSource<C>; }): Formula<C>

const { during } = modules["financial-formulas"].formulas.amount;

modules["financial-formulas"].formulas.amount.shareOfformulas.amount.shareOf provides share of in the Financial Formulas model editor. Use it when a model needs this operation.

<C = CalculationContext>(options: { readonly amount: AmountSource<C>; readonly share: NumberSource<C>; }): Formula<C>

const { formulas } = modules["financial-formulas"];

const paymentAmount = formulas.amount.shareOf({
  amount: monthlyIncome,
  share: paymentShare,
});

const payment = cashflow({
  dynamic:true,
  owner: borrower,
  direction: outflow,
  schedule: schedule.monthly(),
  amount: (ctx) => paymentAmount(ctx),
});

modules["financial-formulas"].formulas.business.breakEvenUnitsformulas.business.breakEvenUnits provides break even units in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly price: AmountSource; readonly variableCost: AmountSource; readonly fixedCost: AmountSource; }): MetricDeclaration

const { breakEvenUnits } = modules["financial-formulas"].formulas.business;

modules["financial-formulas"].formulas.business.cashRunwayformulas.business.cashRunway provides cash runway in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly cash: AmountSource; readonly inflow: AmountSource; readonly outflow: AmountSource; }): MetricDeclaration

const { cashRunway } = modules["financial-formulas"].formulas.business;

modules["financial-formulas"].formulas.business.operatingResultformulas.business.operatingResult provides operating result in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly units: NumberSource; readonly price: AmountSource; readonly variableCost: AmountSource; readonly fixedCost: AmountSource; }): Formula

const { operatingResult } = modules["financial-formulas"].formulas.business;

modules["financial-formulas"].formulas.business.ratioformulas.business.ratio provides ratio in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly numerator: NumberSource; readonly denominator: NumberSource; }): MetricDeclaration

const { ratio } = modules["financial-formulas"].formulas.business;

modules["financial-formulas"].formulas.dates.monthDistanceCounts signed calendar months from from to to, calculated as the difference between their year/month positions. Both required arguments must be strings containing a valid YYYY-MM or YYYY-MM-DD calendar date in years 0001-9999; leap days are checked. Days do not affect the count: January 31 to February 1 is 1, the reverse is -1, and any two dates in the same month give 0. Returns an integer number of months, with no rounding, elapsed-day conversion or model-period conversion. Invalid formats, calendar dates and argument types reject with DECCF_FORMULA_VALUE. Available as formulas.dates.monthDistance and monthDistance in Financial formulas.

(from: string, to: string): number

const months = modules["financial-formulas"].formulas.dates.monthDistance("2026-12-31", "2027-02-01");
// months is 2; reversing the dates gives -2.

modules["financial-formulas"].formulas.dates.shiftMonthShifts a calendar month by a required integer offset and returns a YYYY-MM string. The required period accepts a valid YYYY-MM or YYYY-MM-DD date in years 0001-9999; full dates are validated including leap days, then their day is ignored. Positive offsets move forward, negative offsets move backward, and zero keeps the input month. The result always omits the day, including a January 31 shifted to February. Invalid dates/types, noninteger offsets and shifted years outside 0001-9999 reject with DECCF_FORMULA_VALUE. Existing YYYY-MM calls retain their result format and legacy support for year 0000 only when the shifted result is in 0001-9999. Full dates with year 0000 are invalid. Available as formulas.dates.shiftMonth and shiftMonth in Financial formulas.

(period: string, offset: number): string

const invoiceMonth = modules["financial-formulas"].formulas.dates.shiftMonth("2026-12-31", 2);
// invoiceMonth is "2027-02"; the day is ignored after date validation.

modules["financial-formulas"].formulas.financing.annuityPaymentformulas.financing.annuityPayment provides annuity payment in the Financial Formulas model editor. Use it when a model needs this operation.

<C = CalculationContext>(options: { readonly principal: AmountSource<C>; readonly periodRate: NumberSource<C>; readonly payments: number | InputReference<number> | InputProjectionReference<number>; readonly frequency?: number; }): Formula<C>

const { annuityPayment } = modules["financial-formulas"].formulas.financing;

modules["financial-formulas"].formulas.financing.interestOnOpeningBalanceformulas.financing.interestOnOpeningBalance provides interest on opening balance in the Financial Formulas model editor. Use it when a model needs this operation.

<C = CalculationContext>(options: { readonly balance: AmountSource<C>; readonly annualRate: NumberSource<C>; }): Formula<C>

const { interestOnOpeningBalance } = modules["financial-formulas"].formulas.financing;

modules["financial-formulas"].formulas.financing.principalFromBalanceformulas.financing.principalFromBalance provides principal from balance in the Financial Formulas model editor. Use it when a model needs this operation.

<C = CalculationContext>(options: { readonly balance: AmountSource<C>; readonly annualShare: NumberSource<C>; }): Formula<C>

const { principalFromBalance } = modules["financial-formulas"].formulas.financing;

modules["financial-formulas"].formulas.growth.annualStepformulas.growth.annualStep provides annual step in the Financial Formulas model editor. Use it when a model needs this operation.

<C = CalculationContext>(options: { readonly base: AmountSource<C>; readonly annualRate: NumberSource<C>; readonly elapsedPeriods?: NumberSource<C>; }): Formula<C>

const { annualStep } = modules["financial-formulas"].formulas.growth;

modules["financial-formulas"].formulas.growth.compoundformulas.growth.compound provides compound in the Financial Formulas model editor. Use it when a model needs this operation.

<C = CalculationContext>(options: { readonly base: AmountSource<C>; readonly periodRate: NumberSource<C>; readonly elapsedPeriods?: NumberSource<C>; }): Formula<C>

const monthlyRate = formulas.rates.period({ annualRate, convention: "effective" });

const incomeAtMonth = formulas.growth.compound({
  base: startingIncome,
  periodRate: monthlyRate,
  elapsedPeriods: (ctx) => ctx.time.index,
});

modules["financial-formulas"].formulas.growth.decayformulas.growth.decay provides decay in the Financial Formulas model editor. Use it when a model needs this operation.

<C = CalculationContext>(options: { readonly base: AmountSource<C>; readonly lossRate: NumberSource<C>; readonly elapsedPeriods?: NumberSource<C>; }): Formula<C>

const { decay } = modules["financial-formulas"].formulas.growth;

modules["financial-formulas"].formulas.metrics.cumulativeformulas.metrics.cumulative provides cumulative in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly flows: readonly CashflowReference[]; readonly initial?: AmountSource; readonly sign?: 1 | -1; }): MetricDeclaration

const { cumulative } = modules["financial-formulas"].formulas.metrics;

modules["financial-formulas"].formulas.metrics.discountedCashflowsformulas.metrics.discountedCashflows provides discounted cashflows in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly cashflows: readonly { readonly flow: CashflowReference; readonly placement: "start" | "mid" | "end"; }[]; readonly annualRate: NumberSource; }): Readonly<{ readonly npv: MetricDeclaration; readonly paybackPeriod: MetricDeclaration; }>

const projectValue = formulas.metrics.discountedCashflows({
  cashflows: [
    { flow: investment, placement: "start" },
    { flow: benefits, placement: "start" },
  ],
  annualRate: discountRate,
});

modules["financial-formulas"].formulas.rates.periodformulas.rates.period provides period in the Financial Formulas model editor. Use it when a model needs this operation.

<C = CalculationContext>(options: { readonly annualRate: NumberSource<C>; readonly convention?: "nominal" | "effective"; readonly compoundsPerYear?: number | InputReference<number> | InputProjectionReference<number>; }): Formula<C>

const monthlyRate = formulas.rates.period({ annualRate, convention: "effective" });

const incomeAtMonth = formulas.growth.compound({
  base: startingIncome,
  periodRate: monthlyRate,
  elapsedPeriods: (ctx) => ctx.time.index,
});

modules["financial-formulas"].formulas.savings.futureValueformulas.savings.futureValue provides future value in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly openingBalance: AmountSource; readonly contribution?: AmountSource; readonly periodRate: NumberSource; readonly periods: NumberSource; readonly placement?: "start" | "end"; }): Formula

const { futureValue } = modules["financial-formulas"].formulas.savings;

modules["financial-formulas"].formulas.savings.requiredContributionformulas.savings.requiredContribution provides required contribution in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly openingBalance: AmountSource; readonly target: AmountSource; readonly periodRate: NumberSource; readonly periods: NumberSource; readonly placement?: "start" | "end"; }): Formula

const { formulas } = modules["financial-formulas"];

const { savingsPlan } = modules.savings;

const periodRate = formulas.rates.period({ annualRate, convention: "effective" });

const goalContribution = formulas.savings.requiredContribution({
  openingBalance,
  target,
  periodRate,
  periods: (ctx) => ctx.time.index + 1,
});

const fund = savingsPlan({
  openingBalance,
  annualRate,
  contribution: monthlyContribution,
  contributionPlacement: "end",
});

modules["financial-formulas"].formulas.series.pulseAmount in one selected zero-based period; zero in every other period.

<C = CalculationContext>(options: { readonly atPeriod: NumberSource<C>; readonly amount: AmountSource<C>; }): Formula<C>

const { pulse } = modules["financial-formulas"].formulas.series;

modules["financial-formulas"].formulas.series.rateScenarioChanges use zero-based period indexes; a distribution shock is drawn once per trial.

(options: { readonly name?: string; readonly base: NumberSource; readonly changes?: readonly { readonly fromPeriod: NumberSource; readonly change: NumberSource; }[]; readonly shock?: NumberSource; readonly floor?: NumberSource; }): CalculationReference

const { rateScenario } = modules["financial-formulas"].formulas.series;

modules["financial-formulas"].formulas.series.runningDeclare a numeric running sum, minimum, maximum or product over every model period. The required source and optional initial accept numbers, Money, declared inputs, calculation references/projections, expressions and compatible callbacks. Operation defaults to "sum"; name defaults to "running". Source is read in each period. An explicit initial is read only in period zero and combined before that first source; omission returns the first source unchanged. Later periods combine the previous accumulator with the current source. Each run and repeated item starts afresh. Product sources are per-period factors (1.02 for a 2% increase); initial: 1 creates a dimensionless index, or an amount seeds an indexed amount. Zero and negative finite values are accepted. Money becomes its numeric amount; no rounding, currency conversion or rate annualization is applied. Phase defaults to "periodEnd" for end-of-period/flow dependencies and "period" otherwise; an explicit phase must support reading all dependencies. Sources carry their declared dependencies; opaque callbacks must declare their own dependencies. Returns a CalculationReference with a numeric result in each period. A missing source or unsupported operation rejects with DECCF_FORMULA_CONFIG. A nonfinite or nonnumeric source/initial, or product overflow, rejects with DECCF_FORMULA_VALUE; Money must use the model currency. No account or payment is created.

(options: { readonly name?: string; readonly source: AmountSource; readonly operation?: "sum" | "min" | "max" | "product"; readonly initial?: AmountSource; readonly phase?: "period" | "periodEnd"; }): CalculationReference

const cash = formulas.series.running({
  name:"cash", source:expr.netCash(owner), operation:"sum", initial:opening,
});

const minimum = formulas.series.running({
  name:"minimum", source:cash, operation:"min", initial:opening,
});

modules["financial-formulas"].formulas.snapshots.atPeriodformulas.snapshots.atPeriod provides at period in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly calculation: CalculationReference; readonly period: number | InputReference<number> | InputProjectionReference<number>; }): Readonly<{ readonly field: FieldReference; readonly metric: MetricDeclaration; }>

const { atPeriod } = modules["financial-formulas"].formulas.snapshots;

modules["financial-formulas"].formulas.snapshots.recordPublish a named record of existing sources; explicit types retain Money and missing cells.

(options: RecordSnapshotOptions): CalculationReference

const detail = formulas.snapshots.record({
  name: 'detail',
  fields: { name: assetName, value: assetValue, payment: actualPayment },
  resultType: { name: 'text', value: 'money', payment: 'money' },
});

modules["financial-formulas"].formulas.snapshots.selectSelect a safe path in a calculated record; a missing key rejects unless fallback is explicit.

(options: RecordSelectionOptions): CalculationReference

const charge = formulas.snapshots.select({
  name: 'charge', source: annualCharges,
  path: ['perProperty', homeId, 'total'], resultType: 'money',
  fallback: money(0, currencies.SEK),
});

modules["financial-formulas"].formulas.solve.bisectSolve a continuous, bracketed formula in the current period; this does not rerun a model.

(options: { readonly name?: string; readonly variable: FormulaVariableReference; readonly expression: AmountSource; readonly target: AmountSource; readonly lower: AmountSource; readonly upper: AmountSource; readonly tolerance?: number; readonly maxIterations?: number; }): CalculationReference

const { bisect } = modules["financial-formulas"].formulas.solve;

modules["financial-formulas"].formulas.solve.variableformulas.solve.variable provides variable in the Financial Formulas model editor. Use it when a model needs this operation.

(name: string): FormulaVariableReference

const { variable } = modules["financial-formulas"].formulas.solve;

modules["financial-formulas"].formulas.usage.costformulas.usage.cost provides cost in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly quantity: NumberSource; readonly unitPrice: AmountSource; }): Formula

const { cost } = modules["financial-formulas"].formulas.usage;

modules["financial-formulas"].formulas.usage.fromEfficiencyformulas.usage.fromEfficiency provides from efficiency in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly quantity: NumberSource; readonly unitsPerItem: NumberSource; }): Formula

const { fromEfficiency } = modules["financial-formulas"].formulas.usage;

modules["financial-formulas"].formulas.usage.fromIntensityformulas.usage.fromIntensity provides from intensity in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly quantity: NumberSource; readonly usage: NumberSource; readonly per: NumberSource; }): Formula

const { fromIntensity } = modules["financial-formulas"].formulas.usage;

modules["financial-formulas"].formulas.valuation.presentValueformulas.valuation.presentValue provides present value in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly amount: AmountSource; readonly annualRate: NumberSource; readonly elapsedYears: NumberSource; }): Formula

const { presentValue } = modules["financial-formulas"].formulas.valuation;

modules["financial-formulas"].formulas.valuation.realValueformulas.valuation.realValue provides real value in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly nominal: AmountSource; readonly priceIndex: NumberSource; }): Formula

const { realValue } = modules["financial-formulas"].formulas.valuation;

modules["financial-formulas"].formulas.withdrawals.byDivisorformulas.withdrawals.byDivisor provides by divisor in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly divisor: NumberSource; }): Formula<any>

const { byDivisor } = modules["financial-formulas"].formulas.withdrawals;

modules["financial-formulas"].formulas.workingCapital.cycleDaysformulas.workingCapital.cycleDays provides cycle days in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly inventoryDays: NumberSource; readonly receivableDays: NumberSource; readonly payableDays: NumberSource; }): Formula

const { cycleDays } = modules["financial-formulas"].formulas.workingCapital;

modules["financial-formulas"].formulas.workingCapital.fundingCostformulas.workingCapital.fundingCost provides funding cost in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly balance: AmountSource; readonly annualRate: NumberSource; readonly periodsPerYear?: NumberSource; }): Formula

const { fundingCost } = modules["financial-formulas"].formulas.workingCapital;

modules["financial-formulas"].formulas.workingCapital.netBalanceformulas.workingCapital.netBalance provides net balance in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly dailySales: AmountSource; readonly dailyPurchases: AmountSource; readonly inventoryDays: NumberSource; readonly receivableDays: NumberSource; readonly payableDays: NumberSource; }): Formula

const { netBalance } = modules["financial-formulas"].formulas.workingCapital;

modules["financial-formulas"].formulas.workingCapital.unpaidShareformulas.workingCapital.unpaidShare provides unpaid share in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly paymentDays: NumberSource; readonly periodDays: NumberSource; }): Formula

const { unpaidShare } = modules["financial-formulas"].formulas.workingCapital;

modules["financial-formulas"].formulas.workingCapital.vat.netformulas.workingCapital.vat.net provides net in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly sales: AmountSource; readonly purchases: AmountSource; readonly rate: NumberSource; }): Formula

const { net } = modules["financial-formulas"].formulas.workingCapital.vat;

modules["financial-formulas"].growthgrowth is a model value for growth in the Financial Formulas editor.

Readonly<{ compound<C = CalculationContext>(options: { readonly base: AmountSource<C>; readonly periodRate: NumberSource<C>; readonly elapsedPeriods?: NumberSource<C>; }): Formula<C>; annualStep<C = CalculationContext>(options: { readonly base: AmountSource<C>; readonly annualRate: NumberSource<C>; readonly elapsedPeriods?: NumberSource<C>; }): Formula<C>; decay<C = CalculationContext>(options: { readonly base: AmountSource<C>; readonly lossRate: NumberSource<C>; readonly elapsedPeriods?: NumberSource<C>; }): Formula<C>; }>

const { growth } = modules["financial-formulas"];

modules["financial-formulas"].growth.annualStepgrowth.annualStep provides annual step in the Financial Formulas model editor. Use it when a model needs this operation.

<C = CalculationContext>(options: { readonly base: AmountSource<C>; readonly annualRate: NumberSource<C>; readonly elapsedPeriods?: NumberSource<C>; }): Formula<C>

const { annualStep } = modules["financial-formulas"].growth;

modules["financial-formulas"].growth.compoundgrowth.compound provides compound in the Financial Formulas model editor. Use it when a model needs this operation.

<C = CalculationContext>(options: { readonly base: AmountSource<C>; readonly periodRate: NumberSource<C>; readonly elapsedPeriods?: NumberSource<C>; }): Formula<C>

const monthlyRate = formulas.rates.period({ annualRate, convention: "effective" });

const incomeAtMonth = formulas.growth.compound({
  base: startingIncome,
  periodRate: monthlyRate,
  elapsedPeriods: (ctx) => ctx.time.index,
});

modules["financial-formulas"].growth.decaygrowth.decay provides decay in the Financial Formulas model editor. Use it when a model needs this operation.

<C = CalculationContext>(options: { readonly base: AmountSource<C>; readonly lossRate: NumberSource<C>; readonly elapsedPeriods?: NumberSource<C>; }): Formula<C>

const { decay } = modules["financial-formulas"].growth;

modules["financial-formulas"].metricsmetrics is a model value for metrics in the Financial Formulas editor.

Readonly<{ cumulative(options: { readonly flows: readonly CashflowReference[]; readonly initial?: AmountSource; readonly sign?: 1 | -1; }): MetricDeclaration; discountedCashflows(options: { readonly cashflows: readonly { readonly flow: CashflowReference; readonly placement: "start" | "mid" | "end"; }[]; readonly annualRate: NumberSource; }): Readonly<{ readonly npv: MetricDeclaration; readonly paybackPeriod: MetricDeclaration; }>; }>

const { metrics } = modules["financial-formulas"];

modules["financial-formulas"].metrics.cumulativemetrics.cumulative provides cumulative in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly flows: readonly CashflowReference[]; readonly initial?: AmountSource; readonly sign?: 1 | -1; }): MetricDeclaration

const { cumulative } = modules["financial-formulas"].metrics;

modules["financial-formulas"].metrics.discountedCashflowsmetrics.discountedCashflows provides discounted cashflows in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly cashflows: readonly { readonly flow: CashflowReference; readonly placement: "start" | "mid" | "end"; }[]; readonly annualRate: NumberSource; }): Readonly<{ readonly npv: MetricDeclaration; readonly paybackPeriod: MetricDeclaration; }>

const projectValue = formulas.metrics.discountedCashflows({
  cashflows: [
    { flow: investment, placement: "start" },
    { flow: benefits, placement: "start" },
  ],
  annualRate: discountRate,
});

modules["financial-formulas"].monthDistanceCounts signed calendar months from from to to, calculated as the difference between their year/month positions. Both required arguments must be strings containing a valid YYYY-MM or YYYY-MM-DD calendar date in years 0001-9999; leap days are checked. Days do not affect the count: January 31 to February 1 is 1, the reverse is -1, and any two dates in the same month give 0. Returns an integer number of months, with no rounding, elapsed-day conversion or model-period conversion. Invalid formats, calendar dates and argument types reject with DECCF_FORMULA_VALUE. Available as formulas.dates.monthDistance and monthDistance in Financial formulas.

(from: string, to: string): number

const months = modules["financial-formulas"].monthDistance("2026-12-31", "2027-02-01");
// months is 2; reversing the dates gives -2.

modules["financial-formulas"].ratesrates is a model value for rates in the Financial Formulas editor.

Readonly<{ period<C = CalculationContext>(options: { readonly annualRate: NumberSource<C>; readonly convention?: "nominal" | "effective"; readonly compoundsPerYear?: number | InputReference<number> | InputProjectionReference<number>; }): Formula<C>; }>

const { rates } = modules["financial-formulas"];

modules["financial-formulas"].rates.periodrates.period provides period in the Financial Formulas model editor. Use it when a model needs this operation.

<C = CalculationContext>(options: { readonly annualRate: NumberSource<C>; readonly convention?: "nominal" | "effective"; readonly compoundsPerYear?: number | InputReference<number> | InputProjectionReference<number>; }): Formula<C>

const monthlyRate = formulas.rates.period({ annualRate, convention: "effective" });

const incomeAtMonth = formulas.growth.compound({
  base: startingIncome,
  periodRate: monthlyRate,
  elapsedPeriods: (ctx) => ctx.time.index,
});

modules["financial-formulas"].savingssavings is a model value for savings in the Financial Formulas editor.

Readonly<{ futureValue(options: { readonly openingBalance: AmountSource; readonly contribution?: AmountSource; readonly periodRate: NumberSource; readonly periods: NumberSource; readonly placement?: "start" | "end"; }): Formula; requiredContribution(options: { readonly openingBalance: AmountSource; readonly target: AmountSource; readonly periodRate: NumberSource; readonly periods: NumberSource; readonly placement?: "start" | "end"; }): Formula; }>

const { savings } = modules["financial-formulas"];

modules["financial-formulas"].savings.futureValuesavings.futureValue provides future value in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly openingBalance: AmountSource; readonly contribution?: AmountSource; readonly periodRate: NumberSource; readonly periods: NumberSource; readonly placement?: "start" | "end"; }): Formula

const { futureValue } = modules["financial-formulas"].savings;

modules["financial-formulas"].savings.requiredContributionsavings.requiredContribution provides required contribution in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly openingBalance: AmountSource; readonly target: AmountSource; readonly periodRate: NumberSource; readonly periods: NumberSource; readonly placement?: "start" | "end"; }): Formula

const { formulas } = modules["financial-formulas"];

const { savingsPlan } = modules.savings;

const periodRate = formulas.rates.period({ annualRate, convention: "effective" });

const goalContribution = formulas.savings.requiredContribution({
  openingBalance,
  target,
  periodRate,
  periods: (ctx) => ctx.time.index + 1,
});

const fund = savingsPlan({
  openingBalance,
  annualRate,
  contribution: monthlyContribution,
  contributionPlacement: "end",
});

modules["financial-formulas"].seriesseries is a model value for series in the Financial Formulas editor.

Readonly<{ pulse<C = CalculationContext>(options: { readonly atPeriod: NumberSource<C>; readonly amount: AmountSource<C>; }): Formula<C>; running(options: { readonly name?: string; readonly source: AmountSource; readonly operation?: "sum" | "min" | "max" | "product"; readonly initial?: AmountSource; readonly phase?: "period" | "periodEnd"; }): CalculationReference; rateScenario(options: { readonly name?: string; readonly base: NumberSource; readonly changes?: readonly { readonly fromPeriod: NumberSource; readonly change: NumberSource; }[]; readonly shock?: NumberSource; readonly floor?: NumberSource; }): CalculationReference; }>

const { series } = modules["financial-formulas"];

modules["financial-formulas"].series.pulseAmount in one selected zero-based period; zero in every other period.

<C = CalculationContext>(options: { readonly atPeriod: NumberSource<C>; readonly amount: AmountSource<C>; }): Formula<C>

const { pulse } = modules["financial-formulas"].series;

modules["financial-formulas"].series.rateScenarioChanges use zero-based period indexes; a distribution shock is drawn once per trial.

(options: { readonly name?: string; readonly base: NumberSource; readonly changes?: readonly { readonly fromPeriod: NumberSource; readonly change: NumberSource; }[]; readonly shock?: NumberSource; readonly floor?: NumberSource; }): CalculationReference

const inflation = modules['financial-formulas'].series.rateScenario({
  name: 'monthlyInflation',
  base: 0.002,
  changes: [{ fromPeriod: 12, change: 0.001 }],
});

const indexedRent = modules['financial-formulas'].series.running({
  name: 'indexedRent',
  source: deccf.expr.add(1, inflation),
  operation: 'product',
  initial: 10000,
});

return deccf.defineModel({
  currency: deccf.currencies.SEK,
  timeline: deccf.periods.monthly({ from: '2027-01', count: 24 }),
  calculations: { inflation, indexedRent },
  metrics: { rent: deccf.metric({ value: indexedRent }) },
});

modules["financial-formulas"].series.runningDeclare a numeric running sum, minimum, maximum or product over every model period. The required source and optional initial accept numbers, Money, declared inputs, calculation references/projections, expressions and compatible callbacks. Operation defaults to "sum"; name defaults to "running". Source is read in each period. An explicit initial is read only in period zero and combined before that first source; omission returns the first source unchanged. Later periods combine the previous accumulator with the current source. Each run and repeated item starts afresh. Product sources are per-period factors (1.02 for a 2% increase); initial: 1 creates a dimensionless index, or an amount seeds an indexed amount. Zero and negative finite values are accepted. Money becomes its numeric amount; no rounding, currency conversion or rate annualization is applied. Phase defaults to "periodEnd" for end-of-period/flow dependencies and "period" otherwise; an explicit phase must support reading all dependencies. Sources carry their declared dependencies; opaque callbacks must declare their own dependencies. Returns a CalculationReference with a numeric result in each period. A missing source or unsupported operation rejects with DECCF_FORMULA_CONFIG. A nonfinite or nonnumeric source/initial, or product overflow, rejects with DECCF_FORMULA_VALUE; Money must use the model currency. No account or payment is created.

(options: { readonly name?: string; readonly source: AmountSource; readonly operation?: "sum" | "min" | "max" | "product"; readonly initial?: AmountSource; readonly phase?: "period" | "periodEnd"; }): CalculationReference

const inflation = modules['financial-formulas'].series.rateScenario({
  name: 'monthlyInflation',
  base: 0.002,
  changes: [{ fromPeriod: 12, change: 0.001 }],
});

const indexedRent = modules['financial-formulas'].series.running({
  name: 'indexedRent',
  source: deccf.expr.add(1, inflation),
  operation: 'product',
  initial: 10000,
});

return deccf.defineModel({
  currency: deccf.currencies.SEK,
  timeline: deccf.periods.monthly({ from: '2027-01', count: 24 }),
  calculations: { inflation, indexedRent },
  metrics: { rent: deccf.metric({ value: indexedRent }) },
});

modules["financial-formulas"].shiftMonthShifts a calendar month by a required integer offset and returns a YYYY-MM string. The required period accepts a valid YYYY-MM or YYYY-MM-DD date in years 0001-9999; full dates are validated including leap days, then their day is ignored. Positive offsets move forward, negative offsets move backward, and zero keeps the input month. The result always omits the day, including a January 31 shifted to February. Invalid dates/types, noninteger offsets and shifted years outside 0001-9999 reject with DECCF_FORMULA_VALUE. Existing YYYY-MM calls retain their result format and legacy support for year 0000 only when the shifted result is in 0001-9999. Full dates with year 0000 are invalid. Available as formulas.dates.shiftMonth and shiftMonth in Financial formulas.

(period: string, offset: number): string

const invoiceMonth = modules["financial-formulas"].shiftMonth("2026-12-31", 2);
// invoiceMonth is "2027-02"; the day is ignored after date validation.

modules["financial-formulas"].snapshotssnapshots is a model value for snapshots in the Financial Formulas editor.

Readonly<{ select(options: RecordSelectionOptions): CalculationReference; record(options: RecordSnapshotOptions): CalculationReference; atPeriod(options: { readonly calculation: CalculationReference; readonly period: number | InputReference<number> | InputProjectionReference<number>; }): Readonly<{ readonly field: FieldReference; readonly metric: MetricDeclaration; }>; }>

const { snapshots } = modules["financial-formulas"];

modules["financial-formulas"].snapshots.atPeriodsnapshots.atPeriod provides at period in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly calculation: CalculationReference; readonly period: number | InputReference<number> | InputProjectionReference<number>; }): Readonly<{ readonly field: FieldReference; readonly metric: MetricDeclaration; }>

const { atPeriod } = modules["financial-formulas"].snapshots;

modules["financial-formulas"].snapshots.recordPublish a named record of existing sources; explicit types retain Money and missing cells.

(options: RecordSnapshotOptions): CalculationReference

const detail = formulas.snapshots.record({
  name: 'detail',
  fields: { name: assetName, value: assetValue, payment: actualPayment },
  resultType: { name: 'text', value: 'money', payment: 'money' },
});

modules["financial-formulas"].snapshots.selectSelect a safe path in a calculated record; a missing key rejects unless fallback is explicit.

(options: RecordSelectionOptions): CalculationReference

const charge = formulas.snapshots.select({
  name: 'charge', source: annualCharges,
  path: ['perProperty', homeId, 'total'], resultType: 'money',
  fallback: money(0, currencies.SEK),
});

modules["financial-formulas"].solvesolve is a model value for solve in the Financial Formulas editor.

Readonly<{ variable(name: string): FormulaVariableReference; bisect(options: { readonly name?: string; readonly variable: FormulaVariableReference; readonly expression: AmountSource; readonly target: AmountSource; readonly lower: AmountSource; readonly upper: AmountSource; readonly tolerance?: number; readonly maxIterations?: number; }): CalculationReference; }>

const { solve } = modules["financial-formulas"];

modules["financial-formulas"].solve.bisectSolve a continuous, bracketed formula in the current period; this does not rerun a model.

(options: { readonly name?: string; readonly variable: FormulaVariableReference; readonly expression: AmountSource; readonly target: AmountSource; readonly lower: AmountSource; readonly upper: AmountSource; readonly tolerance?: number; readonly maxIterations?: number; }): CalculationReference

const { bisect } = modules["financial-formulas"].solve;

modules["financial-formulas"].solve.variablesolve.variable provides variable in the Financial Formulas model editor. Use it when a model needs this operation.

(name: string): FormulaVariableReference

const { variable } = modules["financial-formulas"].solve;

modules["financial-formulas"].usageusage is a model value for usage in the Financial Formulas editor.

Readonly<{ fromEfficiency(options: { readonly quantity: NumberSource; readonly unitsPerItem: NumberSource; }): Formula; fromIntensity(options: { readonly quantity: NumberSource; readonly usage: NumberSource; readonly per: NumberSource; }): Formula; cost(options: { readonly quantity: NumberSource; readonly unitPrice: AmountSource; }): Formula; }>

const { usage } = modules["financial-formulas"];

modules["financial-formulas"].usage.costusage.cost provides cost in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly quantity: NumberSource; readonly unitPrice: AmountSource; }): Formula

const { cost } = modules["financial-formulas"].usage;

modules["financial-formulas"].usage.fromEfficiencyusage.fromEfficiency provides from efficiency in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly quantity: NumberSource; readonly unitsPerItem: NumberSource; }): Formula

const { fromEfficiency } = modules["financial-formulas"].usage;

modules["financial-formulas"].usage.fromIntensityusage.fromIntensity provides from intensity in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly quantity: NumberSource; readonly usage: NumberSource; readonly per: NumberSource; }): Formula

const { fromIntensity } = modules["financial-formulas"].usage;

modules["financial-formulas"].valuationvaluation is a model value for valuation in the Financial Formulas editor.

Readonly<{ realValue(options: { readonly nominal: AmountSource; readonly priceIndex: NumberSource; }): Formula; presentValue(options: { readonly amount: AmountSource; readonly annualRate: NumberSource; readonly elapsedYears: NumberSource; }): Formula; }>

const { valuation } = modules["financial-formulas"];

modules["financial-formulas"].valuation.presentValuevaluation.presentValue provides present value in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly amount: AmountSource; readonly annualRate: NumberSource; readonly elapsedYears: NumberSource; }): Formula

const { presentValue } = modules["financial-formulas"].valuation;

modules["financial-formulas"].valuation.realValuevaluation.realValue provides real value in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly nominal: AmountSource; readonly priceIndex: NumberSource; }): Formula

const { realValue } = modules["financial-formulas"].valuation;

modules["financial-formulas"].withdrawalswithdrawals is a model value for withdrawals in the Financial Formulas editor.

Readonly<{ byDivisor(options: { readonly divisor: NumberSource; }): Formula<any>; }>

const { withdrawals } = modules["financial-formulas"];

modules["financial-formulas"].withdrawals.byDivisorwithdrawals.byDivisor provides by divisor in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly divisor: NumberSource; }): Formula<any>

const { byDivisor } = modules["financial-formulas"].withdrawals;

modules["financial-formulas"].workingCapitalworkingCapital is a model value for working capital in the Financial Formulas editor.

Readonly<{ cycleDays(options: { readonly inventoryDays: NumberSource; readonly receivableDays: NumberSource; readonly payableDays: NumberSource; }): Formula; netBalance(options: { readonly dailySales: AmountSource; readonly dailyPurchases: AmountSource; readonly inventoryDays: NumberSource; readonly receivableDays: NumberSource; readonly payableDays: NumberSource; }): Formula; fundingCost(options: { readonly balance: AmountSource; readonly annualRate: NumberSource; readonly periodsPerYear?: NumberSource; }): Formula; unpaidShare(options: { readonly paymentDays: NumberSource; readonly periodDays: NumberSource; }): Formula; vat: Readonly<{ net(options: { readonly sales: AmountSource; readonly purchases: AmountSource; readonly rate: NumberSource; }): Formula; }>; }>

const { workingCapital } = modules["financial-formulas"];

modules["financial-formulas"].workingCapital.cycleDaysworkingCapital.cycleDays provides cycle days in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly inventoryDays: NumberSource; readonly receivableDays: NumberSource; readonly payableDays: NumberSource; }): Formula

const { cycleDays } = modules["financial-formulas"].workingCapital;

modules["financial-formulas"].workingCapital.fundingCostworkingCapital.fundingCost provides funding cost in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly balance: AmountSource; readonly annualRate: NumberSource; readonly periodsPerYear?: NumberSource; }): Formula

const { fundingCost } = modules["financial-formulas"].workingCapital;

modules["financial-formulas"].workingCapital.netBalanceworkingCapital.netBalance provides net balance in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly dailySales: AmountSource; readonly dailyPurchases: AmountSource; readonly inventoryDays: NumberSource; readonly receivableDays: NumberSource; readonly payableDays: NumberSource; }): Formula

const { netBalance } = modules["financial-formulas"].workingCapital;

modules["financial-formulas"].workingCapital.unpaidShareworkingCapital.unpaidShare provides unpaid share in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly paymentDays: NumberSource; readonly periodDays: NumberSource; }): Formula

const { unpaidShare } = modules["financial-formulas"].workingCapital;

modules["financial-formulas"].workingCapital.vat.networkingCapital.vat.net provides net in the Financial Formulas model editor. Use it when a model needs this operation.

(options: { readonly sales: AmountSource; readonly purchases: AmountSource; readonly rate: NumberSource; }): Formula

const { net } = modules["financial-formulas"].workingCapital.vat;

modules["financial-formulas"].AmountSourceAmountSource describes a model value used by the Financial Formulas editor functions.

Model value shape: LookupReference<number | Money | InputReference<number | Money> | CalculationReference | CalculationProjectionReference | AccountReference | CashflowReference> | number | Money | InputReference<number | Money> | InputProjectionReference<number | Money> | CalculationReference | CalculationProjectionReference | ExpressionReference | AccountReference | FieldReference | CashflowReference | FormulaVariableReference | Formula<C>

modules["financial-formulas"].BisectionResultBisectionResult describes a model value used by the Financial Formulas editor functions.

Model value shape: { value: number; converged: boolean; iterations: number; residual: number; reason: "converged" | "target-outside-bounds" | "iteration-limit" }

modules["financial-formulas"].FormulaFormula describes a model value used by the Financial Formulas editor functions.

Model value shape: ((context: C) => number) & { readonly preconditions?: Readonly<Record<string, InputReference<InputValue>>>; readonly dependsOn?: readonly (CalculationReference | CashflowReference)[]; readonly readsAccountsFrom?: readonly AccountReference[]; readonly constant?: boolean; }

modules["financial-formulas"].FormulaVariableReferenceA scoped unknown understood by solve.bisect() and the formula factories.

Model value shape: { kind: "formula-variable"; token: symbol }

modules["financial-formulas"].NumberSourceNumberSource describes a model value used by the Financial Formulas editor functions.

Model value shape: LookupReference<number | InputReference<number> | InputProjectionReference<number> | CalculationReference | CalculationProjectionReference | AccountReference> | number | InputReference<number> | InputProjectionReference<number> | CalculationReference | CalculationProjectionReference | ExpressionReference | AccountReference | FieldReference | FormulaVariableReference | Formula<C>

modules["financial-formulas"].RecordSelectionOptionsRecordSelectionOptions describes a model value used by the Financial Formulas editor functions.

Model value shape: { name: string; source: RecordSnapshotSource; path: readonly (string | ExpressionReference | InputReference<string> | InputProjectionReference<string>)[]; resultType: CalculationResultType; fallback?: RecordSnapshotSource; owner?: deccf.EntityReference | LookupReference<deccf.EntityReference>; publish?: boolean; schedule?: deccf.ScheduleReference; phase?: "period" | "periodEnd" }

modules["financial-formulas"].RecordSnapshotOptionsRecordSnapshotOptions describes a model value used by the Financial Formulas editor functions.

Model value shape: { name: string; owner?: deccf.EntityReference | LookupReference<deccf.EntityReference>; fields: Readonly<Record<string, RecordSnapshotSource>>; resultType: CalculationResultFields; publish?: boolean; schedule?: deccf.ScheduleReference; phase?: "period" | "periodEnd" }

modules["financial-formulas"].RecordSnapshotSourceRecordSnapshotSource describes a model value used by the Financial Formulas editor functions.

Model value shape: ExpressionOperand | RepeatColumnReference | null | Readonly<{[key:string]:RecordSnapshotSource}>

Loans module

Select this module in model settings to use its names in the portal model editor (modules.loans).

Model editor namePurpose and model value shape
modules.loans.annuityPaymentannuityPayment provides annuity payment in the Loans model editor. Use it when a model needs this operation.

(principal: number, periodRate: number, payments: number): number

const { annuityPayment } = modules.loans;

modules.loans.assetFinanceassetFinance provides asset finance in the Loans model editor. Use it when a model needs this operation.

(options: AssetFinanceOptions): AssetFinancePlan

const { assetFinance } = modules.loans;

modules.loans.bondbond provides bond in the Loans model editor. Use it when a model needs this operation.

(options: BondOptions): BondPlan

const { bond } = modules.loans;

modules.loans.convertibleLoanconvertibleLoan provides convertible loan in the Loans model editor. Use it when a model needs this operation.

(options: ConvertibleLoanOptions): ConvertibleLoanPlan

const { convertibleLoan } = modules.loans;

modules.loans.equityContributionequityContribution provides equity contribution in the Loans model editor. Use it when a model needs this operation.

(options: EquityContributionOptions): EquityContributionPlan

const { equityContribution } = modules.loans;

modules.loans.factoringfactoring provides factoring in the Loans model editor. Use it when a model needs this operation.

(options: FactoringOptions): FactoringPlan

const { factoring } = modules.loans;

modules.loans.financialLeasefinancialLease provides financial lease in the Loans model editor. Use it when a model needs this operation.

(options: FinancialLeaseOptions): FinancialLeasePlan

const { financialLease } = modules.loans;

modules.loans.financingGroup of reusable financing formulas available under the module.

Readonly<{ readonly assetFinance: typeof assetFinance; readonly bond: typeof bond; readonly convertibleLoan: typeof convertibleLoan; readonly equityContribution: typeof equityContribution; readonly factoring: typeof factoring; readonly financialLease: typeof financialLease; readonly grant: typeof grant; readonly installmentPurchase: typeof installmentPurchase; readonly invoicePurchase: typeof invoicePurchase; readonly operatingLease: typeof operatingLease; readonly revenueBased: typeof revenueBased; readonly revolvingCredit: typeof revolvingCredit; readonly shareholderLoan: typeof shareholderLoan; readonly termLoan: typeof termLoan; }>

const { financing } = modules.loans;

modules.loans.financing.assetFinancefinancing.assetFinance provides asset finance in the Loans model editor. Use it when a model needs this operation.

(options: AssetFinanceOptions): AssetFinancePlan

const { assetFinance } = modules.loans.financing;

modules.loans.financing.bondfinancing.bond provides bond in the Loans model editor. Use it when a model needs this operation.

(options: BondOptions): BondPlan

const { bond } = modules.loans.financing;

modules.loans.financing.convertibleLoanfinancing.convertibleLoan provides convertible loan in the Loans model editor. Use it when a model needs this operation.

(options: ConvertibleLoanOptions): ConvertibleLoanPlan

const { convertibleLoan } = modules.loans.financing;

modules.loans.financing.equityContributionfinancing.equityContribution provides equity contribution in the Loans model editor. Use it when a model needs this operation.

(options: EquityContributionOptions): EquityContributionPlan

const { equityContribution } = modules.loans.financing;

modules.loans.financing.factoringfinancing.factoring provides factoring in the Loans model editor. Use it when a model needs this operation.

(options: FactoringOptions): FactoringPlan

const { factoring } = modules.loans.financing;

modules.loans.financing.financialLeasefinancing.financialLease provides financial lease in the Loans model editor. Use it when a model needs this operation.

(options: FinancialLeaseOptions): FinancialLeasePlan

const { financialLease } = modules.loans.financing;

modules.loans.financing.grantfinancing.grant provides grant in the Loans model editor. Use it when a model needs this operation.

(options: GrantOptions): GrantPlan

const { grant } = modules.loans.financing;

modules.loans.financing.installmentPurchasefinancing.installmentPurchase provides installment purchase in the Loans model editor. Use it when a model needs this operation.

(options: InstallmentPurchaseOptions): InstallmentPurchasePlan

const { installmentPurchase } = modules.loans.financing;

modules.loans.financing.invoicePurchasefinancing.invoicePurchase provides invoice purchase in the Loans model editor. Use it when a model needs this operation.

(options: InvoicePurchaseOptions): InvoicePurchasePlan

const { invoicePurchase } = modules.loans.financing;

modules.loans.financing.operatingLeasefinancing.operatingLease provides operating lease in the Loans model editor. Use it when a model needs this operation.

(options: OperatingLeaseOptions): OperatingLeasePlan

const { operatingLease } = modules.loans.financing;

modules.loans.financing.revenueBasedfinancing.revenueBased provides revenue based in the Loans model editor. Use it when a model needs this operation.

(options: RevenueBasedOptions): RevenueBasedPlan

const { revenueBased } = modules.loans.financing;

modules.loans.financing.revolvingCreditfinancing.revolvingCredit provides revolving credit in the Loans model editor. Use it when a model needs this operation.

(options: RevolvingCreditOptions): RevolvingCreditPlan

const { revolvingCredit } = modules.loans.financing;

modules.loans.financing.shareholderLoanfinancing.shareholderLoan provides shareholder loan in the Loans model editor. Use it when a model needs this operation.

(options: TermLoanOptions): ShareholderLoanPlan

const { shareholderLoan } = modules.loans.financing;

modules.loans.financing.termLoanfinancing.termLoan provides term loan in the Loans model editor. Use it when a model needs this operation.

(options: TermLoanOptions): LoanPlan

const loanRows = input.objectArray([
  {
    id: input.id("bank-a"),
    principal: input.money(300_000, currencies.SEK),
    annualRate: input.decimal(0.06),
    start: input.integer(0),
    term: input.integer(36),
  },
  {
    id: input.id("bank-b"),
    principal: input.money(150_000, currencies.SEK),
    annualRate: input.decimal(0.075),
    start: input.integer(6),
    term: input.integer(24),
  },
]);

const row = loanRows.item;

const loanTemplate = financing.termLoan({
  owner: company,
  principal: row.data.principal,
  annualRate: row.data.annualRate,
  startPeriod: row.data.start,
  termPeriods: row.data.term,
  repayment: "annuity",
  postings: { cash, liability: bankDebt, interestExpense },
});

const bankLoans = repeat(loanRows, loanTemplate.component);

return defineModel({
  name: "Company funding plan",
  currency: currencies.SEK,
  timeline: periods.monthly({ from: "2026-01", count: 60 }),
  preconditions: { loanRows },
  entities: { company },
  accounts: { cash, bankDebt, interestExpense },
  components: { bankLoans },
});

modules.loans.formulasformulas is a model value for formulas in the Loans editor.

Readonly<{ readonly amount: typeof modules.loans.amount; readonly financing: Readonly<{ interestOnOpeningBalance(options: { readonly balance: LoanAmountSource; readonly annualRate: LoanNumberSource; }): Formula<LoanContext>; annuityPayment(options: { readonly principal: LoanAmountSource; readonly periodRate: LoanNumberSource; readonly payments: number | InputReference<number> | InputProjectionReference<number>; readonly frequency?: number; }): Formula<LoanContext>; principalFromBalance(options: { readonly balance: LoanAmountSource; readonly annualShare: LoanNumberSource; }): Formula<LoanContext>; }>; }>

const { formulas } = modules.loans;

modules.loans.formulas.amount.atPeriodsformulas.amount.atPeriods provides at periods in the Loans model editor. Use it when a model needs this operation.

<C = CalculationContext>(options: { readonly values: Readonly<Record<number, AmountSource<C>>>; readonly otherwise?: AmountSource<C>; }): Formula<C>

const { atPeriods } = modules.loans.formulas.amount;

modules.loans.formulas.amount.duringformulas.amount.during provides during in the Loans model editor. Use it when a model needs this operation.

<C = CalculationContext>(options: { readonly amount: AmountSource<C>; readonly fromPeriod: number | InputReference<number> | InputProjectionReference<number>; readonly toPeriodExclusive: number | InputReference<number> | InputProjectionReference<number>; readonly otherwise?: AmountSource<C>; }): Formula<C>

const { during } = modules.loans.formulas.amount;

modules.loans.formulas.amount.shareOfformulas.amount.shareOf provides share of in the Loans model editor. Use it when a model needs this operation.

<C = CalculationContext>(options: { readonly amount: AmountSource<C>; readonly share: NumberSource<C>; }): Formula<C>

const { formulas } = modules["financial-formulas"];

const paymentAmount = formulas.amount.shareOf({
  amount: monthlyIncome,
  share: paymentShare,
});

const payment = cashflow({
  dynamic:true,
  owner: borrower,
  direction: outflow,
  schedule: schedule.monthly(),
  amount: (ctx) => paymentAmount(ctx),
});

modules.loans.formulas.financing.annuityPaymentformulas.financing.annuityPayment provides annuity payment in the Loans model editor. Use it when a model needs this operation.

(options: { readonly principal: LoanAmountSource; readonly periodRate: LoanNumberSource; readonly payments: number | InputReference<number> | InputProjectionReference<number>; readonly frequency?: number; }): Formula<LoanContext>

const { annuityPayment } = modules.loans.formulas.financing;

modules.loans.formulas.financing.interestOnOpeningBalanceformulas.financing.interestOnOpeningBalance provides interest on opening balance in the Loans model editor. Use it when a model needs this operation.

(options: { readonly balance: LoanAmountSource; readonly annualRate: LoanNumberSource; }): Formula<LoanContext>

const { interestOnOpeningBalance } = modules.loans.formulas.financing;

modules.loans.formulas.financing.principalFromBalanceformulas.financing.principalFromBalance provides principal from balance in the Loans model editor. Use it when a model needs this operation.

(options: { readonly balance: LoanAmountSource; readonly annualShare: LoanNumberSource; }): Formula<LoanContext>

const { principalFromBalance } = modules.loans.formulas.financing;

modules.loans.grantgrant provides grant in the Loans model editor. Use it when a model needs this operation.

(options: GrantOptions): GrantPlan

const { grant } = modules.loans;

modules.loans.installmentPurchaseinstallmentPurchase provides installment purchase in the Loans model editor. Use it when a model needs this operation.

(options: InstallmentPurchaseOptions): InstallmentPurchasePlan

const { installmentPurchase } = modules.loans;

modules.loans.invoicePurchaseinvoicePurchase provides invoice purchase in the Loans model editor. Use it when a model needs this operation.

(options: InvoicePurchaseOptions): InvoicePurchasePlan

const { invoicePurchase } = modules.loans;

modules.loans.loanPeriodloanPeriod provides loan period in the Loans model editor. Use it when a model needs this operation.

(options: LoanPeriodInput): Readonly<LoanPeriodResult>

const { loanPeriod } = modules.loans;

modules.loans.loanPlanloanPlan provides loan plan in the Loans model editor. Use it when a model needs this operation.

(options: { readonly owner?: EntityReference | LookupReference<EntityReference>; readonly calendar?: Calendar; readonly openingBalance: LoanAmountSource; readonly annualRate?: LoanNumberSource; readonly rateConvention?: "nominal" | "effective"; readonly periodRate?: LoanNumberSource; readonly payment: LoanAmountSource; readonly extraPayment?: LoanAmountSource; readonly noncashExtraPayment?: LoanAmountSource; readonly drawdowns?: Readonly<{ readonly start?: LoanAmountSource; readonly end?: LoanAmountSource; }>; readonly unpaidInterest?: "capitalize" | "error"; readonly preconditions?: Readonly<Record<string, InputReference>>; readonly dependsOn?: readonly CalculationReference[]; readonly readsAccountsFrom?: readonly AccountReference[]; readonly postings?: LoanPlanPostingAccounts; }): LoanPlan

const { loanPlan, repayments } = modules.loans;

const loan = loanPlan({
  openingBalance: principal,
  annualRate: annualRateCurve,
  payment: repayments.annuity({ payments: 360 }),
});

modules.loans.operatingLeaseoperatingLease provides operating lease in the Loans model editor. Use it when a model needs this operation.

(options: OperatingLeaseOptions): OperatingLeasePlan

const { operatingLease } = modules.loans;

modules.loans.repaymentsrepayments is a model value for repayments in the Loans editor.

Readonly<{ loanToValue(options: { readonly value: LoanAmountSource; readonly principalBase: LoanAmountSource; readonly debtForLtv?: LoanAmountSource; readonly tiers: readonly Readonly<{ above: number; annualShare: number; }>[]; }): Formula<LoanContext>; select(options: { readonly selector: string | InputReference<string> | InputProjectionReference<string> | LookupReference<string>; readonly cases: Readonly<Record<string, Formula<LoanContext>>>; }): Formula<LoanContext>; settlement(options: { readonly regular: LoanAmountSource; readonly atPeriod: LoanNumberSource; }): Formula<LoanContext>; fixedPrincipal(options: { readonly amount: LoanAmountSource; }): Formula<LoanContext>; interestOnly(): Formula<LoanContext>; bullet(options: { readonly atPeriod: number | InputReference<number> | InputProjectionReference<number>; }): Formula<LoanContext>; annuity(options: { readonly payments: number | InputReference<number> | InputProjectionReference<number>; readonly firstPeriod?: number; }): Formula<LoanContext>; }>

const { repayments } = modules.loans;

modules.loans.repayments.annuityrepayments.annuity provides annuity in the Loans model editor. Use it when a model needs this operation.

(options: { readonly payments: number | InputReference<number> | InputProjectionReference<number>; readonly firstPeriod?: number; }): Formula<LoanContext>

const { loanPlan, repayments } = modules.loans;

const loan = loanPlan({
  openingBalance: principal,
  annualRate: annualRateCurve,
  payment: repayments.annuity({ payments: 360 }),
});

modules.loans.repayments.bulletrepayments.bullet provides bullet in the Loans model editor. Use it when a model needs this operation.

(options: { readonly atPeriod: number | InputReference<number> | InputProjectionReference<number>; }): Formula<LoanContext>

const { bullet } = modules.loans.repayments;

modules.loans.repayments.fixedPrincipalrepayments.fixedPrincipal provides fixed principal in the Loans model editor. Use it when a model needs this operation.

(options: { readonly amount: LoanAmountSource; }): Formula<LoanContext>

const { fixedPrincipal } = modules.loans.repayments;

modules.loans.repayments.interestOnlyrepayments.interestOnly provides interest only in the Loans model editor. Use it when a model needs this operation.

(): Formula<LoanContext>

const { interestOnly } = modules.loans.repayments;

modules.loans.repayments.loanToValueSelect the highest crossed ratio threshold; repay a fixed share of principalBase, capped at current debt.

(options: { readonly value: LoanAmountSource; readonly principalBase: LoanAmountSource; readonly debtForLtv?: LoanAmountSource; readonly tiers: readonly Readonly<{ above: number; annualShare: number; }>[]; }): Formula<LoanContext>

const payment = repayments.loanToValue({
  value: homeValueAtPurchase,
  principalBase: originalLoan,
  tiers: [
    { above: 0.7, annualShare: 0.02 },
    { above: 0.5, annualShare: 0.01 },
  ],
});

const loan = loanPlan({ owner, openingBalance: originalLoan, annualRate, payment });

modules.loans.repayments.selectrepayments.select provides select in the Loans model editor. Use it when a model needs this operation.

(options: { readonly selector: string | InputReference<string> | InputProjectionReference<string> | LookupReference<string>; readonly cases: Readonly<Record<string, Formula<LoanContext>>>; }): Formula<LoanContext>

const { select } = modules.loans.repayments;

modules.loans.repayments.settlementPays amountDue at period end, including that period's interest; uses regular otherwise.

(options: { readonly regular: LoanAmountSource; readonly atPeriod: LoanNumberSource; }): Formula<LoanContext>

const { settlement } = modules.loans.repayments;

modules.loans.revenueBasedrevenueBased provides revenue based in the Loans model editor. Use it when a model needs this operation.

(options: RevenueBasedOptions): RevenueBasedPlan

const { revenueBased } = modules.loans;

modules.loans.revolvingCreditrevolvingCredit provides revolving credit in the Loans model editor. Use it when a model needs this operation.

(options: RevolvingCreditOptions): RevolvingCreditPlan

const { revolvingCredit } = modules.loans;

modules.loans.shareholderLoanshareholderLoan provides shareholder loan in the Loans model editor. Use it when a model needs this operation.

(options: TermLoanOptions): ShareholderLoanPlan

const { shareholderLoan } = modules.loans;

modules.loans.symProvides built-in numeric domains for common positive and percentage inputs.

Readonly<{ keepSettleNewTemp(language?: "en" | "sv"): readonly EnumOption<"keep" | "settle" | "new" | "temporary">[]; amortMethods(language?: "en" | "sv"): readonly EnumOption<"annuity" | "straight" | "interest" | "fixed">[]; }>

const { sym } = modules.loans;

modules.loans.sym.amortMethodssym.amortMethods provides amort methods in the Loans model editor. Use it when a model needs this operation.

(language?: "en" | "sv"): readonly EnumOption<"annuity" | "straight" | "interest" | "fixed">[]

const loanDecision = input.enum('keep', {
  options: modules.loans.sym.keepSettleNewTemp('en'),
});

const repaymentMethod = input.enum('annuity', {
  options: modules.loans.sym.amortMethods('en'),
});

modules.loans.sym.keepSettleNewTempsym.keepSettleNewTemp provides keep settle new temp in the Loans model editor. Use it when a model needs this operation.

(language?: "en" | "sv"): readonly EnumOption<"keep" | "settle" | "new" | "temporary">[]

const loanDecision = input.enum('keep', {
  options: modules.loans.sym.keepSettleNewTemp('en'),
});

const repaymentMethod = input.enum('annuity', {
  options: modules.loans.sym.amortMethods('en'),
});

modules.loans.termLoantermLoan provides term loan in the Loans model editor. Use it when a model needs this operation.

(options: TermLoanOptions): LoanPlan

const loanRows = input.objectArray([
  {
    id: input.id("bank-a"),
    principal: input.money(300_000, currencies.SEK),
    annualRate: input.decimal(0.06),
    start: input.integer(0),
    term: input.integer(36),
  },
  {
    id: input.id("bank-b"),
    principal: input.money(150_000, currencies.SEK),
    annualRate: input.decimal(0.075),
    start: input.integer(6),
    term: input.integer(24),
  },
]);

const row = loanRows.item;

const loanTemplate = financing.termLoan({
  owner: company,
  principal: row.data.principal,
  annualRate: row.data.annualRate,
  startPeriod: row.data.start,
  termPeriods: row.data.term,
  repayment: "annuity",
  postings: { cash, liability: bankDebt, interestExpense },
});

const bankLoans = repeat(loanRows, loanTemplate.component);

return defineModel({
  name: "Company funding plan",
  currency: currencies.SEK,
  timeline: periods.monthly({ from: "2026-01", count: 60 }),
  preconditions: { loanRows },
  entities: { company },
  accounts: { cash, bankDebt, interestExpense },
  components: { bankLoans },
});

modules.loans.AssetFinanceOptionsAssetFinanceOptions describes a model value used by the Loans editor functions.

Model value shape: { owner?: EntityReference | LookupReference<EntityReference>; assetPrice: LoanAmountSource; advance?: LoanAmountSource; downPayment?: LoanAmountSource; annualRate?: LoanNumberSource; periodRate?: LoanNumberSource; startPeriod?: number | InputReference<number>; termPeriods: number | InputReference<number>; repayment?: "annuity" | "fixedPrincipal" | "interestOnly" | "bullet" | "fixed"; payment?: LoanAmountSource; balloon?: LoanAmountSource; originationFee?: LoanAmountSource; postings?: InstallmentPurchasePostings }

modules.loans.AssetFinancePlanAssetFinancePlan describes a model value used by the Loans editor functions.

Model value shape: { calculations: Readonly<Record<string, CalculationReference<unknown>>>; flows: Readonly<Record<string, CashflowReference>>; balance: FieldReference; component: ComponentReference<LoanOutputs>; fields: Readonly<Record<keyof LoanPeriodResult, FieldReference>>; outstanding: CalculationReference<unknown> }

modules.loans.BondOptionsBondOptions describes a model value used by the Loans editor functions.

Model value shape: { owner?: EntityReference | LookupReference<EntityReference>; principal: LoanAmountSource; couponRate: LoanNumberSource; termPeriods: number | InputReference<number>; startPeriod?: number | InputReference<number>; couponStartsPeriod?: number | InputReference<number>; issueFee?: LoanAmountSource; postings?: FinancingPostingAccounts }

modules.loans.BondPlanBondPlan describes a model value used by the Loans editor functions.

Model value shape: { balance: FieldReference; outstanding: CalculationReference<unknown>; fields: Readonly<Record<keyof LoanPeriodResult, FieldReference>>; calculations: Readonly<Readonly<Record<keyof LoanPeriodResult, CalculationReference<unknown>> & { readonly noncashPayment: CalculationReference; readonly totalNoncashPayment: CalculationReference; }> & { readonly principal: CalculationReference; readonly coupon: CalculationReference; readonly finalRedemption: CalculationReference; readonly issueFee: CalculationReference; }>; flows: Readonly<{ readonly issueCash: CashflowReference; readonly coupon: CashflowReference; readonly finalRedemption: CashflowReference; readonly issueFee: CashflowReference; }>; component: ComponentReference<Readonly<Record<string, deccf.ComponentOutputReference>>>; commitment?: CalculationReference<unknown> }

modules.loans.ConvertibleLoanOptionsConvertibleLoanOptions describes a model value used by the Loans editor functions.

Model value shape: { postings?: LoanPlanPostingAccounts; conversionPeriod: number | InputReference<number>; conversionShare?: LoanNumberSource; owner?: EntityReference | LookupReference<EntityReference>; annualRate?: LoanNumberSource; repayment?: "annuity" | "fixedPrincipal" | "interestOnly" | "bullet" | "fixed"; periodRate?: LoanNumberSource; extraPayment?: LoanAmountSource; payment?: LoanAmountSource; principal: LoanAmountSource; startPeriod?: number | InputReference<number>; firstPaymentPeriod?: number | InputReference<number>; termPeriods: number | InputReference<number>; principalPerPeriod?: LoanAmountSource }

modules.loans.ConvertibleLoanPlanConvertibleLoanPlan describes a model value used by the Loans editor functions.

Model value shape: { calculations: Readonly<Record<keyof LoanPeriodResult, CalculationReference<unknown>> & { readonly noncashPayment: CalculationReference; readonly totalNoncashPayment: CalculationReference; }> & { readonly convertedEquity: CalculationReference; readonly totalConvertedEquity: CalculationReference; }; component: ComponentReference<LoanOutputs>; balance: FieldReference; fields: Readonly<Record<keyof LoanPeriodResult, FieldReference>>; outstanding: CalculationReference<unknown>; flows: Readonly<{ readonly drawdownStart: CashflowReference; readonly drawdownEnd: CashflowReference; readonly payment: CashflowReference; }> }

modules.loans.EquityContributionOptionsEquityContributionOptions describes a model value used by the Loans editor functions.

Model value shape: { owner?: EntityReference | LookupReference<EntityReference>; amount: LoanAmountSource; period?: number | InputReference<number>; postings?: EquityContributionPostings }

modules.loans.EquityContributionPlanEquityContributionPlan describes a model value used by the Loans editor functions.

Model value shape: { fields: Readonly<{ readonly totalContributed: FieldReference; }>; calculations: Readonly<{ readonly contribution: CalculationReference; readonly totalContributed: CalculationReference; }>; flows: Readonly<{ readonly contribution: CashflowReference; }>; component: ComponentReference<Readonly<Record<string, deccf.ComponentOutputReference>>>; outstanding?: CalculationReference<unknown>; commitment?: CalculationReference<unknown> }

modules.loans.EquityContributionPostingsEquityContributionPostings describes a model value used by the Loans editor functions.

Model value shape: { cash: AccountReference; equity: AccountReference }

modules.loans.FactoringOptionsFactoringOptions describes a model value used by the Loans editor functions.

Model value shape: { owner?: EntityReference | LookupReference<EntityReference>; invoiceAmount: LoanAmountSource; advanceRate: LoanNumberSource; feeRate?: LoanNumberSource; reserveRate?: LoanNumberSource; startPeriod?: number | InputReference<number>; duePeriod: number | InputReference<number>; unpaidAmount?: LoanAmountSource; recourse?: "none" | "limited" | "full"; postings?: FactoringPostingAccounts }

modules.loans.FactoringPlanFactoringPlan describes a model value used by the Loans editor functions.

Model value shape: { calculations: Readonly<{ readonly invoiceAmount: CalculationReference; readonly advanceAmount: CalculationReference; readonly advance: CalculationReference; readonly reserveAmount: CalculationReference; readonly reserveReleased: CalculationReference; readonly fee: CalculationReference; readonly unpaidAmount: CalculationReference; readonly recoursePayment: CalculationReference; readonly recourseObligation: CalculationReference; readonly netSettlement: CalculationReference; }>; flows: Readonly<{ readonly advance: CashflowReference; readonly reserveRelease: CashflowReference; readonly fee: CashflowReference; readonly recoursePayment: CashflowReference; }>; component: ComponentReference<Readonly<Record<string, deccf.ComponentOutputReference>>>; fields: Readonly<Record<string, FieldReference>>; outstanding?: CalculationReference<unknown>; commitment?: CalculationReference<unknown> }

modules.loans.FactoringPostingAccountsFactoringPostingAccounts describes a model value used by the Loans editor functions.

Model value shape: { cash: AccountReference; receivable: AccountReference; clearing: AccountReference; feeExpense?: AccountReference; recourseExpense?: AccountReference }

modules.loans.FinancialLeaseOptionsFinancialLeaseOptions describes a model value used by the Loans editor functions.

Model value shape: { readonly owner?: EntityReference | LookupReference<EntityReference>; readonly assetPrice: LoanAmountSource; readonly upfrontPayment?: LoanAmountSource; readonly startPeriod?: number | InputReference<number>; readonly firstPaymentPeriod?: number | InputReference<number>; readonly termPeriods: number | InputReference<number>; readonly periodicPayment?: LoanAmountSource; readonly buyout?: LoanAmountSource; readonly postings?: FinancialLeasePostings; } & ( | { readonly annualRate: LoanNumberSource; readonly periodRate?: never; readonly rateConvention?: "nominal" | "effective"; } | { readonly annualRate?: never; readonly periodRate: LoanNumberSource } )

modules.loans.FinancialLeasePlanFinancialLeasePlan describes a model value used by the Loans editor functions.

Model value shape: { calculations: Readonly<Record<string, CalculationReference<unknown>>>; flows: Readonly<Record<string, CashflowReference>>; balance: FieldReference; component: ComponentReference<LoanOutputs>; fields: Readonly<Record<keyof LoanPeriodResult, FieldReference>>; outstanding: CalculationReference<unknown> }

modules.loans.FinancialLeasePostingsFinancialLeasePostings describes a model value used by the Loans editor functions.

Model value shape: { cash: AccountReference; asset: AccountReference; liability: AccountReference; interestExpense: AccountReference }

modules.loans.FinancingPlanFinancingPlan describes a model value used by the Loans editor functions.

Model value shape: { component: ComponentReference<Readonly<Record<string, deccf.ComponentOutputReference>>>; outstanding?: CalculationReference<unknown>; commitment?: CalculationReference<unknown>; fields: Readonly<Record<string, FieldReference>>; calculations: Readonly<Record<string, CalculationReference<unknown>>>; flows: Readonly<Record<string, CashflowReference>> }

modules.loans.FinancingPostingAccountsFinancingPostingAccounts describes a model value used by the Loans editor functions.

Model value shape: { cash: AccountReference; liability: AccountReference; interestExpense: AccountReference; feeExpense?: AccountReference }

modules.loans.GrantOptionsGrantOptions describes a model value used by the Loans editor functions.

Model value shape: { owner?: EntityReference | LookupReference<EntityReference>; amount: LoanAmountSource; period?: number | InputReference<number>; installments?: number | InputReference<number>; postings?: GrantPostings }

modules.loans.GrantPlanGrantPlan describes a model value used by the Loans editor functions.

Model value shape: { fields: Readonly<{ readonly totalReceived: FieldReference; }>; calculations: Readonly<{ readonly receipt: CalculationReference; readonly totalReceived: CalculationReference; }>; flows: Readonly<{ readonly receipt: CashflowReference; }>; component: ComponentReference<Readonly<Record<string, deccf.ComponentOutputReference>>>; outstanding?: CalculationReference<unknown>; commitment?: CalculationReference<unknown> }

modules.loans.GrantPostingsGrantPostings describes a model value used by the Loans editor functions.

Model value shape: { cash: AccountReference; income: AccountReference }

modules.loans.InstallmentPurchaseOptionsInstallmentPurchaseOptions describes a model value used by the Loans editor functions.

Model value shape: { owner?: EntityReference | LookupReference<EntityReference>; purchasePrice: LoanAmountSource; downPayment?: LoanAmountSource; annualRate?: LoanNumberSource; periodRate?: LoanNumberSource; startPeriod?: number | InputReference<number>; termPeriods: number | InputReference<number>; originationFee?: LoanAmountSource; feeFinanced?: boolean; balloon?: LoanAmountSource; repayment?: "annuity" | "fixedPrincipal" | "interestOnly" | "bullet" | "fixed"; payment?: LoanAmountSource; postings?: InstallmentPurchasePostings }

modules.loans.InstallmentPurchasePlanInstallmentPurchasePlan describes a model value used by the Loans editor functions.

Model value shape: { calculations: Readonly<Record<string, CalculationReference<unknown>>>; flows: Readonly<Record<string, CashflowReference>>; balance: FieldReference; component: ComponentReference<LoanOutputs>; fields: Readonly<Record<keyof LoanPeriodResult, FieldReference>>; outstanding: CalculationReference<unknown> }

modules.loans.InstallmentPurchasePostingsInstallmentPurchasePostings describes a model value used by the Loans editor functions.

Model value shape: { asset: AccountReference; cash: AccountReference; liability: AccountReference; interestExpense: AccountReference; feeExpense?: AccountReference }

modules.loans.InvoicePurchaseOptionsInvoicePurchaseOptions describes a model value used by the Loans editor functions.

Model value shape: { owner?: EntityReference | LookupReference<EntityReference>; invoiceAmount: LoanAmountSource; purchaseRate: LoanNumberSource; reserveRate?: LoanNumberSource; discountFeeRate?: LoanNumberSource; startPeriod?: number | InputReference<number>; duePeriod: number | InputReference<number>; unpaidAmount?: LoanAmountSource; recourse?: "none" | "limited" | "full"; postings?: InvoicePurchasePostingAccounts }

modules.loans.InvoicePurchasePlanInvoicePurchasePlan describes a model value used by the Loans editor functions.

Model value shape: { calculations: Readonly<{ readonly invoiceAmount: CalculationReference; readonly purchaseRate: CalculationReference; readonly purchasePrice: CalculationReference; readonly discountAmount: CalculationReference; readonly reserveAmount: CalculationReference; readonly upfrontProceeds: CalculationReference; readonly discountFee: CalculationReference; readonly reserveReleased: CalculationReference; readonly unpaidAmount: CalculationReference; readonly recoursePayment: CalculationReference; readonly recourseObligation: CalculationReference; readonly netSettlement: CalculationReference; }>; flows: Readonly<{ readonly purchaseProceeds: CashflowReference; readonly discountFee: CashflowReference; readonly reserveRelease: CashflowReference; readonly recoursePayment: CashflowReference; }>; component: ComponentReference<Readonly<Record<string, deccf.ComponentOutputReference>>>; fields: Readonly<Record<string, FieldReference>>; outstanding?: CalculationReference<unknown>; commitment?: CalculationReference<unknown> }

modules.loans.InvoicePurchasePostingAccountsInvoicePurchasePostingAccounts describes a model value used by the Loans editor functions.

Model value shape: { cash: AccountReference; receivable: AccountReference; clearing?: AccountReference; discountExpense?: AccountReference; recourseExpense?: AccountReference }

modules.loans.LoanAmountSourceLoanAmountSource describes a model value used by the Loans editor functions.

Model value shape: AmountSource<LoanContext>

modules.loans.LoanContextLoanContext describes a model value used by the Loans editor functions.

Model value shape: { currency: Currency; sourceCurrency: Currency; time: TimeContext; owner?: EntityReference | LookupReference<EntityReference>; loan?: LoanFacts; get: (reference: InputReference | InputProjectionReference | CalculationReference | CalculationProjectionReference | AccountReference) => number | deccf.Money; curveAt: (reference: InputReference<number>, date: deccf.DateString) => number; draw: (reference: InputReference<number>) => number; sample: (reference: InputReference<number>) => number }

modules.loans.LoanFactsLoanFacts describes a model value used by the Loans editor functions.

Model value shape: { openingBalance: number; drawdownStart: number; drawdownEnd: number; interestBase: number; periodRate: number; interest: number; amountDue: number }

modules.loans.LoanNumberSourceLoanNumberSource describes a model value used by the Loans editor functions.

Model value shape: NumberSource<LoanContext>

modules.loans.LoanOutputsLoanOutputs describes a model value used by the Loans editor functions.

Model value shape: Omit<Readonly<Record<LoanPeriodOutputName, CalculationReference>>, "drawdownStart" | "drawdownEnd"> & Readonly<{ drawdownStart: CashflowReference; drawdownEnd: CashflowReference; drawdownStartAmount: CalculationReference; drawdownEndAmount: CalculationReference; balance: CalculationReference; outstanding: CalculationReference; noncashPayment: CalculationReference; totalNoncashPayment: CalculationReference; currencyGuard: CalculationReference; payment: CashflowReference; drawdownStartFlow: CashflowReference; drawdownEndFlow: CashflowReference; paymentFlow: CashflowReference; }>

modules.loans.LoanPeriodInputLoanPeriodInput describes a model value used by the Loans editor functions.

Model value shape: { openingBalance: number; periodRate: number; drawdownStart?: number; drawdownEnd?: number; requestedPayment: number; requestedExtraPayment?: number; unpaidInterest?: "error" | "capitalize" }

modules.loans.LoanPeriodOutputNameLoanPeriodOutputName describes a model value used by the Loans editor functions.

Model value shape: keyof LoanPeriodResult

modules.loans.LoanPeriodResultLoanPeriodResult describes a model value used by the Loans editor functions.

Model value shape: { interestBase: number; interest: number; amountDue: number; regularPayment: number; extraPayment: number; totalPayment: number; interestPaid: number; principalPaid: number; capitalizedInterest: number; closingBalance: number; openingBalance: number; periodRate: number; drawdownStart: number; drawdownEnd: number; requestedPayment: number; requestedExtraPayment: number }

modules.loans.LoanPlanLoanPlan describes a model value used by the Loans editor functions.

Model value shape: { component: ComponentReference<LoanOutputs>; balance: FieldReference; fields: Readonly<Record<keyof LoanPeriodResult, FieldReference>>; outstanding: CalculationReference<unknown>; calculations: Readonly<Record<keyof LoanPeriodResult, CalculationReference<unknown>> & { readonly noncashPayment: CalculationReference; readonly totalNoncashPayment: CalculationReference; }>; flows: Readonly<{ readonly drawdownStart: CashflowReference; readonly drawdownEnd: CashflowReference; readonly payment: CashflowReference; }> }

modules.loans.LoanPlanPostingAccountsLoanPlanPostingAccounts describes a model value used by the Loans editor functions.

Model value shape: { equity?: AccountReference; cash: AccountReference; liability: AccountReference; interestExpense: AccountReference; feeExpense?: AccountReference }

modules.loans.OperatingLeaseOptionsOperatingLeaseOptions describes a model value used by the Loans editor functions.

Model value shape: { owner?: EntityReference | LookupReference<EntityReference>; periodicRent: LoanAmountSource; termPeriods: number | InputReference<number>; startPeriod?: number | InputReference<number>; firstPaymentPeriod?: number | InputReference<number>; setupFee?: LoanAmountSource; deposit?: LoanAmountSource; depositReturnPeriod?: number | InputReference<number>; indexationRate?: LoanNumberSource; buyout?: LoanAmountSource; postings?: OperatingLeasePostings }

modules.loans.OperatingLeasePlanOperatingLeasePlan describes a model value used by the Loans editor functions.

Model value shape: { component: ComponentReference<Readonly<Record<string, deccf.ComponentOutputReference>>>; commitment: CalculationReference<unknown>; fields: Readonly<Record<string, FieldReference>>; calculations: Readonly<Record<string, CalculationReference<unknown>>>; flows: Readonly<{ readonly rent: CashflowReference; readonly setupFee: CashflowReference; readonly deposit: CashflowReference; readonly depositReturn: CashflowReference; readonly buyout: CashflowReference; }> }

modules.loans.OperatingLeasePostingsOperatingLeasePostings describes a model value used by the Loans editor functions.

Model value shape: { cash: AccountReference; operatingExpense: AccountReference; feeExpense?: AccountReference; depositAsset?: AccountReference; asset?: AccountReference }

modules.loans.RevenueBasedOptionsRevenueBasedOptions describes a model value used by the Loans editor functions.

Model value shape: { owner?: EntityReference | LookupReference<EntityReference>; advance: LoanAmountSource; revenue: LoanAmountSource; holdbackRate: LoanNumberSource; repaymentCap: LoanAmountSource; startPeriod?: number | InputReference<number>; firstCollectionPeriod?: number | InputReference<number>; postings?: RevenueBasedPostings }

modules.loans.RevenueBasedPlanRevenueBasedPlan describes a model value used by the Loans editor functions.

Model value shape: { balance: FieldReference; outstanding: CalculationReference<unknown>; calculations: Readonly<{ readonly advance: CalculationReference; readonly advanceAmount: CalculationReference; readonly repaymentCap: CalculationReference; readonly holdbackRate: CalculationReference; readonly openingObligation: CalculationReference; readonly periodPaid: CalculationReference; readonly totalRepaid: CalculationReference; readonly remainingObligation: CalculationReference; readonly principalPaid: CalculationReference; readonly principalOutstanding: CalculationReference; readonly financingCharge: CalculationReference; readonly financingChargePaid: CalculationReference; }>; flows: Readonly<{ readonly drawdown: CashflowReference; readonly payment: CashflowReference; }>; component: ComponentReference<Readonly<Record<string, deccf.ComponentOutputReference>>>; fields: Readonly<Record<string, FieldReference>>; commitment?: CalculationReference<unknown> }

modules.loans.RevenueBasedPostingsRevenueBasedPostings describes a model value used by the Loans editor functions.

Model value shape: { cash: AccountReference; liability: AccountReference; feeExpense?: AccountReference }

modules.loans.RevolvingCreditOptionsRevolvingCreditOptions describes a model value used by the Loans editor functions.

Model value shape: { readonly owner?: EntityReference | LookupReference<EntityReference>; readonly calendar?: Calendar; readonly limit: LoanAmountSource; readonly openingBalance?: LoanAmountSource; readonly drawdown?: LoanAmountSource; readonly repayment?: LoanAmountSource; readonly startPeriod?: number | InputReference<number>; readonly unusedLimitFeeRate?: LoanNumberSource; readonly overLimit?: "error" | "cap"; readonly postings?: FinancingPostingAccounts; } & ( | { readonly annualRate: LoanNumberSource; readonly periodRate?: never; readonly rateConvention?: "nominal" | "effective"; } | { readonly annualRate?: never; readonly periodRate: LoanNumberSource } )

modules.loans.RevolvingCreditPlanRevolvingCreditPlan describes a model value used by the Loans editor functions.

Model value shape: { component: ComponentReference<Readonly<Record<string, deccf.ComponentOutputReference>>>; balance: FieldReference; outstanding: CalculationReference<unknown>; fields: Readonly<{ readonly closingBalance: FieldReference; }>; calculations: Readonly<{ readonly limit: CalculationReference; readonly openingBalance: CalculationReference; readonly requestedDrawdown: CalculationReference; readonly actualDrawdown: CalculationReference; readonly availableBeforeDraw: CalculationReference; readonly interestBase: CalculationReference; readonly periodRate: CalculationReference; readonly interest: CalculationReference; readonly amountDue: CalculationReference; readonly requestedRepayment: CalculationReference; readonly totalPayment: CalculationReference; readonly interestPaid: CalculationReference; readonly principalPaid: CalculationReference; readonly capitalizedInterest: CalculationReference; readonly closingBalance: CalculationReference; readonly availableLimit: CalculationReference; readonly utilization: CalculationReference; readonly unusedLimitFee: CalculationReference; }>; flows: Readonly<{ readonly drawdown: CashflowReference; readonly payment: CashflowReference; readonly unusedLimitFee: CashflowReference; }> }

modules.loans.ShareholderLoanPlanShareholderLoanPlan describes a model value used by the Loans editor functions.

Model value shape: { component: ComponentReference<LoanOutputs>; balance: FieldReference; fields: Readonly<Record<keyof LoanPeriodResult, FieldReference>>; outstanding: CalculationReference<unknown>; calculations: Readonly<Record<keyof LoanPeriodResult, CalculationReference<unknown>> & { readonly noncashPayment: CalculationReference; readonly totalNoncashPayment: CalculationReference; }>; flows: Readonly<{ readonly drawdownStart: CashflowReference; readonly drawdownEnd: CashflowReference; readonly payment: CashflowReference; }> }

modules.loans.TermLoanOptionsTermLoanOptions describes a model value used by the Loans editor functions.

Model value shape: { owner?: EntityReference | LookupReference<EntityReference>; principal: LoanAmountSource; annualRate?: LoanNumberSource; periodRate?: LoanNumberSource; startPeriod?: number | InputReference<number>; firstPaymentPeriod?: number | InputReference<number>; termPeriods: number | InputReference<number>; repayment?: "annuity" | "fixedPrincipal" | "interestOnly" | "bullet" | "fixed"; payment?: LoanAmountSource; principalPerPeriod?: LoanAmountSource; extraPayment?: LoanAmountSource; postings?: FinancingPostingAccounts }

Savings module

Select this module in model settings to use its names in the portal model editor (modules.savings).

Model editor namePurpose and model value shape
modules.savings.prepareRetirementProjectionCreates a reusable synchronous retirement calculator. The optional configuration accepts only execution:"legacy"|"timeline", defaulting to "legacy" as retirementProjection does. Call the returned calculator with complete retirement assumptions, excluding execution. A defined per-call execution value is rejected; create another calculator to select another mode. Unknown factory options and unsupported execution values fail immediately. Every invocation validates and snapshots fresh amounts, ages, annualRates and nested settings using retirementProjection's defaults, units and constraints. It returns the same RetirementProjectionResult shape. Later changes to an earlier input or result do not change another call's assumptions or report. Timeline preparation is reused lazily within this calculator; calculated results, balances, histories and resolved stochastic values are never cached between calls. There is no shared global result cache. Custom sampling callbacks still require dynamic:true and run independently for each invocation. See the Savings guide for an example calling this factory and its returned calculator twice.

(configuration?: { readonly execution?: "legacy" | "timeline"; }): PreparedRetirementProjection

const calculateRetirement = modules.savings.prepareRetirementProjection({execution:'timeline'});

const assumptions = {
  currentAge:62, retirementAge:65, lifeExpectancy:72, pensionStartAge:67,
  currentSavings:450000, annualSavings:25000,
  preRetirementReturn:0.06, postRetirementReturn:0.04,
  inflation:0.03, pensionAnnualIncrease:0.025,
  monthlyPension:3500, monthlyOtherIncome:300, annualExpenses:55000,
  horizonAge:75, includeWhatIf:false,
};

const first = calculateRetirement(assumptions);

const increased = calculateRetirement({...assumptions,annualSavings:30000});

const extraStartingCapital = increased.summary.startingPortfolio-first.summary.startingPortfolio;

modules.savings.retirementPlanConstruct a retirement portfolio on the model's annual timeline with balanced personal account-plan postings. Annual model period zero represents currentAge; cover currentAge through horizonAge inclusively. options is a scalar RetirementProjectionOptions object snapshotted at construction (including nested settings and budget ages), or a callback evaluated once per execution/trial with OnceContext. That context reads declared inputs and bindings and supports draw/sample; it has no time or ledger reads. Use dynamic:true when configuration must be reevaluated per period through CalculationContext. Caller-owned objects and arrays are not frozen. Default static configuration is data-only; supply annualRates for sampled paths. Custom sample callbacks require top-level dynamic:true, even if options.dynamic is true; the top-level setting alone authorizes those callbacks. The callback reads caller-declared inputs; preconditions defaults to {} and dependsOn defaults to []. An omitted owner creates a party; a supplied owner must be declared by the caller. asset is an owned portfolio entity. reportSchedule optionally restricts report evaluation. The authoritative portfolio is accounts.portfolio (assets.investments.brokerage). cash uses assets.cash.bank, netWorth uses equity.retained_earnings, pensionIncome uses income.pension.net, and investmentIncome uses income.capital.other. workingIncome uses income.employment.net_salary and otherIncome uses income.other.net for amounts already entered after tax; expenses uses expense.other (the personal expenses.other category). The owned asset groups contribution, withdrawal, growth and loss flows; personal cash rollups include those descendant flows. Contributions and withdrawals transfer between cash and portfolio; growth/loss are noncash postings. Working-budget shortfalls may leave cash negative but never silently reduce scheduled portfolio saving. Unsaved retirement surpluses remain in cash. This helper does not compute income tax. calculations.year contains current-period assumptions and proposed movements; history is flat state: openingPortfolio, closingPortfolio, legacy, depletionAge, yearsFunded and portfolioLasts. closingPortfolio includes other flows posting to that account. No rows/lifetimeRows maps are stored here; complete rows are assembled once by projection. Use bind.history(plan.calculations.history) for prior snapshots. projection is null before horizonAge and returns RetirementProjectionResult in that final period. Its comparisons and threshold searches use native timeline runs of the entered assumptions. The history and projection calculations run at periodEnd. Regular calculations read opening balances; these periodEnd calculations read settled balances. Uses retirementProjection validation and defaults, and rejects nonannual calendars or execution beyond horizonAge. Callback dependency lists must name same-period calculation reads. Numeric monetary assumptions share model currency. See the Savings guide for a complete callable retirementPlan example.

(options: RetirementPlanOptions & { readonly dynamic?: false; readonly options: RetirementProjectionOptions | ((context: OnceContext) => RetirementProjectionOptions); }): RetirementPlan
(options: RetirementPlanOptions & { readonly dynamic: true; readonly options: RetirementProjectionOptions | ((context: CalculationContext) => RetirementProjectionOptions); }): RetirementPlan

const person = deccf.entity.party({label:'Planner'});

const savings = deccf.input.money(450000, deccf.currencies.USD);

const plan = modules.savings.retirementPlan({
  owner: person,
  preconditions: {savings},
  options: ctx => ({
    currentAge:62, retirementAge:65, lifeExpectancy:72, pensionStartAge:67,
    currentSavings:ctx.get(savings).amount, annualSavings:25000,
    preRetirementReturn:.06, postRetirementReturn:.04, inflation:.03,
    pensionAnnualIncrease:.025, monthlyPension:3500,
    monthlyOtherIncome:300, annualExpenses:55000,
    horizonAge:75, includeWhatIf:false, includeLifetimeRows:true,
  }),
});

return deccf.defineModel({
  currency:deccf.currencies.USD,
  timeline:deccf.periods.annual({from:'2026-01', count:14}),
  entities:{person},
  components:{retirement:plan.component},
  metrics:{portfolio:ctx=>ctx.get(plan.accounts.portfolio)},
});

modules.savings.retirementProjectionProjects retirement savings, annual budgets, funding longevity and deterministic what-if choices from scalar assumptions. All 13 age, amount and rate assumptions are required. Amounts are numbers in one currency, not typed money values. Ages must be integers from 0 through horizonAge (default 150) and currentAge <= retirementAge <= lifeExpectancy. Pension start can exceed a shortened horizon, up to max(150,horizonAge). Money must be finite and nonnegative. Rates are annual decimals within rateBounds (default strictly greater than -1 through 10); sampled rates use the same bounds. Invalid assumptions, callback results and nonfinite calculated amounts throw a model error. By default accumulation runs twelve monthly periods per working year, using preRetirementReturn / 12 and annualSavings / 12, with contributions at month end. The optional settings below override those conventions. Retirement rows include retirementAge through lifeExpectancy: portfolio is the opening balance; first-year expenses are annualExpenses, increasing with inflation from year two. Other income stays at monthlyOtherIncome * 12. Pension is monthlyPension * 12 at pensionStartAge and increases by pensionAnnualIncrease for each later age. A pension already started before retirement includes those increases. The positive expense-income gap is withdrawn at year start, capped to available funds, and the remainder earns postRetirementReturn. Income surpluses are not deposited. Any uncovered year remains a plan failure even if later income covers expenses. Legacy is the closing portfolio after the lifeExpectancy year. annualRates supplies absolute bounded annual rates in optional accumulationReturn, retirementReturn, inflation, incomeIncrease and pensionIncrease maps keyed age0 through age150. Missing channels/ages use the declared mean; unknown channels, malformed age keys, null maps and invalid rates fail. The corresponding sample callback cannot coexist with a channel (sampleReturn conflicts with either return channel). Main projections use supplied paths; sampledEarliestRetirement also reuses them. Unsampled comparisons and threshold searches keep the means. Data is snapshotted, without retaining caller-owned mutable records. Custom sample callbacks require dynamic:true for both execution modes; omission/false uses data-only static configuration. Optional synchronous sampleReturn({age, phase, mean}) samples once per accumulation year (phase "accumulation") and once per retirement year (phase "retirement"); the accumulation draw is divided by 12 for all twelve months. Optional sampleInflation({age, mean}) samples from the second retirement year. Omitted callbacks use means. Optional sampleIncomeIncrease({age, mean}) supplies annual otherIncomeAnnualIncrease draws from the year after incomeIncreaseBaseAge (or retirementAge when omitted). One annual draw compounds the shared working and other-income path, independent of includeLifetimeRows. Working income remains constant if its base age is omitted. Optional samplePensionIncrease({age, mean}) supplies annual pensionAnnualIncrease draws from the year after pensionStartAge. Both callbacks sample only ages after currentAge; earlier accrued increases retain their means. Initial income and pension amounts are not shocked. The main projection calls each applicable callback once per future age through horizonAge; it must return a synchronous finite rate within rateBounds. Invalid callback types/rates fail. Omission or undefined preserves the existing fixed growth exactly. Callers can share an annual shock between these callbacks while adding each callback's own mean. By default these callbacks affect the main projection only; earliest retirement and what-if choices use means. sampledEarliestRetirement defaults to false. True also samples every candidate retirement age in the earliest retirement search, checking funding through lifeExpectancy. The search remains independent of includeWhatIf. Reuse stored annual shocks for each age and add each callback's own mean: search candidates may call callbacks repeatedly at the same age and in different return phases. Fresh random draws on each call do not describe one consistent annual path. With no callbacks the result stays unchanged. Non-boolean option values fail. What-if comparisons always retain the mean assumptions, including when this option is true. The funding calculation continues through horizonAge (default 150), including sampling, but rows stop at lifeExpectancy. Returns JSON-safe named records. rows uses age keys such as age65; budget selects the first two retirement ages, pension start, retirement years 12 and 22, and the final age, omitting out-of-plan ages and duplicates. includeLifetimeRows defaults to false, preserving the previous exact result shape. True adds lifetimeRows, one age-keyed annual row from currentAge through lifeExpectancy, inclusive, in age order. Non-booleans fail. Each has age, phase (accumulation before retirementAge, retirement afterwards), opening portfolio, closingPortfolio, annual income, expenses and gap. Accumulation rows come from the same compounding pass and annual return draws, without extra callback calls; each closing balance equals the next opening balance. At retirementAge the values match rows. Existing rows, budget and summary retain their retirement-only meaning. includeSavingsInWorkingExpenses defaults to false. True treats annualWorkingExpenses as living expenses excluding savings: after their optional inflation, add fixed nominal annualSavings in every working year. Its working gap is max(0, expenses - income) when both amounts are known; missing observations remain null. This affects lifetime budget reporting only. The annualSavings deposit is still made once and retirement expenses keep their existing meaning. Non-boolean values are rejected. Optional annualWorkingIncome and annualWorkingExpenses are finite nonnegative scalar amounts in the same currency. Omission or undefined gives null for that working-year field; supplied values remain constant in every accumulation row unless the corresponding optional expenseInflationBaseAge or incomeIncreaseBaseAge is supplied. Working gap is 0 when both amounts are supplied and null otherwise: working years do not withdraw from the portfolio. These chart/context amounts do not derive, replace or constrain the independently entered annualSavings, even if working expenses exceed income. Null or invalid supplied amounts are rejected even with includeWhatIf:false. Retirement income, expenses and gap match existing rows. summary.portfolioLasts means every planned year is funded. yearsFunded counts consecutive funded years through horizonAge; depletionAge is the first uncovered age, fundedUntilAge is its preceding age, and both are null if funded through that horizon. longevityBuffer is yearsFunded minus retirementYears. earliestRetirementAge is the first whole age from currentAge through lifeExpectancy funding the plan, or null. Withdrawal rates are gap/opening funds: null when a positive gap has zero funds, otherwise a decimal. maximumWithdrawalRate is the planned maximum and bridgeWithdrawalRate is the arithmetic average before pension starts (0 with no bridge); either is null when one of its included rates is null. includeWhatIf defaults to true; false returns whatIf: null. Comparisons test one extra working year, retirement now, no further saving, 6000 extra annual saving, 500 extra monthly other income, expenses 10% lower/higher, pension removed/halved, and a 20% portfolio loss at retirement by default. Depletion ages are first uncovered years through horizonAge; null means horizonAge+. delayYearsGain and extraSavingsYearsGain divide the additional retirement starting portfolio by the baseline first-year expense-income gap: these are spending-equivalent years, not additional funded years, and are null when that gap is zero. delayYearsGain is also null when retirement cannot be delayed within the plan. Bisection finds the maximum annual inflation and minimum post-retirement return funding every planned year within the supported rate bounds. inflationBuffer is that maximum inflation minus inflation (a rate difference, possibly negative), or null when no supported inflation funds the plan. minimumReturn is null when no supported return funds the plan. Milestones ten/twentyFive/thirty/thirtyThree multiply annualExpenses by 10/25/30/33; coverage is retirement startingPortfolio / target, or null for a zero target. They do not subtract pension or other income. Every fixed comparison/timing/selection assumption has optional overrides. horizonAge (integer 0..150, default 150) must be at least lifeExpectancy. accumulationPeriodsPerYear (integer 1..366, default 12) divides annualSavings and the nominal preRetirementReturn into equal periods. contributionPlacement defaults to end. withdrawalPlacement defaults to start; end applies the annual return before withdrawal. reinvestIncomeSurplus defaults to false; true deposits positive income minus expenses at the same placement as withdrawals. otherIncomeAnnualIncrease (default 0) grows other income from year two and obeys rateBounds. expenseInflationStartYear (integer 1..1001, default 2) chooses the first year receiving inflation or a sample. Optional expenseInflationBaseAge (integer 0..currentAge) instead treats annualExpenses and annualWorkingExpenses as amounts in money at that age. The first age keeps that amount; each elapsed year multiplies expenses by 1 + inflation (or its sample). For base age 40 and retirement 65, retirement costs include 25 annual increases. This overrides expenseInflationStartYear. Inflation sampling then covers base age + 1 through horizonAge, exactly once per age; working rows and retirement expenses share those factors. Retirement milestone targets use the first retirement year's inflated expenses. Omission preserves all previous expense timing and targets. Optional incomeIncreaseBaseAge (integer 0..currentAge) anchors annualWorkingIncome and monthlyOtherIncome to that age and compounds otherIncomeAnnualIncrease for each elapsed year, before and after retirement. Pension retains its independent pensionAnnualIncrease; annualSavings always stays a fixed nominal amount. Omission retains constant working income and retirement-based other income. Invalid, null, fractional or future base ages fail. With either base supplied, a retirementAge below currentAge starts retirement at currentAge; no historical withdrawals or contributions are reconstructed. lifeExpectancy must still be at least currentAge. Placement values must be start/end. Twelve calendar months still convert monthly income/savings to annual amounts. budgetAges optionally supplies up to 1001 integer ages 0..1000. First-occurrence order is retained; duplicates and ages outside retirementAge..lifeExpectancy are omitted. [] selects none. Omission retains the original six derived ages above. milestoneMultiples partially replaces the four named finite nonnegative multiples; keys and coverage rules remain compatible, including null coverage for zero targets. whatIf partially overrides delayYears (integer 0..1000, default 1), annualSavingsAfterStopping (0), extraMonthlySavings (500), extraMonthlyIncome (500), lowerExpenseReduction (0.1), higherExpenseIncrease (0.1), pensionRemoval (1), pensionReduction (0.5), marketCrashLoss (0.2). Amounts and expense increases must be finite and nonnegative; reduction/removal/loss fractions must lie in 0..1. Extra monthly savings are multiplied by 12. Existing result names remain: noPensionDepletionAge uses pensionRemoval; halfPensionDepletionAge uses pensionReduction even for configured fractions other than 1/0.5. Delay beyond lifeExpectancy returns null; zero delay gives zero gained years when the first-year gap is positive. rateBounds.minimum defaults to -1 + Number.EPSILON, must be finite and strictly above -1; maximum defaults to 10 and must exceed minimum. thresholdSearch.minimumRate/maximumRate default to those bounds, must be increasing and inside them. iterations is an integer 1..100, default 55. Bisection's unresolved interval is at most initial width / 2**iterations. A feasible lower return boundary or upper inflation boundary returns that boundary; infeasible searches return null. Optional groups accept partial and undefined members. Null groups, unknown group members and invalid settings fail even with includeWhatIf:false. The 150-horizon, 366-period, 1001-entry and 100-iteration ceilings are execution safety limits.

(options: RetirementProjectionOptions): RetirementProjectionResult

const report = modules.savings.retirementProjection({
  execution:'timeline',
  currentAge:62, retirementAge:65, lifeExpectancy:72, pensionStartAge:67,
  currentSavings:450000, annualSavings:25000,
  preRetirementReturn:.06, postRetirementReturn:.04,
  inflation:.03, pensionAnnualIncrease:.025,
  monthlyPension:3500, monthlyOtherIncome:300, annualExpenses:55000,
  horizonAge:75, includeWhatIf:false,
});

const legacy = report.summary.legacy;

modules.savings.savingsPeriodsavingsPeriod provides savings period in the Savings model editor. Use it when a model needs this operation.

(options: { readonly openingBalance: number; readonly periodRate: number; readonly contribution?: number; readonly contributionPlacement?: "start" | "end"; readonly requestedWithdrawal?: number; readonly feeRate?: number; readonly insufficientFunds?: "cap" | "error"; }): SavingsPeriodResult

const { savingsPeriod } = modules.savings;

modules.savings.savingsPlansavingsPlan provides savings plan in the Savings model editor. Use it when a model needs this operation.

(options: { readonly owner?: EntityReference; readonly calendar?: Calendar; readonly openingBalance: SavingsSource; readonly annualRate?: SavingsSource; readonly rateConvention?: "nominal" | "effective"; readonly compoundsPerYear?: number | InputReference<number>; readonly periodRate?: SavingsSource; readonly contribution?: AmountSource<SavingsContext>; readonly contributionPlacement?: "start" | "end"; readonly withdrawal?: AmountSource<SavingsContext>; readonly feeRate?: NumberSource<SavingsContext>; readonly insufficientFunds?: "cap" | "error"; readonly preconditions?: Readonly<Record<string, InputReference>>; readonly dependsOn?: readonly CalculationReference[]; readonly readsAccountsFrom?: readonly AccountReference[]; }): SavingsPlan

const { savingsPlan } = modules.savings;

const fund = savingsPlan({
  openingBalance: currentSavings,
  annualRate,
  contribution: monthlyDeposit,
  contributionPlacement: "end",
  withdrawal: (ctx) => ctx.time.index < 120 ? 0 : ctx.savings.openingBalance / 25,
});

modules.savings.withdrawalswithdrawals is a model value for withdrawals in the Savings editor.

Readonly<{ byDivisor(options: { readonly divisor: NumberSource<SavingsContext>; }): Formula<SavingsContext>; }>

const { withdrawals } = modules.savings;

modules.savings.withdrawals.byDivisorwithdrawals.byDivisor provides by divisor in the Savings model editor. Use it when a model needs this operation.

(options: { readonly divisor: NumberSource<SavingsContext>; }): Formula<SavingsContext>

const { savingsPlan, withdrawals } = modules.savings;

const fund = savingsPlan({
  owner: subject,
  calendar: "monthly",
  openingBalance: currentSavings,
  annualRate: investmentReturn,
  contribution: annualDeposit,
  contributionPlacement: "end",
  withdrawal: withdrawals.byDivisor({ divisor: distributionDivisor }),
});

return defineModel({
  name: "savings projection",
  currency: currencies.USD,
  timeline: periods.monthly({ from: "2026-01", count: 120 }),
  preconditions: { currentSavings, investmentReturn, annualDeposit, distributionDivisor },
  entities: { subject },
  components: { fund: fund.component },
  metrics: { ending_balance: (ctx) => ctx.get(fund.balance) },
});

modules.savings.PreparedRetirementProjectionSynchronous retirement calculator. Each invocation validates fresh assumptions and returns a fresh complete report.

Model value shape: (options: PreparedRetirementProjectionOptions) => RetirementProjectionResult

modules.savings.PreparedRetirementProjectionOptionsRetirement assumptions for a prepared calculator; its execution mode is fixed by the factory.

Model value shape: Omit<RetirementProjectionOptions, "execution"> & { readonly execution?: never }

modules.savings.RetirementAnnualRatesAbsolute annual decimal rates keyed by canonical ages such as age65, from age0 through age150. Missing entries use the corresponding mean.

Model value shape: { accumulationReturn?: Readonly<Record<string, number>>; retirementReturn?: Readonly<Record<string, number>>; inflation?: Readonly<Record<string, number>>; incomeIncrease?: Readonly<Record<string, number>>; pensionIncrease?: Readonly<Record<string, number>> }

modules.savings.RetirementPlanRetirementPlan describes a model value used by the Savings editor functions.

Model value shape: { component: ComponentReference<Readonly<Record<string, deccf.ComponentOutputReference>>>; person: EntityReference; asset: EntityReference; accounts: Readonly<Record<"cash" | "portfolio" | "netWorth" | "workingIncome" | "pensionIncome" | "otherIncome" | "investmentIncome" | "expenses", AccountReference>>; flows: Readonly<Record<"pension" | "growth" | "workingIncome" | "otherIncome" | "expenses" | "contribution" | "withdrawal" | "loss", CashflowReference>>; calculations: Readonly<{ readonly year: CalculationReference; readonly history: CalculationReference<RetirementPlanHistory>; readonly projection: CalculationReference<RetirementProjectionResult | null>; }> }

modules.savings.RetirementPlanHistoryFlat settled-period state and cumulative funding facts. Full historical rows are assembled by calculations.projection at the horizon.

Model value shape: { openingPortfolio: number; closingPortfolio: number; legacy: number; depletionAge: number; yearsFunded: number; portfolioLasts: boolean }

modules.savings.RetirementPlanOptionsShared declaration settings for a native retirement component.

Model value shape: { owner?: EntityReference; preconditions?: Readonly<Record<string, InputReference>>; dependsOn?: readonly CalculationReference<unknown>[]; reportSchedule?: ScheduleReference }

modules.savings.RetirementProjectionLifetimeRowAnnual lifetime context from currentAge through lifeExpectancy, including working and retired years.

Model value shape: { age: number; phase: "accumulation" | "retirement"; portfolio: number; closingPortfolio: number; income: number; expenses: number; gap: number }

modules.savings.RetirementProjectionOptionsScalar retirement assumptions in one consistent currency, with decimal annual rates.

Model value shape: { execution?: "timeline" | "legacy"; dynamic?: boolean; annualRates?: RetirementAnnualRates; currentAge: number; retirementAge: number; lifeExpectancy: number; pensionStartAge: number; currentSavings: number; annualSavings: number; annualWorkingIncome?: number; annualWorkingExpenses?: number; includeSavingsInWorkingExpenses?: boolean; preRetirementReturn: number; postRetirementReturn: number; inflation: number; pensionAnnualIncrease: number; … 24 more fields }

modules.savings.RetirementProjectionRateBoundsAnnual rate validation bounds, including sampling and other income growth.

Model value shape: { minimum?: number; maximum?: number }

modules.savings.RetirementProjectionResultRetirementProjectionResult describes a model value used by the Savings editor functions.

Model value shape: { summary: { readonly startingPortfolio: number; readonly yearsUntilRetirement: number; readonly retirementYears: number; readonly bridgeYears: number; readonly legacy: number; readonly yearsFunded: number; readonly fundedUntilAge: number | null; readonly depletionAge: number | null; readonly earliestRetirementAge: number | null; readonly maximumWithdrawalRate: number | null; readonly bridgeWithdrawalRate: number | null; readonly longevityBuffer: number; readonly portfolioLasts: boolean; }; rows: Readonly<Record<string, RetirementProjectionRow>>; lifetimeRows?: Readonly<Record<string, RetirementProjectionLifetimeRow>>; budget: Readonly<Record<string, RetirementProjectionRow>>; whatIf: RetirementProjectionWhatIf; milestones: Readonly<Record<"ten" | "twentyFive" | "thirty" | "thirtyThree", { readonly multiple: number; readonly target: number; readonly coverage: number | null; }>> }

modules.savings.RetirementProjectionRowA retirement year: opening portfolio, beginning-of-year withdrawals, then annual investment growth.

Model value shape: { age: number; year: number; portfolio: number; pensionIncome: number; otherIncome: number; income: number; expenses: number; gap: number; withdrawalRate: number; actualWithdrawal: number; shortfall: number; closingPortfolio: number; funded: boolean; bridge: boolean }

modules.savings.RetirementProjectionThresholdSearchDeterministic threshold bounds and bisection precision.

Model value shape: { minimumRate?: number; maximumRate?: number; iterations?: number }

modules.savings.RetirementProjectionWhatIfDeterministic comparisons; null depletion ages mean no shortfall through horizonAge (default 150).

Model value shape: { delayYearsGain: number; retireNowDepletionAge: number; stopSavingDepletionAge: number; extraSavingsYearsGain: number; extraIncomeDepletionAge: number; lowerExpensesDepletionAge: number; noPensionDepletionAge: number; halfPensionDepletionAge: number; marketCrashDepletionAge: number; higherExpensesDepletionAge: number; inflationBuffer: number; minimumReturn: number }

modules.savings.RetirementProjectionWhatIfOptionsOptional comparison amounts, durations and decimal fractions; partial members retain their defaults.

Model value shape: { delayYears?: number; annualSavingsAfterStopping?: number; extraMonthlySavings?: number; extraMonthlyIncome?: number; lowerExpenseReduction?: number; higherExpenseIncrease?: number; pensionRemoval?: number; pensionReduction?: number; marketCrashLoss?: number }

modules.savings.SavingsContextSavingsContext describes a model value used by the Savings editor functions.

Model value shape: { time: deccf.TimeContext; owner?: EntityReference; savings: SavingsFacts; get: (reference: InputReference | CalculationReference | AccountReference) => number | deccf.Money; curveAt: (reference: InputReference<number>, date: deccf.DateString) => number; draw: (reference: InputReference<number>) => number; sample: (reference: InputReference<number>) => number }

modules.savings.SavingsFactsSavingsFacts describes a model value used by the Savings editor functions.

Model value shape: { openingBalance: number; returnBase: number; growth: number; fee: number; available: number }

modules.savings.SavingsPeriodResultSavingsPeriodResult describes a model value used by the Savings editor functions.

Model value shape: { openingBalance: number; contribution: number; periodRate: number; returnBase: number; growth: number; fee: number; available: number; requestedWithdrawal: number; actualWithdrawal: number; withdrawalShortfall: number; closingBalance: number }

modules.savings.SavingsPlanSavingsPlan describes a model value used by the Savings editor functions.

Model value shape: { component: ComponentReference<Readonly<Record<string, deccf.ComponentOutputReference>>>; balance: FieldReference; fields: Readonly<Record<keyof SavingsPeriodResult, FieldReference>>; calculations: Readonly<Record<string, CalculationReference<unknown>>>; totals: Readonly<Record<"growth" | "withdrawalShortfall" | "fees" | "contributed" | "withdrawn", FieldReference>>; flows: Readonly<{ readonly contribution: CashflowReference; readonly withdrawal: CashflowReference; }> }

modules.savings.SavingsSourceSavingsSource describes a model value used by the Savings editor functions.

Model value shape: number | InputReference<number | deccf.Money> | ((context: SavingsContext) => number)

Pension module

Select this module in model settings to use its names in the portal model editor (modules.pension).

Model editor namePurpose and model value shape
modules.pension.annuityFactorannuityFactor provides annuity factor in the Pension model editor. Use it when a model needs this operation.

(options: { readonly survivalToPayment: readonly number[]; readonly discountFactors: readonly number[]; readonly indexFactors: readonly number[]; readonly guaranteedPayments?: number; }): number

const { annuityFactor } = modules.pension;

modules.pension.applyCapitalEventsapplyCapitalEvents provides apply capital events in the Pension model editor. Use it when a model needs this operation.

(options: { readonly opening: number; readonly transferIn?: number; readonly transferOut?: number; readonly annuitizedCapital?: number; readonly forfeitedCapital?: number; }): Readonly<{ adjustedOpening: number; }>

const { applyCapitalEvents } = modules.pension;

modules.pension.assessmentDeltaassessmentDelta provides assessment delta in the Pension model editor. Use it when a model needs this operation.

(options: { readonly before: number; readonly through: number; readonly evaluate: (cumulativeBasis: number) => number; }): number

const { assessmentDelta } = modules.pension;

modules.pension.assessmentWindowassessmentWindow provides assessment window in the Pension model editor. Use it when a model needs this operation.

(options: { readonly date: string; readonly unit: AssessmentUnit; }): Readonly<{ from: string; toExclusive: string; key: string; }>

const { assessmentWindow } = modules.pension;

modules.pension.careerAverageBenefitcareerAverageBenefit provides career average benefit in the Pension model editor. Use it when a model needs this operation.

(options: { readonly credits: readonly CareerAverageCredit[]; }): number

const { careerAverageBenefit } = modules.pension;

modules.pension.contributionPeriodcontributionPeriod provides contribution period in the Pension model editor. Use it when a model needs this operation.

(options: ContributionPeriodInput): ContributionPeriodResult

const { contributionPeriod } = modules.pension;

modules.pension.createPensionAssumptionscreatePensionAssumptions creates or declares create pension assumptions in the Pension model editor. Use it when a model needs this operation.

(entries: readonly PensionAssumption[]): PensionAssumptionRegistry

const { createPensionAssumptions } = modules.pension;

modules.pension.definedBenefitAmountdefinedBenefitAmount creates or declares defined benefit amount in the Pension model editor. Use it when a model needs this operation.

(options: DefinedBenefitInput): Readonly<Record<BenefitOutput, number>>

const { definedBenefitAmount } = modules.pension;

modules.pension.definedBenefitPensiondefinedBenefitPension creates or declares defined benefit pension in the Pension model editor. Use it when a model needs this operation.

(options: SuppliedAccruedBenefitOptions): PensionPlan<SuppliedAccruedBenefitOutput>
(options: ProjectedRetirementBenefitOptions | CareerAverageBenefitOptions): PensionPlan<ProjectedBenefitOutput>
(options: DefinedBenefitOptions): PensionPlan<ProjectedBenefitOutput> | PensionPlan<SuppliedAccruedBenefitOutput>

const { definedBenefitPension } = modules.pension;

modules.pension.definedContributionPensiondefinedContributionPension creates or declares defined contribution pension in the Pension model editor. Use it when a model needs this operation.

(options: ContributionOnlyOptions): PensionPlan<ContributionOutput>
(options: CapitalPensionOptions): PensionPlan<ContributionOutput | CapitalOutput>
(options: DefinedContributionOptions): PensionPlan<ContributionOutput> | PensionPlan<ContributionOutput | CapitalOutput>

const { definedContributionPension } = modules.pension;

modules.pension.definePensionAgreementProfiledefinePensionAgreementProfile creates or declares define pension agreement profile in the Pension model editor. Use it when a model needs this operation.

(options: DefinePensionAgreementProfileOptions): PensionAgreementProfile

const { definePensionAgreementProfile } = modules.pension;

modules.pension.evaluatePensionAgreementProfileevaluatePensionAgreementProfile provides evaluate pension agreement profile in the Pension model editor. Use it when a model needs this operation.

(options: { readonly profile: PensionAgreementProfile; readonly inputs?: PensionAgreementEvaluationInputs; readonly asOf: string; }): Readonly<{ profileId: string; asOf: string; status: PensionAgreementProfileStatus; operations: readonly Readonly<{ id: string; kind: PensionAgreementOperation["kind"]; eligible: boolean; result: ContributionPeriodResult | Readonly<Record<BenefitOutput, number>>; }>[]; }>

const { evaluatePensionAgreementProfile } = modules.pension;

modules.pension.fixedTermPaymentfixedTermPayment provides fixed term payment in the Pension model editor. Use it when a model needs this operation.

(options: { readonly capital: number; readonly periodRate: number; readonly remainingPayments: number; readonly placement?: "start" | "end"; }): number

const { fixedTermPayment } = modules.pension;

modules.pension.flatPerServiceYearflatPerServiceYear provides flat per service year in the Pension model editor. Use it when a model needs this operation.

(options: { readonly annualAmountPerServiceYear: number; readonly serviceYears: number; }): number

const { flatPerServiceYear } = modules.pension;

modules.pension.fundedPensionCreates a monthly pension-capital component with balanced debit/credit flows. Supply owner, currency, annualReturn and payout.from, payout.months and payout.annualReturn. Amounts use the declared currency; annual return rates are decimals, for example 0.04 for 4%. Values may be declared input or calculation sources. label defaults to "Pensionskapital"; openingCapital and the monthly contribution default to 0. valuedAt is optional: future statement capital enters in its valuation month; older capital must already be valued at model start. payout.from is YYYY-MM or YYYY-MM-01 and months is a positive integer. The model must use monthly periods and the declared currency; opening capital must be nonnegative and annual returns must exceed -1. Growth uses the effective monthly rate on opening capital; contributions enter at month end. From payout start, the explicit payout return applies and the fixed-term payment uses the remaining months, capped to available capital. Register the returned component in model components. accounts exposes capital, equity, revaluation and benefits; flows exposes funding, investmentReturn and withdrawal. outputs exposes payment, capital, contribution, growth and the period record. These flows create no bank payment: connect outputs.payment separately to the person's pension-income flow. No tax or lifetime-insurance assumptions are inferred. Each repeated pension receives separate accounts.

(options: FundedPensionOptions): Readonly<{ component: ComponentReference; accounts: Readonly<Record<"capital" | "equity" | "revaluation" | "benefits", AccountReference>>; flows: Readonly<Record<"funding" | "investmentReturn" | "withdrawal", CashflowReference>>; outputs: Readonly<{ payment: CalculationProjectionReference; capital: AccountReference; contribution: CalculationProjectionReference; growth: CalculationProjectionReference; period: CalculationReference; }>; }>

const { fundedPension } = modules.pension;

const pension = fundedPension({
  owner: person,
  currency: currencies.SEK,
  openingCapital: statementCapital,
  valuedAt: statementDate,
  contribution: monthlyPremium,
  annualReturn: stockGrowth,
  payout: { from: firstPayoutMonth, months: payoutMonths, annualReturn: payoutReturn },
});

modules.pension.indexBenefitindexBenefit provides index benefit in the Pension model editor. Use it when a model needs this operation.

(options: { readonly annualBenefit: number; readonly indexFactor: number; }): number

const { indexBenefit } = modules.pension;

modules.pension.monthlySurvivalmonthlySurvival provides monthly survival in the Pension model editor. Use it when a model needs this operation.

(options: { readonly entry: PensionAssumption; readonly dateOfBirth: string; readonly valuationDate: string; readonly paymentDates: readonly string[]; }): readonly number[]

const { monthlySurvival } = modules.pension;

modules.pension.PENSION_AGREEMENT_PROFILE_STATUSESPENSION_AGREEMENT_PROFILE_STATUSES is a model value for pension agreement profile statuses in the Pension editor.

readonly PensionAgreementProfileStatus[]

const { PENSION_AGREEMENT_PROFILE_STATUSES } = modules.pension;

modules.pension.qualifiedServiceMonthsqualifiedServiceMonths provides qualified service months in the Pension model editor. Use it when a model needs this operation.

(options: { readonly intervals: readonly { readonly from: string; readonly toExclusive: string; }[]; }): number

const { qualifiedServiceMonths } = modules.pension;

modules.pension.resolvePensionAgreementProfileresolvePensionAgreementProfile resolves resolve pension agreement profile in the Pension model editor. Use it when a model needs this operation.

(profiles: readonly PensionAgreementProfile[], options: { readonly id: string; readonly asOf: string; readonly birthDate?: string; }): PensionAgreementProfile

const { resolvePensionAgreementProfile } = modules.pension;

modules.pension.serviceFractionserviceFraction provides service fraction in the Pension model editor. Use it when a model needs this operation.

(options: { readonly creditedMonths: number; readonly fullMonths: number; readonly cap?: number; }): number

const { serviceFraction } = modules.pension;

modules.pension.AssessmentUnitAssessmentUnit describes a model value used by the Pension editor functions.

Model value shape: "month" | "half-year" | "year"

modules.pension.BenefitBandBenefitBand describes a model value used by the Pension editor functions.

Model value shape: { lower: T; upper: T; rate: T }

modules.pension.BenefitOutputBenefitOutput describes a model value used by the Pension editor functions.

Model value shape: "grossAnnual" | "offsetAnnual" | "protectedAnnual" | "normalAnnual" | "payableAnnual" | "payableMonthly"

modules.pension.BenefitPolicyBenefitPolicy describes a model value used by the Pension editor functions.

Model value shape: { annualSalaryBasis: PensionSource; bands: readonly BenefitBand<PensionSource>[]; serviceFactor: PensionSource; offsetAnnual?: PensionSource; protectedAnnual?: PensionSource; retirementFactor?: PensionSource; id: string; version: string }

modules.pension.CapitalOutputCapitalOutput describes a model value used by the Pension editor functions.

Model value shape: "openingCapital" | "periodReturn" | "investmentReturn" | "capitalFee" | "grossPension" | "withdrawalShortfall" | "closingCapital"

modules.pension.CapitalPensionOptionsCapitalPensionOptions describes a model value used by the Pension editor functions.

Model value shape: CommonPensionOptions & PensionWindow & ReturnOptions & { readonly calculationScope: "capital-and-benefit"; readonly contributionPolicy: ContributionPolicy; readonly openingCapital: PensionSource; readonly contributionPlacement: "start" | "end"; readonly capitalFeeRate?: PensionSource; readonly crediting: "accrual-projection"; readonly withdrawalPolicy: { readonly type: "none" } | (PensionWindow & { readonly type: "amount"; readonly amount: PensionSource }); }

modules.pension.CareerAverageBenefitOptionsCareerAverageBenefitOptions describes a model value used by the Pension editor functions.

Model value shape: { basis: { readonly mode: "career-average"; }; benefitPolicy: CareerAverageBenefitPolicy; withdrawal?: PensionWindow & { readonly from: string; }; id: string; owner: EntityReference; currency: Currency; cashflows?: "person" | "none"; preconditions?: Readonly<Record<string, InputReference<number>>>; dependsOn?: readonly CalculationReference<unknown>[]; readsAccountsFrom?: readonly AccountReference[] }

modules.pension.CareerAverageBenefitPolicyCareerAverageBenefitPolicy describes a model value used by the Pension editor functions.

Model value shape: { credits: readonly { readonly annualSalary: PensionSource; readonly accrualRate: PensionSource; readonly revaluationFactor: PensionSource; }[]; serviceFactor?: PensionSource; offsetAnnual?: PensionSource; protectedAnnual?: PensionSource; retirementFactor?: PensionSource; id: string; version: string }

modules.pension.CareerAverageCreditCareerAverageCredit describes a model value used by the Pension editor functions.

Model value shape: { annualSalary: number; accrualRate: number; revaluationFactor: number }

modules.pension.CommonPensionOptionsCommonPensionOptions describes a model value used by the Pension editor functions.

Model value shape: { id: string; owner: EntityReference; currency: Currency; cashflows?: "person" | "none"; preconditions?: Readonly<Record<string, InputReference<number>>>; dependsOn?: readonly CalculationReference<unknown>[]; readsAccountsFrom?: readonly AccountReference[] }

modules.pension.ContributionBandContributionBand describes a model value used by the Pension editor functions.

Model value shape: { id: string; contributionKey: string; payer: "employer" | "employee"; lower: T; upper: T; rate: T }

modules.pension.ContributionOnlyOptionsContributionOnlyOptions describes a model value used by the Pension editor functions.

Model value shape: { calculationScope: "contributions"; contributionPolicy: ContributionPolicy; id: string; owner: EntityReference; currency: Currency; cashflows?: "person" | "none"; preconditions?: Readonly<Record<string, InputReference<number>>>; dependsOn?: readonly CalculationReference<unknown>[]; readsAccountsFrom?: readonly AccountReference[]; from?: string; toExclusive?: string }

modules.pension.ContributionOutputContributionOutput describes a model value used by the Pension editor functions.

Model value shape: "employerPremium" | "employeePremium" | "additionalPremium" | "premiumBeforeCharges" | "premiumCharge" | "netPremium" | "employerCost" | "subsidy" | "cashCompensation"

modules.pension.ContributionPeriodInputContributionPeriodInput describes a model value used by the Pension editor functions.

Model value shape: { salary: T; bands: readonly ContributionBand<T>[]; eligible: T; fixedEmployer?: T; fixedEmployee?: T; employeeElection?: T; employerMatch?: { readonly rate: T; readonly eligibleEmployeeAmount: T; readonly eligibleAmountCap: T; }; additionalContributions?: readonly { readonly id: string; readonly payer: "employer" | "employee"; readonly amount: T; }[]; premiumCharge?: T; employerCost?: T; employerCostDiscounts?: readonly { readonly bandId: string; readonly rate: T; }[]; cashCompensation?: T }

modules.pension.ContributionPeriodResultContributionPeriodResult describes a model value used by the Pension editor functions.

Model value shape: Readonly<Record<ContributionOutput, number>> & { readonly bandAmounts: Readonly<Record<string, number>> }

modules.pension.ContributionPolicyContributionPolicy describes a model value used by the Pension editor functions.

Model value shape: { assessmentPeriod: AssessmentUnit; periodSeed?: { readonly key: string; readonly cumulativeSalary: number; readonly fixedAssessmentPaid?: boolean; }; salary: PensionSource; bands: readonly ContributionBand<PensionSource>[]; eligible: PensionSource; fixedEmployer?: PensionSource; fixedEmployee?: PensionSource; employeeElection?: PensionSource; employerMatch?: { readonly rate: PensionSource; readonly eligibleEmployeeAmount: PensionSource; readonly eligibleAmountCap: PensionSource; }; additionalContributions?: readonly { readonly id: string; readonly payer: "employer" | "employee"; readonly amount: PensionSource; }[]; premiumCharge?: PensionSource; employerCost?: PensionSource; employerCostDiscounts?: readonly { readonly bandId: string; readonly rate: PensionSource; }[]; cashCompensation?: PensionSource; id: string; version: string }

modules.pension.DbFinalSalaryOperationDbFinalSalaryOperation describes a model value used by the Pension editor functions.

Model value shape: { id: string; kind: "db-final-salary"; eligibility?: PensionAgreementEligibility; birthYearRange?: { readonly birthYearFrom?: number; readonly birthYearThrough?: number; }; bands: readonly { readonly lower: Exclude<PensionAgreementBoundary, null>; readonly upper: PensionAgreementBoundary; readonly rate: PensionAgreementRate; }[]; fullServiceMonths: number; minimumServiceMonths?: number }

modules.pension.DcBandedContributionOperationDcBandedContributionOperation describes a model value used by the Pension editor functions.

Model value shape: { id: string; kind: "dc-banded-contribution"; salaryPeriod: "month" | "year"; eligibility?: PensionAgreementEligibility; birthYearRange?: { readonly birthYearFrom?: number; readonly birthYearThrough?: number; }; bands: readonly PensionAgreementBand[] }

modules.pension.DefinedBenefitInputDefinedBenefitInput describes a model value used by the Pension editor functions.

Model value shape: { annualSalaryBasis: T; bands: readonly BenefitBand<T>[]; serviceFactor: T; offsetAnnual?: T; protectedAnnual?: T; retirementFactor?: T }

modules.pension.DefinedBenefitOptionsDefinedBenefitOptions describes a model value used by the Pension editor functions.

Model value shape: ProjectedRetirementBenefitOptions | CareerAverageBenefitOptions | SuppliedAccruedBenefitOptions

modules.pension.DefinedContributionOptionsDefinedContributionOptions describes a model value used by the Pension editor functions.

Model value shape: ContributionOnlyOptions | CapitalPensionOptions

modules.pension.DefinePensionAgreementProfileOptionsDefinePensionAgreementProfileOptions describes a model value used by the Pension editor functions.

Model value shape: { id: string; name: string; sector: string; variant?: string; validFrom: string; validToExclusive?: string; birthYearRange?: { readonly birthYearFrom?: number; readonly birthYearThrough?: number; }; status: PensionAgreementProfileStatus; coverageNote: string; sources: readonly PensionAgreementSource[]; operations: readonly PensionAgreementOperation[] }

modules.pension.FundedPensionOptionsFundedPensionOptions describes a model value used by the Pension editor functions.

Model value shape: { owner: EntityReference; currency: Currency; label?: string | InputReference<string> | InputProjectionReference<string>; openingCapital?: PensionAmountSource; valuedAt?: PensionDateSource; contribution?: PensionAmountSource; annualReturn: PensionAmountSource; payout: { readonly from: PensionDateSource; readonly months: PensionAmountSource; readonly annualReturn: PensionAmountSource; } }

modules.pension.PensionAgreementBandPensionAgreementBand describes a model value used by the Pension editor functions.

Model value shape: { id: string; lower: PensionAgreementBoundary; upper: PensionAgreementBoundary; rate: PensionAgreementRate; contributionKey?: string; payer?: "employer" | "employee" }

modules.pension.PensionAgreementBoundaryPensionAgreementBoundary describes a model value used by the Pension editor functions.

Model value shape: number | null | { readonly kind: "income-base-amount" | "price-base-amount"; readonly multiple: number; }

modules.pension.PensionAgreementEligibilityPensionAgreementEligibility describes a model value used by the Pension editor functions.

Model value shape: { fromAge?: number; fromAgeMonthOffset?: number; toAgeExclusive?: number; throughAge?: number; activeEmployment?: true; employmentStartBeforeAge?: number; requiredDecisions?: readonly string[] }

modules.pension.PensionAgreementEvaluationInputsPensionAgreementEvaluationInputs describes a model value used by the Pension editor functions.

Model value shape: { readonly birthDate?: string; readonly employmentStartDate?: string; readonly employmentEndDate?: string; readonly eligibilityDecisions?: Readonly<Record<string, { readonly status: "eligible" | "ineligible"; readonly source: string; }>>; readonly monthlyPensionableSalary?: number; readonly annualPensionableSalary?: number; readonly annualSalaryBasis?: number; readonly creditedServiceMonths?: number; readonly incomeBaseAmount?: number; readonly priceBaseAmount?: number; readonly offsetAnnual?: number; readonly protectedAnnual?: number; readonly retirementFactor?: number; }

modules.pension.PensionAgreementOperationPensionAgreementOperation describes a model value used by the Pension editor functions.

Model value shape: DcBandedContributionOperation | DbFinalSalaryOperation

modules.pension.PensionAgreementProfilePensionAgreementProfile describes a model value used by the Pension editor functions.

Model value shape: { kind: "deccf-pension-agreement-profile"; operations: readonly PensionAgreementOperation[]; id: string; name: string; sector: string; variant?: string; validFrom: string; validToExclusive?: string; birthYearRange?: { readonly birthYearFrom?: number; readonly birthYearThrough?: number; }; status: PensionAgreementProfileStatus; coverageNote: string; sources: readonly PensionAgreementSource[] }

modules.pension.PensionAgreementProfileStatusPensionAgreementProfileStatus describes a model value used by the Pension editor functions.

Model value shape: "supported" | "partial" | "statement-only"

modules.pension.PensionAgreementRatePensionAgreementRate describes a model value used by the Pension editor functions.

Model value shape: number | { readonly kind: "birth-year-table"; readonly values: Readonly<Record<number, number>>; } | { readonly kind: "age-step"; readonly atAge: number; readonly before: number; readonly from: number; }

modules.pension.PensionAgreementSourcePensionAgreementSource describes a model value used by the Pension editor functions.

Model value shape: { title: string; url: string; section?: string }

modules.pension.PensionAmountSourcePensionAmountSource describes a model value used by the Pension editor functions.

Model value shape: number | Money | InputReference<number | Money> | InputProjectionReference<number | Money> | CalculationReference | CalculationProjectionReference | ExpressionReference | ((context: CalculationContext) => number | Money)

modules.pension.PensionAssumptionPensionAssumption describes a model value used by the Pension editor functions.

Model value shape: { id: string; version: string; kind: "mortality-qx"; validFrom: string; validTo: string; source: string; units: "annual-probability"; population: string; sexBasis: string; cohortBasis: string; startingAge: number; qx: readonly number[]; interpolation: "constant-force"; terminalRule: { readonly type: "extend-last"; } | { readonly type: "max-age"; readonly age: number; } }

modules.pension.PensionAssumptionRegistryPensionAssumptionRegistry describes a model value used by the Pension editor functions.

Model value shape: { entries: readonly PensionAssumption[]; get: (options: { readonly id: string; readonly version: string; readonly at: string; }) => PensionAssumption }

modules.pension.PensionContextDeliberately excludes current fields/flows and arbitrary model reads.

Model value shape: { time: TimeContext; owner?: EntityReference; get: (reference: InputReference<number> | CalculationReference | AccountReference) => number; curveAt: (reference: InputReference<number>, date: string) => number; draw: (reference: InputReference<number>) => number; sample: (reference: InputReference<number>) => number }

modules.pension.PensionDateSourcePensionDateSource describes a model value used by the Pension editor functions.

Model value shape: string | InputReference<string | null> | InputProjectionReference<string | null> | ((context: CalculationContext) => string)

modules.pension.PensionFormulaPensionFormula describes a model value used by the Pension editor functions.

Model value shape: ((context: PensionContext) => number) & { readonly preconditions?: Readonly<Record<string, InputReference<number>>>; }

modules.pension.PensionMetadataPensionMetadata describes a model value used by the Pension editor functions.

Model value shape: { id: string; currency: string; calendar: "monthly"; kind: "defined-contribution" | "defined-benefit"; basisStatus: "projection" | "supplied-accrued"; policy?: PolicyIdentity; source?: string; valuedAt?: string; calculationScope?: "contributions" | "capital-and-benefit"; crediting?: "accrual-projection"; basis?: "career-average" | "supplied-accrued" | "projected-retirement" }

modules.pension.PensionPlanPensionPlan describes a model value used by the Pension editor functions.

Model value shape: { component: ComponentReference<Readonly<Record<string, deccf.ComponentOutputReference>>>; calculations: Readonly<Record<K, CalculationReference<unknown>>>; fields: Readonly<Record<K, FieldReference>>; flows: Readonly<Partial<Record<"pension" | "employeePremium", CashflowReference>>>; metadata: PensionMetadata }

modules.pension.PensionSourceNumeric amounts use the plan currency. Money inputs are not supported in this first slice.

Model value shape: number | InputReference<number> | PensionFormula

modules.pension.PensionWindowPensionWindow describes a model value used by the Pension editor functions.

Model value shape: { from?: string; toExclusive?: string }

modules.pension.PolicyIdentityPolicyIdentity describes a model value used by the Pension editor functions.

Model value shape: { id: string; version: string }

modules.pension.ProjectedBenefitOutputProjectedBenefitOutput describes a model value used by the Pension editor functions.

Model value shape: BenefitOutput | "grossPension"

modules.pension.ProjectedRetirementBenefitOptionsProjectedRetirementBenefitOptions describes a model value used by the Pension editor functions.

Model value shape: { basis: { readonly mode: "projected-retirement"; }; benefitPolicy: BenefitPolicy; withdrawal?: PensionWindow & { readonly from: string; }; id: string; owner: EntityReference; currency: Currency; cashflows?: "person" | "none"; preconditions?: Readonly<Record<string, InputReference<number>>>; dependsOn?: readonly CalculationReference<unknown>[]; readsAccountsFrom?: readonly AccountReference[] }

modules.pension.ReturnOptionsReturnOptions describes a model value used by the Pension editor functions.

Model value shape: | { readonly periodReturn: PensionSource; readonly annualReturn?: never; readonly returnConvention?: never } | { readonly annualReturn: PensionSource; readonly returnConvention: "nominal" | "effective"; readonly periodReturn?: never }

modules.pension.SuppliedAccruedBenefitOptionsSuppliedAccruedBenefitOptions describes a model value used by the Pension editor functions.

Model value shape: { basis: { readonly mode: "supplied-accrued"; readonly annualBenefit: PensionSource; readonly valuedAt: string; readonly source: string; readonly indexFactor?: PensionSource; readonly retirementFactor?: PensionSource; }; benefitPolicy?: never; withdrawal?: PensionWindow & { readonly from: string; }; id: string; owner: EntityReference; currency: Currency; cashflows?: "person" | "none"; preconditions?: Readonly<Record<string, InputReference<number>>>; dependsOn?: readonly CalculationReference<unknown>[]; readsAccountsFrom?: readonly AccountReference[] }

modules.pension.SuppliedAccruedBenefitOutputSuppliedAccruedBenefitOutput describes a model value used by the Pension editor functions.

Model value shape: "suppliedAnnual" | "payableAnnual" | "payableMonthly" | "grossPension"

Swedish Pension module

Select this module in model settings to use its names in the portal model editor (modules["swedish-pension"]).

Model editor namePurpose and model value shape
modules["swedish-pension"].comparePayoutScenarioscomparePayoutScenarios compares compare payout scenarios in the Swedish Pension model editor. Use it when a model needs this operation.

(options: { readonly pensionCase: SwedishPensionCase; readonly scenarios: readonly PensionPayoutScenario[]; }): readonly PensionScenarioResult[]

const { comparePayoutScenarios } = modules["swedish-pension"];

modules["swedish-pension"].createPensionCasecreatePensionCase creates or declares create pension case in the Swedish Pension model editor. Use it when a model needs this operation.

(options: { readonly id: string; readonly birthDate: string; readonly rights: readonly SwedishPensionRight[]; readonly currentEmployment?: SwedishPensionCurrentEmployment; }): SwedishPensionCase

const { createPensionCase } = modules["swedish-pension"];

modules["swedish-pension"].evaluateSwedishPensionAgreementevaluateSwedishPensionAgreement provides evaluate swedish pension agreement in the Swedish Pension model editor. Use it when a model needs this operation.

(options: { readonly id: string; readonly asOf: string; readonly inputs?: PensionAgreementEvaluationInputs; }): ReturnType<typeof evaluatePensionAgreementProfile>

const { evaluateSwedishPensionAgreement } = modules["swedish-pension"];

modules["swedish-pension"].isSwedishPensionCaseisSwedishPensionCase provides is swedish pension case in the Swedish Pension model editor. Use it when a model needs this operation.

(value: unknown): value is SwedishPensionCase

const { isSwedishPensionCase } = modules["swedish-pension"];

modules["swedish-pension"].listSwedishPensionAgreementslistSwedishPensionAgreements lists list swedish pension agreements in the Swedish Pension model editor. Use it when a model needs this operation.

(options?: { readonly coverage?: PensionAgreementProfileStatus | readonly PensionAgreementProfileStatus[]; }): readonly SwedishPensionAgreementCatalogEntry[]

const { listSwedishPensionAgreements } = modules["swedish-pension"];

modules["swedish-pension"].pensionAgreementInputpensionAgreementInput provides pension agreement input in the Swedish Pension model editor. Use it when a model needs this operation.

(options?: { readonly value?: string; readonly includePartial?: boolean; readonly includeStatementOnly?: boolean; readonly ui?: Readonly<Record<string, unknown>>; }): InputReference<string>

const { pensionAgreementInput } = modules["swedish-pension"];

modules["swedish-pension"].resolveSwedishPensionAgreementresolveSwedishPensionAgreement resolves resolve swedish pension agreement in the Swedish Pension model editor. Use it when a model needs this operation.

(id: string, options: { readonly asOf: string; readonly birthDate?: string; }): PensionAgreementProfile

const { resolveSwedishPensionAgreement } = modules["swedish-pension"];

modules["swedish-pension"].swedishPensionAgreementCatalogswedishPensionAgreementCatalog provides swedish pension agreement catalog in the Swedish Pension model editor. Use it when a model needs this operation.

(): readonly PensionAgreementProfile[]

const { swedishPensionAgreementCatalog } = modules["swedish-pension"];

modules["swedish-pension"].swedishPensionForecastComposes a one-person Swedish pension forecast from explicit statements and dated agreement rules. Supply all option groups; there are no implicit salary, statement, agreement or return defaults. startYear and person.birthYear are integer inputs; person.members must contain exactly one person with an explicit dateOfBirth matching birthYear. Money amounts use SEK, annual return and growth assumptions are decimal rates, and payout ages/durations use years. work supplies monthlySalary, employment startDate, lastYear, agreement, agreementChangeYear, agreementAfterChange, fallbackAnnualContribution and incomeBaseAmount. A positive change year switches agreements from that year. pensions supplies public/premium annual-benefit statements, occupational DC capital or DB annual-benefit rows, and the future-premium payout window. Each statement needs its value date and source. assumptions supplies inflation, generalSalaryGrowth, individualSalaryGrowth, stockGrowth and payoutRate. Optional rates supplies numeric calculation references under any of those five names. Missing entries use the corresponding assumption input. The required assumptions remain editable means, also used to value periods before forecast start. Reading a distribution assumption with get does not draw a sample. Bind a declared hidden distribution with bind.sample(...,{calendar:"annual"}) in each source calculation to opt into annual Monte Carlo uncertainty. Rates are annual decimals and must be finite and greater than -1. Register source calculations in the model. Callback, projection and unknown rate entries are unsupported. Salary and benefit inflation accumulate each January after their base year, preserving earlier years' factors and the initial observation. DC growth uses each current annual rate converted to an effective monthly rate; payoutRate applies from payout start and recalculates the remaining payment. DB inflation adjustments stop at their payout-start year. The returned monthly timeline starts in January of startYear and continues through the 85th-birthday year, with a minimum of twelve months. Register component and use timeline in the model. DC rights and future premiums use fundedPension accounts/flows; DB rights retain their stated annual benefits. Missing agreement rules or required rule inputs use the explicit annual fallback contribution, divided into monthly premiums, with a visible status. incomes exposes salary, publicPension and occupationalPension for householdPeople to book bank income and calculate tax. Pension-capital flows do not duplicate those bank payments. reports and outputs expose gross pension parts, premium status and annualPensionSnapshot; household net income is separate. Payouts start in the person's birth month at the specified age. No historic rights, lifetime insurance factors or future tax legislation are invented; household tax continues to use its explicitly supported tax-rule version.

(options: SwedishPensionForecastOptions): Readonly<{ component: ComponentReference; timeline: Timeline; reports: Readonly<Record<string, CalculationReference>>; incomes: Readonly<Record<"salary" | "publicPension" | "occupationalPension", { readonly amount: CalculationReference; readonly code: string; }>>; outputs: Readonly<Record<"salary" | "publicPension" | "occupationalPension" | "premium" | "annualPensionSnapshot" | "pensionPartValues", CalculationReference>>; }>

const { input, calculation, bind, currencies, entity } = deccf;

const SEK = currencies.SEK;

const owner = entity.party({ label: "Pension forecast" });

const statement = input.object({
  name: input.str("Statement"), annualAmount: input.money(120000, SEK),
  valueDate: input.date("2026-01-01"), startAge: input.integer(67),
  durationYears: input.integer(19), source: input.str("My pension statement"),
});

const assumptions = {
  inflation: input.rate(0.02), generalSalaryGrowth: input.rate(0.03),
  individualSalaryGrowth: input.rate(0.01), stockGrowth: input.rate(0.05),
  payoutRate: input.rate(0.02),
};

const stockShock = input.normal({ mean: 0, stdev: 0.15 }, { visible: false });

const stockReturn = calculation({
  name: "stockReturn",
  bindings: {
    mean: assumptions.stockGrowth,
    shock: bind.sample(stockShock, { calendar: "annual" }),
  },
  calculate: ({ mean, shock }) => Math.max(-0.99, mean + shock),
});

const forecast = modules["swedish-pension"].swedishPensionForecast({
  owner, startYear: input.integer(2026),
  person: {
    birthYear: input.integer(1960),
    members: input.objectArray([
      { id: input.id("person"), dateOfBirth: input.date("1960-06-15") },
    ]),
  },
  work: {
    monthlySalary: input.money(48000, SEK), startDate: input.date("2010-01-01"),
    lastYear: input.integer(2027), agreement: input.str("itp1"),
    agreementChangeYear: input.integer(0), agreementAfterChange: input.str("akap-kr"),
    fallbackAnnualContribution: input.money(36000, SEK),
    incomeBaseAmount: input.money(83400, SEK),
  },
  pensions: {
    public: statement, premium: statement,
    occupational: input.objectArray([{
      id: input.id("dc"), name: input.str("Occupational statement"),
      rightType: input.str("dc-capital"), agreementId: input.str("itp1"),
      amount: input.money(1250000, SEK), valueDate: input.date("2026-01-01"),
      startAge: input.integer(67), durationYears: input.integer(10),
      source: input.str("My capital statement"),
    }]),
    future: { startAge: input.integer(67), durationYears: input.integer(20) },
  },
  assumptions,
  rates: { stockGrowth: stockReturn },
});

return deccf.defineModel({
  currency: SEK, timeline: forecast.timeline, entities: { owner },
  preconditions: { stockShock }, calculations: { stockReturn },
  components: { pension: forecast.component },
  metrics: { pension: deccf.metric({ value: forecast.outputs.occupationalPension }) },
});

modules["swedish-pension"].swedishPensionProfilesswedishPensionProfiles is a model value for swedish pension profiles in the Swedish Pension editor.

readonly PensionAgreementProfile[]

const { swedishPensionProfiles } = modules["swedish-pension"];

modules["swedish-pension"].PensionPayoutScenarioPensionPayoutScenario describes a model value used by the Swedish Pension editor functions.

Model value shape: { id: string; label: string; startDate: string; payouts: Readonly<Record<string, PensionRightPayout>> }

modules["swedish-pension"].PensionRightPayoutPensionRightPayout describes a model value used by the Swedish Pension editor functions.

Model value shape: | { readonly form: "exclude"; readonly reason?: string } | { readonly form: "fixed-term"; readonly remainingPayments: number; readonly periodRate: number; readonly placement: "start" | "end" } | { readonly form: "lifetime"; readonly factorSource: string; readonly annuityFactor: number } | { readonly form: "lifetime"; readonly factorSource: string; readonly survivalToPayment: readonly number[]; readonly discountFactors: readonly number[]; readonly indexFactors: readonly number[]; readonly guaranteedPayments?: number } | { readonly form: "db-statement"; readonly statementPayableFrom: string; readonly benefitFactor?: number; readonly factorSource?: string }

modules["swedish-pension"].PensionScenarioResultPensionScenarioResult describes a model value used by the Swedish Pension editor functions.

Model value shape: { id: string; label: string; startDate: string; currency: "SEK"; grossMonthly: number; annualizedGross: number; basisStatus: "statement" | "assumption-based"; rights: readonly PensionScenarioRightResult[] }

modules["swedish-pension"].PensionScenarioRightResultPensionScenarioRightResult describes a model value used by the Swedish Pension editor functions.

Model value shape: { rightId: string; agreementId: string; kind: "dc-capital" | "db-annual-benefit"; excluded?: true; exclusionReason?: string; product?: string; payoutForm?: "exclude" | "fixed-term" | "lifetime" | "db-statement"; grossMonthly?: number; annualizedGross?: number; basisStatus?: "statement" | "assumption-based"; assumptions?: Readonly<Record<string, string | number>> }

modules["swedish-pension"].SwedishPensionAgreementCatalogEntrySwedishPensionAgreementCatalogEntry describes a model value used by the Swedish Pension editor functions.

Model value shape: { id: string; name: string; sector: string; variant?: string; status: PensionAgreementProfileStatus; coverageNote: string; validFrom: string; validToExclusive?: string; sources: readonly modules.pension.PensionAgreementSource[] }

modules["swedish-pension"].SwedishPensionCaseSwedishPensionCase describes a model value used by the Swedish Pension editor functions.

Model value shape: { kind: "deccf-swedish-pension-case"; id: string; birthDate: string; rights: readonly SwedishPensionRight[]; currentEmployment?: SwedishPensionCurrentEmployment }

modules["swedish-pension"].SwedishPensionCurrentEmploymentSwedishPensionCurrentEmployment describes a model value used by the Swedish Pension editor functions.

Model value shape: { agreementId: string; startDate: string; endDate?: string; annualPensionableSalary?: number; source: string }

modules["swedish-pension"].SwedishPensionDbRightSwedishPensionDbRight describes a model value used by the Swedish Pension editor functions.

Model value shape: { id: string; kind: "db-annual-benefit"; annualAmount: number; currency: "SEK"; valuedAt: string; agreementId: string; payableFrom?: string; product?: string; source: string }

modules["swedish-pension"].SwedishPensionDcRightSwedishPensionDcRight describes a model value used by the Swedish Pension editor functions.

Model value shape: { id: string; kind: "dc-capital"; amount: number; currency: "SEK"; valuedAt: string; agreementId: string; product?: string; source: string }

modules["swedish-pension"].SwedishPensionForecastOptionsSwedishPensionForecastOptions describes a model value used by the Swedish Pension editor functions.

Model value shape: { owner: EntityReference; startYear: InputReference<number>; person: { readonly birthYear: InputReference<number>; readonly members: InputReference<readonly Record<string, InputValue>[]>; }; work: { readonly monthlySalary: InputReference<Money>; readonly startDate: InputReference<string | null>; readonly lastYear: InputReference<number>; readonly agreement: InputReference<string>; readonly agreementChangeYear: InputReference<number>; readonly agreementAfterChange: InputReference<string>; readonly fallbackAnnualContribution: InputReference<Money>; readonly incomeBaseAmount: InputReference<Money>; }; pensions: { readonly public: InputReference<SwedishPensionStatement>; readonly premium: InputReference<SwedishPensionStatement>; readonly occupational: ObjectArrayInputReference; readonly future: { readonly startAge: InputReference<number>; readonly durationYears: InputReference<number>; }; }; assumptions: Readonly<Record<"inflation" | "generalSalaryGrowth" | "individualSalaryGrowth" | "stockGrowth" | "payoutRate", InputReference<number>>>; rates?: Readonly<Partial<Record<"inflation" | "generalSalaryGrowth" | "individualSalaryGrowth" | "stockGrowth" | "payoutRate", CalculationReference<number>>>> }

modules["swedish-pension"].SwedishPensionRightSwedishPensionRight describes a model value used by the Swedish Pension editor functions.

Model value shape: SwedishPensionDcRight | SwedishPensionDbRight

modules["swedish-pension"].SwedishPensionStatementSwedishPensionStatement describes a model value used by the Swedish Pension editor functions.

Model value shape: { readonly name: string; readonly annualAmount: Money; readonly valueDate: string | null; readonly startAge: number; readonly durationYears: number; readonly source: string; }

Housing module

Select this module in model settings to use its names in the portal model editor (modules.housing).

Model editor namePurpose and model value shape
modules.housing.propertyPlanpropertyPlan({owner,cashAccount,...options}) returns {component,outputs,accounts,reportGroups,operatingCosts}; register component once. One property's monthly asset/cost/transactions, in model currency. openingValue/monthlyCost/annualGrowth default 0; growth compounds monthly. amortizationValue is separate regulatory value. operatingCosts replaces monthlyCost with named amount/code lines. purchase/sale require zero-based atPeriod and price; costs default 0, enabled true. Purchase is period start, sale period end; capitalizeCosts defaults false. Opening assets cannot also be purchased; sale cannot precede purchase. ownership/paymentShares use owners (keyed entities/repeated output) and weights by stable ID: keyed numeric sources, repeated columns or repeated numeric calculation outputs. Register source repeats. Legal weights sum to one; payment weights are nonnegative/proportional with positive total. Omitted owner weights are zero; unknown/negative/nonnumeric weights reject. Omitted allocations use owner. label names reports; accounts supplies compatible owner/type mappings, distinct per home. Outputs include numeric marketValue/carryingValue/regulatoryValue/active/costs/book gain, payment flows and Money breakdown. Invalid timing/currency/amounts/allocations reject. Loans/tax/eligibility stay separate; see Property plans for accounts/reports.

(options: PropertyPlanOptions): PropertyPlan

// Select Housing, Account plans and Swedish family benefits.
const members = deccf.input.objectArray([
  {id: deccf.input.id("anna"), share: deccf.input.fraction(0.5)},
  {id: deccf.input.id("erik"), share: deccf.input.fraction(0.5)},
]);
const owner = deccf.entity.party();
const cash = deccf.account({owner, type: "asset", initial: 10000});
const person = deccf.entity.party({owner});
const people = deccf.repeat(members, deccf.component({entities: {person}, outputs: {person}}));
const weight = deccf.calculation({
  name: "Ownership weight", calculate: deccf.expr.multiply(members.item.data.share, 1),
});
const allocations = deccf.repeat(members, deccf.component({calculations: {weight}, outputs: {weight}}));
const expense = modules.accountplan.reallocateExpense({
  from: owner, to: people.outputs.person, code: "expense.housing.mortgage_interest",
  amount: 100, weights: allocations.outputs.weight,
});
const benefits = modules["swedish-family-benefits"].swedishFamilyBenefits({
  owner, recipients: people.outputs.person, profile: "household",
  children: [{id: "kim", parent: "shared", benefitKind: "child", householdShare: "half"}],
});
const home = modules.housing.propertyPlan({
  owner, cashAccount: cash, openingValue: 1000000, monthlyCost: 100,
  ownership: {owners: people.outputs.person, weights: allocations.outputs.weight},
  paymentShares: {owners: people.outputs.person, weights: allocations.outputs.weight},
});
return deccf.defineModel({
  currency: deccf.currencies.SEK,
  timeline: deccf.periods.monthly({from: "2026-01", count: 1}),
  preconditions: {members}, entities: {owner}, accounts: {cash},
  components: {people, allocations, expense, benefits: benefits.component, home: home.component},
});
 

modules.housing.symProvides built-in numeric domains for common positive and percentage inputs.

Readonly<{ keepSellBuy(language?: "en" | "sv"): readonly EnumOption<"keep" | "sell" | "buy">[]; }>

const { sym } = modules.housing;

modules.housing.sym.keepSellBuysym.keepSellBuy provides keep sell buy in the Housing model editor. Use it when a model needs this operation.

(language?: "en" | "sv"): readonly EnumOption<"keep" | "sell" | "buy">[]

const homeDecision = input.enum('keep', {
  options: modules.housing.sym.keepSellBuy('en'),
});

modules.housing.PropertyAccountsPropertyAccounts describes a model value used by the Housing editor functions.

Model value shape: { assets: Readonly<Record<string, AccountReference>>; equity: Readonly<Record<string, AccountReference>>; operating: Readonly<Record<string, Readonly<Record<string, AccountReference>>>>; purchaseCosts: Readonly<Record<string, AccountReference>>; saleCosts: Readonly<Record<string, AccountReference>>; gains: Readonly<Record<string, AccountReference>>; losses: Readonly<Record<string, AccountReference>> }

modules.housing.PropertyOutputsPropertyOutputs describes a model value used by the Housing editor functions.

Model value shape: { readonly breakdown:CalculationReference; readonly marketValue:CalculationProjectionReference; readonly carryingValue:CalculationProjectionReference; readonly regulatoryValue:CalculationProjectionReference; readonly valueBeforeSale:CalculationProjectionReference; readonly realizedBookGain:CalculationProjectionReference; readonly active:CalculationProjectionReference; readonly operatingCost:CalculationProjectionReference; readonly purchaseCosts:CalculationProjectionReference; readonly saleCosts:CalculationProjectionReference; readonly opening:CashflowReference; readonly purchasePayment:CashflowReference; readonly revaluation:CashflowReference; readonly operatingPayment:CashflowReference; readonly saleProceeds:CashflowReference; }

modules.housing.PropertyPlanPropertyPlan describes a model value used by the Housing editor functions.

Model value shape: { component: ComponentReference<PropertyOutputs>; outputs: PropertyOutputs; accounts: PropertyAccounts; reportGroups: Readonly<Record<string, ReportGroupOptions>>; operatingCosts: Readonly<Record<string, CalculationProjectionReference>> }

modules.housing.PropertyPlanOptionsPropertyPlanOptions describes a model value used by the Housing editor functions.

Model value shape: { owner: EntityReference | RepeatOutputProjection<EntityReference> | LookupReference<EntityReference>; cashAccount: AccountReference | LookupReference<AccountReference>; openingValue?: AmountSource; monthlyCost?: AmountSource; operatingCosts?: Readonly<Record<string, { readonly amount: AmountSource; readonly code?: string; }>>; annualGrowth?: NumberSource; amortizationValue?: AmountSource; purchase?: PropertyPurchase; sale?: PropertyTransaction; ownership?: PropertyShares; paymentShares?: PropertyShares; accounts?: Partial<PropertyAccounts>; label?: string | InputProjectionReference<string> }

modules.housing.PropertyPurchasePropertyPurchase describes a model value used by the Housing editor functions.

Model value shape: { capitalizeCosts?: boolean; atPeriod: NumberSource; price: AmountSource; costs?: AmountSource; enabled?: boolean | NumberSource }

modules.housing.PropertySharespropertyPlan ownership/paymentShares allocation: owners is a keyed entity map or repeated entity output; weights is a keyed numeric-source map, repeated column or numeric calculation output map. Stable IDs join owners and weights; omitted owners have zero. Legal weights sum to one; payment weights are nonnegative with positive total. Invalid/unknown weights reject. Register source repeats. See propertyPlan for defaults and its complete callable example.

Model value shape: { owners: Readonly<Record<string, EntityReference>> | RepeatOutputProjection<EntityReference>; weights: RepeatColumnReference<number> | RepeatOutputProjection<CalculationReference<number>> | Readonly<Record<string, NumberSource>> }

modules.housing.PropertyTransactionPropertyTransaction describes a model value used by the Housing editor functions.

Model value shape: { atPeriod: NumberSource; price: AmountSource; costs?: AmountSource; enabled?: boolean | NumberSource }

Swedish Family Benefits module

Select this module in model settings to use its names in the portal model editor (modules["swedish-family-benefits"]).

Model editor namePurpose and model value shape
modules["swedish-family-benefits"].calculateChildBenefit2026calculateChildBenefit2026 calculates calculate child benefit2026 in the Swedish Family Benefits model editor. Use it when a model needs this operation.

(count?: number): number

const { calculateChildBenefit2026 } = modules["swedish-family-benefits"];

modules["swedish-family-benefits"].calculateMultiChildSupplement2026calculateMultiChildSupplement2026 calculates calculate multi child supplement2026 in the Swedish Family Benefits model editor. Use it when a model needs this operation.

(count: number): number

const { calculateMultiChildSupplement2026 } = modules["swedish-family-benefits"];

modules["swedish-family-benefits"].calculateStudyBenefit2026calculateStudyBenefit2026 calculates calculate study benefit2026 in the Swedish Family Benefits model editor. Use it when a model needs this operation.

(count: number, month: number): number

const { calculateStudyBenefit2026 } = modules["swedish-family-benefits"];

modules["swedish-family-benefits"].calculateSwedishFamilyBenefits2026calculateSwedishFamilyBenefits2026 calculates calculate swedish family benefits2026 in the Swedish Family Benefits model editor. Use it when a model needs this operation.

(options: { readonly children: readonly SwedishBenefitChild[]; readonly recipientIds: readonly string[]; readonly period: number; readonly month: number; }): SwedishFamilyBenefitsResult

const { calculateSwedishFamilyBenefits2026 } = modules["swedish-family-benefits"];

modules["swedish-family-benefits"].SWEDISH_FAMILY_BENEFITS_RULE_YEARSWEDISH_FAMILY_BENEFITS_RULE_YEAR is a model value for swedish family benefits rule year in the Swedish Family Benefits editor.

2026

const { SWEDISH_FAMILY_BENEFITS_RULE_YEAR } = modules["swedish-family-benefits"];

modules["swedish-family-benefits"].swedishFamilyBenefit2026Source formulas return krona numbers; calculations must declare the formula's dependsOn metadata.

Readonly<{ child(options?: { readonly count?: NumberSource; }): Formula; study(options?: { readonly count?: NumberSource; }): Formula; supplement(options: { readonly count: NumberSource; }): Formula; }>

const { swedishFamilyBenefit2026 } = modules["swedish-family-benefits"];

modules["swedish-family-benefits"].swedishFamilyBenefit2026.childswedishFamilyBenefit2026.child provides child in the Swedish Family Benefits model editor. Use it when a model needs this operation.

(options?: { readonly count?: NumberSource; }): Formula

const { child } = modules["swedish-family-benefits"].swedishFamilyBenefit2026;

modules["swedish-family-benefits"].swedishFamilyBenefit2026.studyswedishFamilyBenefit2026.study provides study in the Swedish Family Benefits model editor. Use it when a model needs this operation.

(options?: { readonly count?: NumberSource; }): Formula

const { study } = modules["swedish-family-benefits"].swedishFamilyBenefit2026;

modules["swedish-family-benefits"].swedishFamilyBenefit2026.supplementswedishFamilyBenefit2026.supplement provides supplement in the Swedish Family Benefits model editor. Use it when a model needs this operation.

(options: { readonly count: NumberSource; }): Formula

const { supplement } = modules["swedish-family-benefits"].swedishFamilyBenefit2026;

modules["swedish-family-benefits"].swedishFamilyBenefitsswedishFamilyBenefits({owner,children,recipients,profile?,fields?}) returns {component,outputs}; register component. Household call: `modules["swedish-family-benefits"].swedishFamilyBenefits({owner, recipients, children, profile: 'household'})`. Monthly SEK only. owner is an entity; recipients a keyed entity map/repeated person output, each entity once. children accepts fixed records or typed object-array/projection. Monthly Money outputs: child, study, supplement, total. breakdown includes ruleYear, period/month, recipients/groups, household/external/entitlement. Recipients receive bank income.tax_free postings; external portions create none. Omitting profile preserves explicit shares: id, benefitKind (child/study/none), eligibleForSupplement, familyGroupId, recipientShares:[{id,share}]; externalShare defaults 0. Shares sum to one. Optional inclusive fromPeriod/throughPeriod default to continuing; benefitSchedule sets timing. fields maps canonical to source names (defaults canonical). profile:'household' requires id,parent,benefitKind,householdShare. parent is a recipient ID or 'shared'; householdShare is required full/half. Full pays the whole entitlement here; half pays 50% outside. The household portion goes to parent or equally to shared recipients. Exactly one or two recipients, even without children; 'shared' is reserved. One implicit supplement group: child/study eligible, none inactive; no age inference. Household fields maps only those four fields; explicit shares support separate groups/eligibility/schedules. Both profiles: 2026 rules, July/August study pause, October supplement catch-up, cent rounding. Empty children yield zero. Invalid/duplicate IDs, unknown parents/recipients (even for none), kinds/shares, profile/fields, calendar/currency reject, including changed sources. Existing explicit-share APIs, pure calculations and outputs retain their contracts.

(options: SwedishFamilyBenefitsOptions): SwedishFamilyBenefitsPlan
(options: SwedishFamilyBenefitsMappedOptions): SwedishFamilyBenefitsPlan
(options: SwedishHouseholdFamilyBenefitsOptions): SwedishFamilyBenefitsPlan
(options: SwedishHouseholdFamilyBenefitsMappedOptions): SwedishFamilyBenefitsPlan

// Select Housing, Account plans and Swedish family benefits.
const members = deccf.input.objectArray([
  {id: deccf.input.id("anna"), share: deccf.input.fraction(0.5)},
  {id: deccf.input.id("erik"), share: deccf.input.fraction(0.5)},
]);
const owner = deccf.entity.party();
const cash = deccf.account({owner, type: "asset", initial: 10000});
const person = deccf.entity.party({owner});
const people = deccf.repeat(members, deccf.component({entities: {person}, outputs: {person}}));
const weight = deccf.calculation({
  name: "Ownership weight", calculate: deccf.expr.multiply(members.item.data.share, 1),
});
const allocations = deccf.repeat(members, deccf.component({calculations: {weight}, outputs: {weight}}));
const expense = modules.accountplan.reallocateExpense({
  from: owner, to: people.outputs.person, code: "expense.housing.mortgage_interest",
  amount: 100, weights: allocations.outputs.weight,
});
const benefits = modules["swedish-family-benefits"].swedishFamilyBenefits({
  owner, recipients: people.outputs.person, profile: "household",
  children: [{id: "kim", parent: "shared", benefitKind: "child", householdShare: "half"}],
});
const home = modules.housing.propertyPlan({
  owner, cashAccount: cash, openingValue: 1000000, monthlyCost: 100,
  ownership: {owners: people.outputs.person, weights: allocations.outputs.weight},
  paymentShares: {owners: people.outputs.person, weights: allocations.outputs.weight},
});
return deccf.defineModel({
  currency: deccf.currencies.SEK,
  timeline: deccf.periods.monthly({from: "2026-01", count: 1}),
  preconditions: {members}, entities: {owner}, accounts: {cash},
  components: {people, allocations, expense, benefits: benefits.component, home: home.component},
});
 

modules["swedish-family-benefits"].symProvides built-in numeric domains for common positive and percentage inputs.

Readonly<{ benefitKinds(language?: "en" | "sv"): readonly EnumOption<SwedishBenefitKind>[]; }>

const { sym } = modules["swedish-family-benefits"];

modules["swedish-family-benefits"].sym.benefitKindssym.benefitKinds provides benefit kinds in the Swedish Family Benefits model editor. Use it when a model needs this operation.

(language?: "en" | "sv"): readonly EnumOption<SwedishBenefitKind>[]

const benefitKind = input.enum('study', {
  options: modules['swedish-family-benefits'].sym.benefitKinds('en'),
});

modules["swedish-family-benefits"].FixedNumberSourceFixedNumberSource describes a model value used by the Swedish Family Benefits editor functions.

Model value shape: number | InputReference<number> | InputProjectionReference<number> | ExpressionReference

modules["swedish-family-benefits"].StringSourceStringSource describes a model value used by the Swedish Family Benefits editor functions.

Model value shape: T | InputReference<T> | InputProjectionReference<T>

modules["swedish-family-benefits"].SwedishBenefitAmountsSwedishBenefitAmounts describes a model value used by the Swedish Family Benefits editor functions.

Model value shape: { child: TAmount; study: TAmount; supplement: TAmount; total: TAmount }

modules["swedish-family-benefits"].SwedishBenefitChildSwedishBenefitChild describes a model value used by the Swedish Family Benefits editor functions.

Model value shape: { id: string; benefitKind: SwedishBenefitKind; eligibleForSupplement: boolean | 0 | 1; familyGroupId: string; recipientShares: readonly SwedishBenefitRecipientShare[]; externalShare?: number; fromPeriod?: number; throughPeriod?: number; benefitSchedule?: readonly SwedishBenefitScheduleEntry[] }

modules["swedish-family-benefits"].SwedishBenefitChildrenSourceSwedishBenefitChildrenSource describes a model value used by the Swedish Family Benefits editor functions.

Model value shape: readonly SwedishBenefitChildSource[] | InputReference<readonly InputValue[]> | InputProjectionReference<readonly InputValue[]>

modules["swedish-family-benefits"].SwedishBenefitChildSourceSwedishBenefitChildSource describes a model value used by the Swedish Family Benefits editor functions.

Model value shape: { id: StringSource<string>; benefitKind: StringSource<SwedishBenefitKind>; eligibleForSupplement: boolean | 0 | InputReference<number> | 1 | InputReference<boolean> | InputProjectionReference<number> | InputProjectionReference<boolean>; familyGroupId: StringSource<string>; recipientShares: InputProjectionReference<readonly InputValue[]> | InputReference<readonly InputValue[]> | readonly { readonly id: StringSource; readonly share: FixedNumberSource; }[]; externalShare?: FixedNumberSource; fromPeriod?: FixedNumberSource; throughPeriod?: FixedNumberSource; benefitSchedule?: InputProjectionReference<readonly InputValue[]> | InputReference<readonly InputValue[]> | readonly { readonly fromPeriod: FixedNumberSource; readonly throughPeriod: FixedNumberSource; readonly benefitKind: StringSource<SwedishBenefitKind>; readonly eligibleForSupplement: boolean | 0 | 1 | InputReference<boolean> | InputProjectionReference<boolean> | InputReference<number> | InputProjectionReference<number>; }[] }

modules["swedish-family-benefits"].SwedishBenefitFieldsSwedishBenefitFields describes a model value used by the Swedish Family Benefits editor functions.

Model value shape: Partial<Readonly<Record<keyof SwedishBenefitChild, string>>>

modules["swedish-family-benefits"].SwedishBenefitKindSwedishBenefitKind describes a model value used by the Swedish Family Benefits editor functions.

Model value shape: "child" | "study" | "none"

modules["swedish-family-benefits"].SwedishBenefitRecipientShareSwedishBenefitRecipientShare describes a model value used by the Swedish Family Benefits editor functions.

Model value shape: { id: string; share: number }

modules["swedish-family-benefits"].SwedishBenefitScheduleEntrySwedishBenefitScheduleEntry describes a model value used by the Swedish Family Benefits editor functions.

Model value shape: { fromPeriod: number; throughPeriod: number; benefitKind: SwedishBenefitKind; eligibleForSupplement: boolean | 0 | 1 }

modules["swedish-family-benefits"].SwedishFamilyBenefitsMappedOptionsSwedishFamilyBenefitsMappedOptions describes a model value used by the Swedish Family Benefits editor functions.

Model value shape: { children: InputProjectionReference<readonly InputValue[]> | readonly Readonly<Record<string, unknown>>[] | InputReference<readonly InputValue[]>; fields: Partial<Readonly<Record<keyof SwedishBenefitChild, string>>>; owner: EntityReference; profile?: never; recipients: Readonly<Record<string, EntityReference>> | RepeatOutputProjection<EntityReference> }

modules["swedish-family-benefits"].SwedishFamilyBenefitsOptionsSwedishFamilyBenefitsOptions describes a model value used by the Swedish Family Benefits editor functions.

Model value shape: { profile?: never; owner: EntityReference; children: SwedishBenefitChildrenSource; recipients: Readonly<Record<string, EntityReference>> | RepeatOutputProjection<EntityReference>; fields?: Partial<Readonly<Record<keyof SwedishBenefitChild, string>>> }

modules["swedish-family-benefits"].SwedishFamilyBenefitsOutputsSwedishFamilyBenefitsOutputs describes a model value used by the Swedish Family Benefits editor functions.

Model value shape: Readonly<{ breakdown: CalculationReference; child: CalculationProjectionReference; study: CalculationProjectionReference; supplement: CalculationProjectionReference; total: CalculationProjectionReference; }>

modules["swedish-family-benefits"].SwedishFamilyBenefitsPlanSwedishFamilyBenefitsPlan describes a model value used by the Swedish Family Benefits editor functions.

Model value shape: { component: ComponentReference<Readonly<{ breakdown: CalculationReference; child: CalculationProjectionReference; study: CalculationProjectionReference; supplement: CalculationProjectionReference; total: CalculationProjectionReference; }>>; outputs: Readonly<{ breakdown: CalculationReference; child: CalculationProjectionReference; study: CalculationProjectionReference; supplement: CalculationProjectionReference; total: CalculationProjectionReference; }> }

modules["swedish-family-benefits"].SwedishFamilyBenefitsResultPure results use krona numbers; published calculation records use Money amounts.

Model value shape: { ruleYear: 2026; period: number; month: number; recipients: Readonly<Record<string, SwedishBenefitAmounts<TAmount>>>; groups: Readonly<Record<string, SwedishBenefitAmounts<TAmount>>>; household: SwedishBenefitAmounts<TAmount>; external: SwedishBenefitAmounts<TAmount>; entitlement: SwedishBenefitAmounts<TAmount> }

modules["swedish-family-benefits"].SwedishHouseholdBenefitChildSourceHousehold child: required string sources id, parent (recipient ID or shared), benefitKind (child/study/none), householdShare (full/half). See swedishFamilyBenefits for rules, validation and example.

Model value shape: { id: StringSource<string>; parent: StringSource<string>; benefitKind: StringSource<SwedishBenefitKind>; householdShare: StringSource<"full" | "half"> }

modules["swedish-family-benefits"].SwedishHouseholdBenefitFieldsOptional canonical-to-source name map: id, parent, benefitKind, householdShare only; omitted mappings use canonical names. See swedishFamilyBenefits.

Model value shape: Partial<Readonly<Record<keyof SwedishHouseholdBenefitChildSource, string>>>

modules["swedish-family-benefits"].SwedishHouseholdFamilyBenefitsMappedOptionsHousehold profile options with explicit fields mapping. See swedishFamilyBenefits for supported names, defaults, validation, outputs and example.

Model value shape: { children: InputProjectionReference<readonly InputValue[]> | readonly Readonly<Record<string, unknown>>[] | InputReference<readonly InputValue[]>; fields: Partial<Readonly<Record<keyof SwedishHouseholdBenefitChildSource, string>>>; owner: EntityReference; profile: "household"; recipients: Readonly<Record<string, EntityReference>> | RepeatOutputProjection<EntityReference> }

modules["swedish-family-benefits"].SwedishHouseholdFamilyBenefitsOptionsswedishFamilyBenefits options with required profile:'household', owner, children, recipients; optional fields. See the function's complete contract and callable example.

Model value shape: { profile: "household"; children: InputProjectionReference<readonly InputValue[]> | InputReference<readonly InputValue[]> | readonly SwedishHouseholdBenefitChildSource[]; fields?: Partial<Readonly<Record<keyof SwedishHouseholdBenefitChildSource, string>>>; owner: EntityReference; recipients: Readonly<Record<string, EntityReference>> | RepeatOutputProjection<EntityReference> }

Swedish Credit module

Select this module in model settings to use its names in the portal model editor (modules["swedish-credit"]).

Model editor namePurpose and model value shape
modules["swedish-credit"].calculateSwedishInterestAllocation2025calculateSwedishInterestAllocation2025 calculates calculate swedish interest allocation2025 in the Swedish Credit model editor. Use it when a model needs this operation.

(options: { readonly annualInterest: number; readonly profiles: Readonly<Record<string, SwedishResolvedTaxProfile2025>>; readonly enabled?: boolean; readonly weights?: Readonly<Record<string, number>>; }): SwedishInterestAllocation2025Result

const { calculateSwedishInterestAllocation2025 } = modules["swedish-credit"];

modules["swedish-credit"].calculateSwedishInterestPortfolio2025calculateSwedishInterestPortfolio2025 calculates calculate swedish interest portfolio2025 in the Swedish Credit model editor. Use it when a model needs this operation.

(options: { readonly pools: Readonly<Record<string, SwedishInterestPool2025>>; readonly profiles: Readonly<Record<string, SwedishProjectedTaxProfile2025>>; readonly enabled?: boolean; }): SwedishInterestPortfolio2025Result

const { calculateSwedishInterestPortfolio2025 } = modules["swedish-credit"];

modules["swedish-credit"].swedishDebtRatioswedishDebtRatio provides swedish debt ratio in the Swedish Credit model editor. Use it when a model needs this operation.

(options: SwedishDebtRatioOptions): CalculationReference

const { swedishDebtRatio } = modules["swedish-credit"];

modules["swedish-credit"].swedishInterestAllocation2025swedishInterestAllocation2025 provides swedish interest allocation2025 in the Swedish Credit model editor. Use it when a model needs this operation.

(options: SwedishInterestAllocation2025Options): CalculationReference

const allocation = swedishInterestAllocation2025({
  owner: family,
  annualInterest: annualSecuredInterest,
  recipients: people.outputs.applicants,
  profiles: {
    dateOfBirth: people.applicants.column("dateOfBirth"),
    taxBases: {
      [SWEDISH_INCOME_TAX_2025_BASE.EMPLOYMENT]: {
        amount: people.applicants.column("salary"), period: "monthly"
      }
    },
    rules: { municipalRate: people.applicants.column("municipalRate") }
  }
});

const recognition = reallocateExpense({
  from: family, to: people.outputs.applicants,
  code: "expense.housing.mortgage_interest",
  amount: monthlySecuredInterest, weights: allocation.project("weights")
});

modules["swedish-credit"].swedishInterestPortfolio2025swedishInterestPortfolio2025 provides swedish interest portfolio2025 in the Swedish Credit model editor. Use it when a model needs this operation.

(options: SwedishInterestPortfolio2025Options): CalculationReference

const { swedishInterestPortfolio2025 } = modules["swedish-credit"];

modules["swedish-credit"].CreditMapSourceCreditMapSource describes a model value used by the Swedish Credit editor functions.

Model value shape: Readonly<Record<string,T>> | InputReference<Readonly<Record<string,InputValue>>> | InputProjectionReference<Readonly<Record<string,InputValue>>> | RepeatColumnReference | RepeatOutputProjection<CalculationReference | CalculationProjectionReference> | CalculationReference | CalculationProjectionReference | ExpressionReference

modules["swedish-credit"].SwedishDebtRatioOptionsSwedishDebtRatioOptions describes a model value used by the Swedish Credit editor functions.

Model value shape: { owner?: EntityReference | RepeatOutputProjection<EntityReference>; debt: AmountSource; annualIncome: AmountSource }

modules["swedish-credit"].SwedishInterestAllocation2025OptionsSwedishInterestAllocation2025Options describes a model value used by the Swedish Credit editor functions.

Model value shape: { owner?: EntityReference | RepeatOutputProjection<EntityReference>; annualInterest: AmountSource; recipients: Readonly<Record<string, EntityReference>> | RepeatOutputProjection<EntityReference>; profiles: SwedishInterestProfiles2025; enabled?: SwedishTaxBooleanSource; weights?: CreditMapSource<NumberSource> }

modules["swedish-credit"].SwedishInterestAllocation2025ResultSwedishInterestAllocation2025Result describes a model value used by the Swedish Credit editor functions.

Model value shape: { ruleYear: 2025; annualInterest: number; allocations: Readonly<Record<string, number>>; weights: Readonly<Record<string, number>>; baselineLiabilities: Readonly<Record<string, number>>; allocatedLiabilities: Readonly<Record<string, number>>; savings: number; status: "manual" | "exact-whole-kr" | "bounded-estimate"; savingsGapBound: number; engineEvaluations: number }

modules["swedish-credit"].SwedishInterestPool2025SwedishInterestPool2025 describes a model value used by the Swedish Credit editor functions.

Model value shape: { name?: string; annualInterest: number; eligible: Readonly<Record<string, boolean | 0 | 1>>; weights: Readonly<Record<string, number>> }

modules["swedish-credit"].SwedishInterestPool2025SourcesSwedishInterestPool2025Sources describes a model value used by the Swedish Credit editor functions.

Model value shape: { name?: string | CalculationReference<unknown> | InputReference<string> | InputProjectionReference<string> | CalculationProjectionReference; annualInterest: AmountSource; eligible: CreditMapSource<boolean | 0 | 1>; weights: CreditMapSource<NumberSource> }

modules["swedish-credit"].SwedishInterestPortfolio2025OptionsSwedishInterestPortfolio2025Options describes a model value used by the Swedish Credit editor functions.

Model value shape: { owner?: EntityReference | RepeatOutputProjection<EntityReference>; pools: CreditMapSource<CalculationReference<unknown> | CalculationProjectionReference | SwedishInterestPool2025Sources>; recipients: Readonly<Record<string, EntityReference>> | RepeatOutputProjection<EntityReference>; profiles: CreditMapSource<CalculationReference<unknown> | CalculationProjectionReference | SwedishProjectedTaxProfile2025>; enabled?: SwedishTaxBooleanSource }

modules["swedish-credit"].SwedishInterestPortfolio2025ResultSwedishInterestPortfolio2025Result describes a model value used by the Swedish Credit editor functions.

Model value shape: { ruleYear: 2025; perPool: Readonly<Record<string, { readonly name: string; readonly annualInterest: number; readonly allocations: Readonly<Record<string, number>>; readonly weights: Readonly<Record<string, number>>; readonly taxSavings: number; }>>; perRecipient: Readonly<Record<string, number>>; weights: Readonly<Record<string, number>>; totalInterest: number; baselineLiabilities: Readonly<Record<string, number>>; allocatedLiabilities: Readonly<Record<string, number>>; baselineLiability: number; allocatedLiability: number; taxSavings: number; status: "manual" | "bounded-estimate"; savingsGapBound: number; engineEvaluations: number }

modules["swedish-credit"].SwedishInterestProfiles2025SwedishInterestProfiles2025 describes a model value used by the Swedish Credit editor functions.

Model value shape: { dateOfBirth: CreditMapSource<string | InputReference<string> | InputProjectionReference<string>>; taxBases?: Readonly<Record<string, CreditMapSource<AmountSource> | { readonly amount: CreditMapSource<AmountSource>; readonly period?: "monthly" | "annual"; }>>; rules?: { readonly residentMonths?: CreditMapSource<NonNullable<NumberSource>>; readonly municipalRate?: CreditMapSource<NonNullable<NumberSource>>; readonly stateThreshold?: CreditMapSource<NonNullable<NumberSource>>; readonly burialFeeRate?: CreditMapSource<NonNullable<NumberSource>>; readonly communityMember?: CreditMapSource<NonNullable<SwedishTaxBooleanSource>>; readonly communityFeeRate?: CreditMapSource<NonNullable<NumberSource>>; }; propertyAssessments?: CreditMapSource<CalculationReference<unknown> | CalculationProjectionReference | readonly SwedishPropertyAssessment[]> }

modules["swedish-credit"].SwedishProjectedTaxProfile2025SwedishProjectedTaxProfile2025 describes a model value used by the Swedish Credit editor functions.

Model value shape: { ruleYear: 2025; taxYear?: number; dateOfBirth: string; taxBases?: Readonly<Record<string, number>>; rules?: Readonly<{ residentMonths?: number; municipalRate?: number; stateThreshold?: number; burialFeeRate?: number; communityMember?: boolean; communityFeeRate?: number; }>; propertyAssessments: Readonly<Record<string, { readonly assessmentValue: number; readonly buildingYear: number; readonly valueYear?: number; readonly ownershipShare?: number; }>> }

modules["swedish-credit"].SwedishResolvedTaxProfile2025SwedishResolvedTaxProfile2025 describes a model value used by the Swedish Credit editor functions.

Model value shape: { dateOfBirth: string; taxBases?: Readonly<Record<string, number>>; rules?: Readonly<{ residentMonths?: number; municipalRate?: number; stateThreshold?: number; burialFeeRate?: number; communityMember?: boolean; communityFeeRate?: number; }>; propertyAssessments?: readonly { readonly assessmentValue: number; readonly buildingYear: number; readonly valueYear?: number; readonly ownershipShare?: number; }[] }

Swedish Property Sale Tax module

Select this module in model settings to use its names in the portal model editor (modules["swedish-property-sale-tax"]).

Model editor namePurpose and model value shape
modules["swedish-property-sale-tax"].calculateSwedishPropertySalecalculateSwedishPropertySale calculates calculate swedish property sale in the Swedish Property Sale Tax model editor. Use it when a model needs this operation.

(input: SwedishPropertySaleCalculationInput): SwedishPropertySaleCalculationResult

const { calculateSwedishPropertySale } = modules["swedish-property-sale-tax"];

modules["swedish-property-sale-tax"].swedishPropertySaleswedishPropertySale provides swedish property sale in the Swedish Property Sale Tax model editor. Use it when a model needs this operation.

(options: SwedishPropertySaleOptions): SwedishPropertySale

const { swedishPropertySale } = modules['swedish-property-sale-tax'];

const { personalTax } = modules['swedish-income-tax'];

const sale = swedishPropertySale({
  person: anna,
  cashAccount: bank,
  mortgageAccount: mortgage,
  propertyType: 'villa',
  sale: {
    contractPeriod: 9,
    settlementPeriod: 10,
    price: salePrice,
    expenses: saleExpenses,
    mortgagePayoff: mortgagePayoff,
  },
  purchase: { price: purchasePrice, costs: purchaseCosts },
  improvements,
  previousDeferral,
  deferralEligibilityConfirmed: eligibleForDeferral,
  replacementHome: {
    propertyType: 'bostadsratt',
    purchasePrice: replacementPrice,
    repairFundAtPurchase: replacementRepairFund,
  },
});

const taxes = personalTax({
  person: anna,
  cashAccount: bank,
  taxBases: sale.taxBases,
  publishAssessment: true,
});

modules["swedish-property-sale-tax"].SwedishPropertyImprovementSwedishPropertyImprovement describes a model value used by the Swedish Property Sale Tax editor functions.

Model value shape: Readonly<{ year: number; cost: number; rotReduction?: number; insuranceReimbursement?: number; } & ( | { type: 'improvement'; deductibleShare?: never } | { type: 'repair'; deductibleShare: number } )>

modules["swedish-property-sale-tax"].SwedishPropertyImprovementSourceSwedishPropertyImprovementSource describes a model value used by the Swedish Property Sale Tax editor functions.

Model value shape: Readonly<{ year: NumberSource; cost: AmountSource; rotReduction?: AmountSource; insuranceReimbursement?: AmountSource; } & ( | { type: 'improvement'; deductibleShare?: never } | { type: 'repair'; deductibleShare: NumberSource } )>

modules["swedish-property-sale-tax"].SwedishPropertySaleSwedishPropertySale describes a model value used by the Swedish Property Sale Tax editor functions.

Model value shape: { component: ComponentReference<SwedishPropertySaleOutputs>; outputs: SwedishPropertySaleOutputs; taxBases: Readonly<{ 'capital.income': CalculationReference; }> }

modules["swedish-property-sale-tax"].SwedishPropertySaleBooleanSourceSwedishPropertySaleBooleanSource describes a model value used by the Swedish Property Sale Tax editor functions.

Model value shape: boolean | InputReference<boolean> | InputProjectionReference<boolean> | CalculationReference | CalculationProjectionReference | ExpressionReference

modules["swedish-property-sale-tax"].SwedishPropertySaleBreakdownSwedishPropertySaleBreakdown describes a model value used by the Swedish Property Sale Tax editor functions.

Model value shape: { contractYear: number; capitalGainBeforeDeferral: Money; gainIncludingPreviousDeferral: Money; improvementDeduction: Money; newDeferral: Money; taxableGain: Money; taxableCapitalIncome: Money; estimatedTax: Money; netSalePriceForDeferral: Money; replacementPurchasePriceForDeferral: Money; cashProceeds: Money }

modules["swedish-property-sale-tax"].SwedishPropertySaleCalculationBaseSwedishPropertySaleCalculationBase describes a model value used by the Swedish Property Sale Tax editor functions.

Model value shape: { saleYear: number; salePrice: number; saleExpenses?: number; purchasePrice: number; purchaseCosts?: number; improvements?: readonly SwedishPropertyImprovement[]; mortgagePayoff?: number; previousDeferral?: number; ownershipShare?: number; deferralEligibilityConfirmed?: boolean; requestedDeferral?: number; replacementHome?: SwedishReplacementHome }

modules["swedish-property-sale-tax"].SwedishPropertySaleCalculationInputSwedishPropertySaleCalculationInput describes a model value used by the Swedish Property Sale Tax editor functions.

Model value shape: Readonly<SwedishPropertySaleCalculationBase & ( | { propertyType: 'villa'; capitalContributions?: never; repairFundAtSale?: never; repairFundAtPurchase?: never } | { propertyType: 'bostadsratt'; capitalContributions?: number; repairFundAtSale?: number; repairFundAtPurchase?: number } )>

modules["swedish-property-sale-tax"].SwedishPropertySaleCalculationResultSwedishPropertySaleCalculationResult describes a model value used by the Swedish Property Sale Tax editor functions.

Model value shape: { capitalGainBeforeDeferral: number; gainIncludingPreviousDeferral: number; improvementDeduction: number; newDeferral: number; taxableGain: number; taxableCapitalIncome: number; estimatedTax: number; netSalePriceForDeferral: number; replacementPurchasePriceForDeferral: number; cashProceeds: number }

modules["swedish-property-sale-tax"].SwedishPropertySaleOptionBaseSwedishPropertySaleOptionBase describes a model value used by the Swedish Property Sale Tax editor functions.

Model value shape: { person: EntityReference; cashAccount: AccountReference; mortgageAccount?: AccountReference; sale: Readonly<{ contractPeriod: NumberSource; settlementPeriod?: NumberSource; readonly price: AmountSource; readonly expenses?: AmountSource; readonly mortgagePayoff?: AmountSource; }>; purchase: Readonly<{ price: AmountSource; costs?: AmountSource; }>; improvements?: readonly SwedishPropertyImprovementSource[]; previousDeferral?: AmountSource; ownershipShare?: NumberSource; deferralEligibilityConfirmed?: SwedishPropertySaleBooleanSource; requestedDeferral?: AmountSource; replacementHome?: SwedishReplacementHomeSource; bookSettlement?: boolean }

modules["swedish-property-sale-tax"].SwedishPropertySaleOptionsSwedishPropertySaleOptions describes a model value used by the Swedish Property Sale Tax editor functions.

Model value shape: Readonly<SwedishPropertySaleOptionBase & ( | { propertyType: 'villa'; capitalContributions?: never; repairFundAtSale?: never; repairFundAtPurchase?: never } | { propertyType: 'bostadsratt'; capitalContributions?: AmountSource; repairFundAtSale?: AmountSource; repairFundAtPurchase?: AmountSource } )>

modules["swedish-property-sale-tax"].SwedishPropertySaleOutputsSwedishPropertySaleOutputs describes a model value used by the Swedish Property Sale Tax editor functions.

Model value shape: { settlement: CashflowReference; breakdown: CalculationReference<unknown>; taxableCapitalIncome: CalculationReference<unknown> }

modules["swedish-property-sale-tax"].SwedishPropertyTypeSwedishPropertyType describes a model value used by the Swedish Property Sale Tax editor functions.

Model value shape: 'villa' | 'bostadsratt'

modules["swedish-property-sale-tax"].SwedishReplacementHomeSwedishReplacementHome describes a model value used by the Swedish Property Sale Tax editor functions.

Model value shape: Readonly<{ purchasePrice: number; } & ( | { propertyType: 'villa'; purchaseCosts?: number; qualifyingImprovements?: number; repairFundAtPurchase?: never } | { propertyType: 'bostadsratt'; repairFundAtPurchase?: number; purchaseCosts?: never; qualifyingImprovements?: never } )>

modules["swedish-property-sale-tax"].SwedishReplacementHomeSourceSwedishReplacementHomeSource describes a model value used by the Swedish Property Sale Tax editor functions.

Model value shape: Readonly<{ purchasePrice: AmountSource; } & ( | { propertyType: 'villa'; purchaseCosts?: AmountSource; qualifyingImprovements?: AmountSource; repairFundAtPurchase?: never } | { propertyType: 'bostadsratt'; repairFundAtPurchase?: AmountSource; purchaseCosts?: never; qualifyingImprovements?: never } )>

Swedish Investment Accounts module

Select this module in model settings to use its names in the portal model editor (modules["swedish-investment-accounts"]).

Model editor namePurpose and model value shape
modules["swedish-investment-accounts"].swedishInvestmentAccountsDeclare Swedish ISK and VP ledgers and publish period facts without applying tax rules.

(options: SwedishInvestmentAccountsOptions): SwedishInvestmentAccounts

const { account, currencies, defineModel, entity, input, periods } = deccf;

const { swedishInvestmentAccounts } = modules["swedish-investment-accounts"];

const SEK = currencies.SEK;

const owner = entity.party();

const bankOpening = input.money(80_000, SEK, { ui: { label: "Opening bank balance" } });

const bank = account({
  owner,
  type: "asset",
  category: deccf.category("assets.cash.bank"),
  initial: bankOpening,
});

const timeline = periods.monthly({ from: "2026-01", count: 12 });

const deposit = input.money(2_000, SEK);

const purchase = input.money(1_500, SEK);

const dividend = input.money(25, SEK);

const accounts = swedishInvestmentAccounts({
  owner,
  bankAccount: bank,
  timeline,
  accounts: [
    {
      id: "isk",
      type: "ISK",
      opening: { cash: 5_000, securities: 40_000 },
      events: [
        { id: "monthly-deposit", date: "2026-02", type: "deposit", amount: deposit },
        { id: "monthly-purchase", date: "2026-02", type: "purchase", amount: purchase },
        { id: "spring-dividend", date: "2026-04", type: "dividend", amount: dividend },
        { id: "spring-value", date: "2026-04", type: "valuation", value: 47_500 },
      ],
    },
    { id: "vp", type: "VP", opening: { cash: 1_000, securities: 12_000 } },
  ],
});

return defineModel({
  name: "Swedish ISK and VP account example",
  currency: SEK,
  timeline,
  preconditions: { bankOpening, deposit, purchase, dividend },
  entities: { owner },
  accounts: { bank },
  components: { investments: accounts.component },
  metrics: {
    isk_cash_sek: context => context.get(accounts.accounts.isk.cash),
    isk_securities_at_cost_sek: context => context.get(accounts.accounts.isk.securities),
    isk_dividends_sek: context => context.get(accounts.taxFacts.isk).dividends,
    vp_cash_sek: context => context.get(accounts.accounts.vp.cash),
  },
});

modules["swedish-investment-accounts"].InvestmentAmountSourceInvestmentAmountSource describes a model value used by the Swedish Investment Accounts editor functions.

Model value shape: number | Money | InputReference<number | Money> | InputProjectionReference<number | Money> | CalculationReference | CalculationProjectionReference | ExpressionReference

modules["swedish-investment-accounts"].SwedishInvestmentAccountDeclarationSwedishInvestmentAccountDeclaration describes a model value used by the Swedish Investment Accounts editor functions.

Model value shape: { id: string; type: SwedishInvestmentAccountType; label?: string; opening?: Readonly<{ cash?: InvestmentAmountSource; securities?: InvestmentAmountSource; }>; events?: readonly SwedishInvestmentEvent[] }

modules["swedish-investment-accounts"].SwedishInvestmentAccountReferencesSwedishInvestmentAccountReferences describes a model value used by the Swedish Investment Accounts editor functions.

Model value shape: { cash: AccountReference; securities: AccountReference; openingEquity: AccountReference; dividendIncome: AccountReference; interestIncome: AccountReference; realizedGain: AccountReference; realizedLoss: AccountReference; fees: AccountReference }

modules["swedish-investment-accounts"].SwedishInvestmentAccountsSwedishInvestmentAccounts describes a model value used by the Swedish Investment Accounts editor functions.

Model value shape: { component: ComponentReference<Readonly<Record<string, deccf.ComponentOutputReference>>>; accounts: Readonly<Record<string, SwedishInvestmentAccountReferences>>; taxFacts: Readonly<Record<string, CalculationReference<unknown>>>; flows: Readonly<Record<string, Readonly<Record<string, CashflowReference>>>> }

modules["swedish-investment-accounts"].SwedishInvestmentAccountsOptionsSwedishInvestmentAccountsOptions describes a model value used by the Swedish Investment Accounts editor functions.

Model value shape: { owner: EntityReference; bankAccount: AccountReference; timeline: Timeline; accounts: readonly SwedishInvestmentAccountDeclaration[] }

modules["swedish-investment-accounts"].SwedishInvestmentAccountTypeSwedishInvestmentAccountType describes a model value used by the Swedish Investment Accounts editor functions.

Model value shape: "ISK" | "VP"

modules["swedish-investment-accounts"].SwedishInvestmentEventSwedishInvestmentEvent describes a model value used by the Swedish Investment Accounts editor functions.

Model value shape: Readonly<{ id: string; date: SwedishInvestmentMonth }> & ( | Readonly<{ type: "deposit" | "withdrawal" | "purchase" | "dividend" | "interest" | "fee"; amount: InvestmentAmountSource }> | Readonly<{ type: "sale"; proceeds: InvestmentAmountSource; costBasis: InvestmentAmountSource }> | Readonly<{ type: "valuation"; value: InvestmentAmountSource }> )

modules["swedish-investment-accounts"].SwedishInvestmentMonthSwedishInvestmentMonth describes a model value used by the Swedish Investment Accounts editor functions.

Model value shape: `${number}-${number}`

modules["swedish-investment-accounts"].SwedishInvestmentPeriodFactsSwedishInvestmentPeriodFacts describes a model value used by the Swedish Investment Accounts editor functions.

Model value shape: { accountId: string; period: string; accountType: SwedishInvestmentAccountType; currency: "SEK"; openingCash: number; closingCash: number; openingSecurities: number; closingSecurities: number; externalDeposits: number; externalWithdrawals: number; realizedGains: number; realizedLosses: number; dividends: number; interest: number; fees: number; observedAccountValueAvailable: boolean; … 1 more fields }

Danish Pension module

Select this module in model settings to use its names in the portal model editor (modules["danish-pension"]).

Model editor namePurpose and model value shape
modules["danish-pension"].assessDanishPensionPure assessment of the same partial 2026 scheme as danishPension. Numeric sources must already be resolved; amounts use the native period and currency. The explicit scheme and nonempty basisSource are mandatory. No owner, id, engine reference, callback, bank payment or personal pension-capital balance is created. Invalid/negative bases, foreign Money, missing data and unsupported schemes fail.

(options: DanishPensionAssessmentOptions): DanishPensionAssessment

const assessment = modules['danish-pension'].assessDanishPension({ruleYear: 2026, scheme: 'atp-a-monthly', basisSource: 'Confirmed monthly insured payroll', coveredHours: 160});

return deccf.defineModel({
  currency: deccf.currencies.DKK,
  timeline: deccf.periods.monthly({from: '2026-05', count: 1}),
  metrics: {assessedAmount: deccf.metric({value: assessment.employeeContribution, unit: 'money', annualAggregation: 'last'})},
});

modules["danish-pension"].DANISH_PENSION_2026Immutable DK 2026 partial pension rules, parameter provenance and assessment validity.

NationalPensionRules

const { DANISH_PENSION_2026 } = modules["danish-pension"];

modules["danish-pension"].danishPensionCalculates the 2026 monthly ATP A-rate contribution for an already covered monthly paid Danish employee. coveredHours is the nonnegative payroll-hour basis after the employer has established coverage, including the age-16 requirement; it accepts a number or declared numeric source, not money. basisSource must name that payroll/enrolment record. Hours include qualifying paid leave according to ATP's rules; the factory does not infer hours from salary. Below 39 hours the contribution is zero; from 39, 78 and 117 hours the employee pays DKK 33/66/99 and employer DKK 66/132/198. Rates have applied since 2024 and were confirmed for this 2026 slice. Weekly, fortnightly, casual-worker, public-sector alternative-rate and self-employed cases are unsupported. Required options are id, owner, ruleYear:2026, the explicit scheme, basisSource and all numeric bases. There are no implicit amount or scheme defaults; pass zero explicitly when true. The owner is an entity or a keyed entity lookup, such as lookup(people.outputs.person, people.item.data.id) for repeated rows. Register the returned component in model components. outputs.assessment publishes the full record, and named numeric outputs are calculation projections usable in metrics and other declarations. rules exposes immutable national parameters, source links, validity and review dates. The model must use DKK and the monthly calendar with periods starting on the first day. Only the 2026 assessment year is supported. All amounts use DKK; rate calculations retain raw values before payment rounding. Unknown options/schemes, missing source classifications, negative or nonfinite bases, wrong currencies and uncovered dates/calendars fail explicitly. Callbacks capturing row projections cannot rebind. For repeated rows, use direct input references, expressions or bindable calculation references instead. Ordinary callbacks may use declared inputs that do not capture symbolic rows. No tax, bank transaction, capital balance or current pension payout is created.

(options: DanishPensionOptions): DanishPensionComponent

const {currencies, defineModel, entity, input, metric, periods} = deccf;

const {danishPension} = modules["danish-pension"];

const owner = entity.party();

const basis = input.decimal(160, {ui: {label: "Covered payroll hours"}});

const pension = danishPension({
  id: "employee-pension", owner, ruleYear: 2026, scheme: "atp-a-monthly",
  basisSource: "Confirmed insured payroll record for 2026",
  coveredHours: basis,
});

return defineModel({
  currency: currencies.DKK,
  timeline: periods.monthly({from: "2026-01-01", count: 1}),
  entities: {owner},
  components: {pension: pension.component},
  metrics: {pensionResult: metric({label: "ATP contributions, DKK/month", calculate: ctx => ctx.get(pension.outputs.totalContribution)})},
});

modules["danish-pension"].DanishPensionAssessmentDanishPensionAssessment describes a model value used by the Danish Pension editor functions.

Model value shape: { country: "DK"; currency: "DKK"; ruleYear: 2026; scheme: "atp-a-monthly"; period: "monthly"; coverage: "partial"; resultKind: "insurance-contribution"; roundingScope: "before-payment-rounding"; ruleSource: string; basisSource: string; employeeContribution: number; employerContribution: number; totalContribution: number }

modules["danish-pension"].DanishPensionAssessmentOptionsResolved classified bases for the native pension assessment; all bases are required.

Model value shape: { readonly [K in keyof Omit<DanishPensionOptions, 'id' | 'owner'>]: Exclude<DanishPensionOptions[K], undefined> extends PensionNumberSource ? number : Exclude<DanishPensionOptions[K], undefined> extends PensionAmountSource ? number | Money : DanishPensionOptions[K]; }

modules["danish-pension"].DanishPensionComponentDanishPensionComponent describes a model value used by the Danish Pension editor functions.

Model value shape: { component: ComponentReference<Readonly<Record<string, deccf.ComponentOutputReference>>>; rules: NationalPensionRules; outputs: Readonly<{ assessment: CalculationReference; employeeContribution: CalculationProjectionReference; employerContribution: CalculationProjectionReference; totalContribution: CalculationProjectionReference; }> }

modules["danish-pension"].DanishPensionOptionsDanishPensionOptions describes a model value used by the Danish Pension editor functions.

Model value shape: { id: string; owner: EntityReference | LookupReference<EntityReference>; ruleYear: 2026; scheme: "atp-a-monthly"; basisSource: string; coveredHours: PensionNumberSource }

modules["danish-pension"].NationalPensionRulesNationalPensionRules describes a model value used by the Danish Pension editor functions.

Model value shape: { country: "DK"; currency: "DKK"; scheme: "atp-a-monthly"; ruleYear: 2026; validFrom: "2026-01-01"; validToExclusive: "2027-01-01"; reviewedOn: string; coverage: "partial"; period: "monthly"; roundingScope: "before-payment-rounding"; parameters: Readonly<Record<string, number | readonly number[]>>; sources: readonly Readonly<{ url: string; title: string; parameters: readonly string[]; reviewedOn: string; }>[] }

modules["danish-pension"].PensionAmountSourcePensionAmountSource describes a model value used by the Danish Pension editor functions.

Model value shape: number | Money | InputReference<number | Money> | InputProjectionReference<number | Money> | CalculationReference | CalculationProjectionReference | ExpressionReference | ((context: CalculationContext) => number | Money)

modules["danish-pension"].PensionNumberSourcePensionNumberSource describes a model value used by the Danish Pension editor functions.

Model value shape: number | InputReference<number> | InputProjectionReference<number> | CalculationReference | CalculationProjectionReference | ExpressionReference | ((context: CalculationContext) => number)

Finnish Pension module

Select this module in model settings to use its names in the portal model editor (modules["finnish-pension"]).

Model editor namePurpose and model value shape
modules["finnish-pension"].assessFinnishPensionPure assessment of the same partial 2026 scheme as finnishPension. Numeric sources must already be resolved; amounts use the native period and currency. The explicit scheme and nonempty basisSource are mandatory. No owner, id, engine reference, callback, bank payment or personal pension-capital balance is created. Invalid/negative bases, foreign Money, missing data and unsupported schemes fail.

(options: FinnishPensionAssessmentOptions): FinnishPensionAssessment

const assessment = modules['finnish-pension'].assessFinnishPension({ruleYear: 2026, scheme: 'tyel-accrual', basisSource: 'Confirmed insured annual TyEL earnings', pensionableEarnings: 60000});

return deccf.defineModel({
  currency: deccf.currencies.EUR,
  timeline: deccf.periods.monthly({from: '2026-05', count: 1}),
  metrics: {assessedAmount: deccf.metric({value: assessment.annualPensionAccrual, unit: 'money', annualAggregation: 'last'})},
});

modules["finnish-pension"].FINNISH_PENSION_2026Immutable FI 2026 partial pension rules, parameter provenance and assessment validity.

NationalPensionRules

const { FINNISH_PENSION_2026 } = modules["finnish-pension"];

modules["finnish-pension"].finnishPensionCalculates the unadjusted Finnish TyEL pension entitlement earned on insured employee earnings in calendar year 2026. pensionableEarnings is the annual insured earnings basis in EUR, supplied as a number, same-currency money or a declared amount source. basisSource names the payroll or pension record establishing insurance coverage and pensionable classification. Earnings accrue a 1.5% annual pension increment for every supported age group from 2026; the former 1.7% older-worker transition ended in 2025. Employee pension contributions are not deducted from this basis. annualPensionAccrual is the new yearly pension right and monthlyPensionAccrual is that right divided by twelve. Neither is cash paid or the person's accumulated whole-career pension. Life expectancy coefficients, indexation, deferred/early retirement, Kela, disability, unsalaried credits and self-employment are unsupported. Required options are id, owner, ruleYear:2026, the explicit scheme, basisSource and all numeric bases. There are no implicit amount or scheme defaults; pass zero explicitly when true. The owner is an entity or a keyed entity lookup, such as lookup(people.outputs.person, people.item.data.id) for repeated rows. Register the returned component in model components. outputs.assessment publishes the full record, and named numeric outputs are calculation projections usable in metrics and other declarations. rules exposes immutable national parameters, source links, validity and review dates. The model must use EUR and the annual calendar with periods starting on the first day, in January. Only the 2026 assessment year is supported. All amounts use EUR; rate calculations retain raw values before payment rounding. Unknown options/schemes, missing source classifications, negative or nonfinite bases, wrong currencies and uncovered dates/calendars fail explicitly. Callbacks capturing row projections cannot rebind. For repeated rows, use direct input references, expressions or bindable calculation references instead. Ordinary callbacks may use declared inputs that do not capture symbolic rows. No tax, bank transaction, capital balance or current pension payout is created.

(options: FinnishPensionOptions): FinnishPensionComponent

const {currencies, defineModel, entity, input, metric, periods} = deccf;

const {finnishPension} = modules["finnish-pension"];

const owner = entity.party();

const basis = input.money(60000, currencies.EUR, {ui: {label: "Insured annual earnings"}});

const pension = finnishPension({
  id: "employee-pension", owner, ruleYear: 2026, scheme: "tyel-accrual",
  basisSource: "Confirmed insured payroll record for 2026",
  pensionableEarnings: basis,
});

return defineModel({
  currency: currencies.EUR,
  timeline: periods.annual({from: "2026-01-01", count: 1}),
  entities: {owner},
  components: {pension: pension.component},
  metrics: {pensionResult: metric({label: "Unadjusted monthly pension increment, EUR/month", calculate: ctx => ctx.get(pension.outputs.monthlyPensionAccrual)})},
});

modules["finnish-pension"].FinnishPensionAssessmentFinnishPensionAssessment describes a model value used by the Finnish Pension editor functions.

Model value shape: { country: "FI"; currency: "EUR"; ruleYear: 2026; scheme: "tyel-accrual"; period: "annual"; coverage: "partial"; resultKind: "unadjusted-earned-benefit-increment"; roundingScope: "before-payment-rounding"; ruleSource: string; basisSource: string; annualPensionAccrual: number; monthlyPensionAccrual: number }

modules["finnish-pension"].FinnishPensionAssessmentOptionsResolved classified bases for the native pension assessment; all bases are required.

Model value shape: { readonly [K in keyof Omit<FinnishPensionOptions, 'id' | 'owner'>]: Exclude<FinnishPensionOptions[K], undefined> extends PensionNumberSource ? number : Exclude<FinnishPensionOptions[K], undefined> extends PensionAmountSource ? number | Money : FinnishPensionOptions[K]; }

modules["finnish-pension"].FinnishPensionComponentFinnishPensionComponent describes a model value used by the Finnish Pension editor functions.

Model value shape: { component: ComponentReference<Readonly<Record<string, deccf.ComponentOutputReference>>>; rules: NationalPensionRules; outputs: Readonly<{ assessment: CalculationReference; annualPensionAccrual: CalculationProjectionReference; monthlyPensionAccrual: CalculationProjectionReference; }> }

modules["finnish-pension"].FinnishPensionOptionsFinnishPensionOptions describes a model value used by the Finnish Pension editor functions.

Model value shape: { id: string; owner: EntityReference | LookupReference<EntityReference>; ruleYear: 2026; scheme: "tyel-accrual"; basisSource: string; pensionableEarnings: PensionAmountSource }

modules["finnish-pension"].NationalPensionRulesNationalPensionRules describes a model value used by the Finnish Pension editor functions.

Model value shape: { country: "FI"; currency: "EUR"; scheme: "tyel-accrual"; ruleYear: 2026; validFrom: "2026-01-01"; validToExclusive: "2027-01-01"; reviewedOn: string; coverage: "partial"; period: "annual"; roundingScope: "before-payment-rounding"; parameters: Readonly<Record<string, number | readonly number[]>>; sources: readonly Readonly<{ url: string; title: string; parameters: readonly string[]; reviewedOn: string; }>[] }

modules["finnish-pension"].PensionAmountSourcePensionAmountSource describes a model value used by the Finnish Pension editor functions.

Model value shape: number | Money | InputReference<number | Money> | InputProjectionReference<number | Money> | CalculationReference | CalculationProjectionReference | ExpressionReference | ((context: CalculationContext) => number | Money)

modules["finnish-pension"].PensionNumberSourcePensionNumberSource describes a model value used by the Finnish Pension editor functions.

Model value shape: number | InputReference<number> | InputProjectionReference<number> | CalculationReference | CalculationProjectionReference | ExpressionReference | ((context: CalculationContext) => number)

Icelandic Pension module

Select this module in model settings to use its names in the portal model editor (modules["icelandic-pension"]).

Model editor namePurpose and model value shape
modules["icelandic-pension"].assessIcelandicPensionPure assessment of the same partial 2026 scheme as icelandicPension. Numeric sources must already be resolved; amounts use the native period and currency. The explicit scheme and nonempty basisSource are mandatory. No owner, id, engine reference, callback, bank payment or personal pension-capital balance is created. Invalid/negative bases, foreign Money, missing data and unsupported schemes fail.

(options: IcelandicPensionAssessmentOptions): IcelandicPensionAssessment

const assessment = modules['icelandic-pension'].assessIcelandicPension({ruleYear: 2026, scheme: 'mandatory-minimum', basisSource: 'Confirmed covered monthly payroll', pensionableEarnings: 1000000});

return deccf.defineModel({
  currency: deccf.currencies.ISK,
  timeline: deccf.periods.monthly({from: '2026-05', count: 1}),
  metrics: {assessedAmount: deccf.metric({value: assessment.employeeContribution, unit: 'money', annualAggregation: 'last'})},
});

modules["icelandic-pension"].ICELANDIC_PENSION_2026Immutable IS 2026 partial pension rules, parameter provenance and assessment validity.

NationalPensionRules

const { ICELANDIC_PENSION_2026 } = modules["icelandic-pension"];

modules["icelandic-pension"].icelandicPensionCalculates Iceland's 2026 mandatory mutual-insurance minimum for an already covered employee's monthly pensionable wages. pensionableEarnings is the monthly ISK wage basis, supplied as a number, same-currency money or a declared amount source. basisSource names the verified payroll/enrolment record, which establishes coverage including the age-16-to-70 condition. The employee minimum is 4% and employer minimum 11.5%, totaling 15.5%. employeeContribution, employerContribution and totalContribution are minimum premiums, not an insurer quote, savings balance or current pension payment. Actual collective-agreement premiums may be higher and must be obtained separately; this slice does not silently treat the legal minimum as the employee's full agreement. Voluntary additional savings, self-employment, state pension, lifetime benefit pricing, disability/survivor benefits and tax are unsupported. Required options are id, owner, ruleYear:2026, the explicit scheme, basisSource and all numeric bases. There are no implicit amount or scheme defaults; pass zero explicitly when true. The owner is an entity or a keyed entity lookup, such as lookup(people.outputs.person, people.item.data.id) for repeated rows. Register the returned component in model components. outputs.assessment publishes the full record, and named numeric outputs are calculation projections usable in metrics and other declarations. rules exposes immutable national parameters, source links, validity and review dates. The model must use ISK and the monthly calendar with periods starting on the first day. Only the 2026 assessment year is supported. All amounts use ISK; rate calculations retain raw values before payment rounding. Unknown options/schemes, missing source classifications, negative or nonfinite bases, wrong currencies and uncovered dates/calendars fail explicitly. Callbacks capturing row projections cannot rebind. For repeated rows, use direct input references, expressions or bindable calculation references instead. Ordinary callbacks may use declared inputs that do not capture symbolic rows. No tax, bank transaction, capital balance or current pension payout is created.

(options: IcelandicPensionOptions): IcelandicPensionComponent

const {currencies, defineModel, entity, input, metric, periods} = deccf;

const {icelandicPension} = modules["icelandic-pension"];

const owner = entity.party();

const basis = input.money(1000000, currencies.ISK, {ui: {label: "Insured monthly earnings"}});

const pension = icelandicPension({
  id: "employee-pension", owner, ruleYear: 2026, scheme: "mandatory-minimum",
  basisSource: "Confirmed insured payroll record for 2026",
  pensionableEarnings: basis,
});

return defineModel({
  currency: currencies.ISK,
  timeline: periods.monthly({from: "2026-01-01", count: 1}),
  entities: {owner},
  components: {pension: pension.component},
  metrics: {pensionResult: metric({label: "Minimum pension contributions, ISK/month", calculate: ctx => ctx.get(pension.outputs.totalContribution)})},
});

modules["icelandic-pension"].IcelandicPensionAssessmentIcelandicPensionAssessment describes a model value used by the Icelandic Pension editor functions.

Model value shape: { country: "IS"; currency: "ISK"; ruleYear: 2026; scheme: "mandatory-minimum"; period: "monthly"; coverage: "partial"; resultKind: "minimum-insurance-contribution"; roundingScope: "before-payment-rounding"; ruleSource: string; basisSource: string; employeeContribution: number; employerContribution: number; totalContribution: number }

modules["icelandic-pension"].IcelandicPensionAssessmentOptionsResolved classified bases for the native pension assessment; all bases are required.

Model value shape: { readonly [K in keyof Omit<IcelandicPensionOptions, 'id' | 'owner'>]: Exclude<IcelandicPensionOptions[K], undefined> extends PensionNumberSource ? number : Exclude<IcelandicPensionOptions[K], undefined> extends PensionAmountSource ? number | Money : IcelandicPensionOptions[K]; }

modules["icelandic-pension"].IcelandicPensionComponentIcelandicPensionComponent describes a model value used by the Icelandic Pension editor functions.

Model value shape: { component: ComponentReference<Readonly<Record<string, deccf.ComponentOutputReference>>>; rules: NationalPensionRules; outputs: Readonly<{ assessment: CalculationReference; employeeContribution: CalculationProjectionReference; employerContribution: CalculationProjectionReference; totalContribution: CalculationProjectionReference; }> }

modules["icelandic-pension"].IcelandicPensionOptionsIcelandicPensionOptions describes a model value used by the Icelandic Pension editor functions.

Model value shape: { id: string; owner: EntityReference | LookupReference<EntityReference>; ruleYear: 2026; scheme: "mandatory-minimum"; basisSource: string; pensionableEarnings: PensionAmountSource }

modules["icelandic-pension"].NationalPensionRulesNationalPensionRules describes a model value used by the Icelandic Pension editor functions.

Model value shape: { country: "IS"; currency: "ISK"; scheme: "mandatory-minimum"; ruleYear: 2026; validFrom: "2026-01-01"; validToExclusive: "2027-01-01"; reviewedOn: string; coverage: "partial"; period: "monthly"; roundingScope: "before-payment-rounding"; parameters: Readonly<Record<string, number | readonly number[]>>; sources: readonly Readonly<{ url: string; title: string; parameters: readonly string[]; reviewedOn: string; }>[] }

modules["icelandic-pension"].PensionAmountSourcePensionAmountSource describes a model value used by the Icelandic Pension editor functions.

Model value shape: number | Money | InputReference<number | Money> | InputProjectionReference<number | Money> | CalculationReference | CalculationProjectionReference | ExpressionReference | ((context: CalculationContext) => number | Money)

modules["icelandic-pension"].PensionNumberSourcePensionNumberSource describes a model value used by the Icelandic Pension editor functions.

Model value shape: number | InputReference<number> | InputProjectionReference<number> | CalculationReference | CalculationProjectionReference | ExpressionReference | ((context: CalculationContext) => number)

Norwegian Pension module

Select this module in model settings to use its names in the portal model editor (modules["norwegian-pension"]).

Model editor namePurpose and model value shape
modules["norwegian-pension"].assessNorwegianPensionPure assessment of the same partial 2026 scheme as norwegianPension. Numeric sources must already be resolved; amounts use the native period and currency. The explicit scheme and nonempty basisSource are mandatory. No owner, id, engine reference, callback, bank payment or personal pension-capital balance is created. Invalid/negative bases, foreign Money, missing data and unsupported schemes fail.

(options: NorwegianPensionAssessmentOptions): NorwegianPensionAssessment

const assessment = modules['norwegian-pension'].assessNorwegianPension({ruleYear: 2026, scheme: 'national-insurance-accrual', basisSource: 'Confirmed annual pensionable earnings', pensionableEarnings: 600000, birthYear: 1980});

return deccf.defineModel({
  currency: deccf.currencies.NOK,
  timeline: deccf.periods.monthly({from: '2026-05', count: 1}),
  metrics: {assessedAmount: deccf.metric({value: assessment.notionalAccrual, unit: 'money', annualAggregation: 'last'})},
});

modules["norwegian-pension"].NORWEGIAN_PENSION_2026Immutable NO 2026 partial pension rules, parameter provenance and assessment validity.

NationalPensionRules

const { NORWEGIAN_PENSION_2026 } = modules["norwegian-pension"];

modules["norwegian-pension"].norwegianPensionCalculates income-based notional pension accrual under Norway's new National Insurance rules for calendar year 2026. pensionableEarnings is already classified annual NOK pensionable income: a number, same-currency money or declared amount source. basisSource names the record establishing that classification. birthYear is an integer numeric source from 1963 through 2013, excluding transitional cohorts and years below the age-13 boundary. Accrual is 18.1% of income capped at 7.1 times the annual average G. For 2026 average G is NOK 134419; the May G of NOK 136549 is not used for this annual cap. notionalAccrual is an increase in the notional pension right; coveredIncome, earningsCap and averageBaseAmount explain its basis. It is neither an employer premium nor liquid capital nor annual pension income. Care/service credits, old/transitional rules, guarantee pension, AFP, occupational schemes, indexation and conversion using individual life-expectancy divisors are unsupported. Required options are id, owner, ruleYear:2026, the explicit scheme, basisSource and all numeric bases. There are no implicit amount or scheme defaults; pass zero explicitly when true. The owner is an entity or a keyed entity lookup, such as lookup(people.outputs.person, people.item.data.id) for repeated rows. Register the returned component in model components. outputs.assessment publishes the full record, and named numeric outputs are calculation projections usable in metrics and other declarations. rules exposes immutable national parameters, source links, validity and review dates. The model must use NOK and the annual calendar with periods starting on the first day, in January. Only the 2026 assessment year is supported. All amounts use NOK; rate calculations retain raw values before payment rounding. Unknown options/schemes, missing source classifications, negative or nonfinite bases, wrong currencies and uncovered dates/calendars fail explicitly. Callbacks capturing row projections cannot rebind. For repeated rows, use direct input references, expressions or bindable calculation references instead. Ordinary callbacks may use declared inputs that do not capture symbolic rows. No tax, bank transaction, capital balance or current pension payout is created.

(options: NorwegianPensionOptions): NorwegianPensionComponent

const {currencies, defineModel, entity, input, metric, periods} = deccf;

const {norwegianPension} = modules["norwegian-pension"];

const owner = entity.party();

const basis = input.money(600000, currencies.NOK, {ui: {label: "Insured annual earnings"}});

const pension = norwegianPension({
  id: "employee-pension", owner, ruleYear: 2026, scheme: "national-insurance-accrual",
  basisSource: "Confirmed insured payroll record for 2026",
  pensionableEarnings: basis,
  birthYear: 1980,
});

return defineModel({
  currency: currencies.NOK,
  timeline: periods.annual({from: "2026-01-01", count: 1}),
  entities: {owner},
  components: {pension: pension.component},
  metrics: {pensionResult: metric({label: "Notional pension increment, NOK", calculate: ctx => ctx.get(pension.outputs.notionalAccrual)})},
});

modules["norwegian-pension"].NationalPensionRulesNationalPensionRules describes a model value used by the Norwegian Pension editor functions.

Model value shape: { country: "NO"; currency: "NOK"; scheme: "national-insurance-accrual"; ruleYear: 2026; validFrom: "2026-01-01"; validToExclusive: "2027-01-01"; reviewedOn: string; coverage: "partial"; period: "annual"; roundingScope: "before-payment-rounding"; parameters: Readonly<Record<string, number | readonly number[]>>; sources: readonly Readonly<{ url: string; title: string; parameters: readonly string[]; reviewedOn: string; }>[] }

modules["norwegian-pension"].NorwegianPensionAssessmentNorwegianPensionAssessment describes a model value used by the Norwegian Pension editor functions.

Model value shape: { country: "NO"; currency: "NOK"; ruleYear: 2026; scheme: "national-insurance-accrual"; period: "annual"; coverage: "partial"; resultKind: "notional-pension-accrual"; roundingScope: "before-payment-rounding"; ruleSource: string; basisSource: string; notionalAccrual: number; coveredIncome: number; earningsCap: number; averageBaseAmount: number }

modules["norwegian-pension"].NorwegianPensionAssessmentOptionsResolved classified bases for the native pension assessment; all bases are required.

Model value shape: { readonly [K in keyof Omit<NorwegianPensionOptions, 'id' | 'owner'>]: Exclude<NorwegianPensionOptions[K], undefined> extends PensionNumberSource ? number : Exclude<NorwegianPensionOptions[K], undefined> extends PensionAmountSource ? number | Money : NorwegianPensionOptions[K]; }

modules["norwegian-pension"].NorwegianPensionComponentNorwegianPensionComponent describes a model value used by the Norwegian Pension editor functions.

Model value shape: { component: ComponentReference<Readonly<Record<string, deccf.ComponentOutputReference>>>; rules: NationalPensionRules; outputs: Readonly<{ assessment: CalculationReference; notionalAccrual: CalculationProjectionReference; coveredIncome: CalculationProjectionReference; earningsCap: CalculationProjectionReference; averageBaseAmount: CalculationProjectionReference; }> }

modules["norwegian-pension"].NorwegianPensionOptionsNorwegianPensionOptions describes a model value used by the Norwegian Pension editor functions.

Model value shape: { id: string; owner: EntityReference | LookupReference<EntityReference>; ruleYear: 2026; scheme: "national-insurance-accrual"; basisSource: string; pensionableEarnings: PensionAmountSource; birthYear: PensionNumberSource }

modules["norwegian-pension"].PensionAmountSourcePensionAmountSource describes a model value used by the Norwegian Pension editor functions.

Model value shape: number | Money | InputReference<number | Money> | InputProjectionReference<number | Money> | CalculationReference | CalculationProjectionReference | ExpressionReference | ((context: CalculationContext) => number | Money)

modules["norwegian-pension"].PensionNumberSourcePensionNumberSource describes a model value used by the Norwegian Pension editor functions.

Model value shape: number | InputReference<number> | InputProjectionReference<number> | CalculationReference | CalculationProjectionReference | ExpressionReference | ((context: CalculationContext) => number)

Host website integrations

Use the complete embedded Calculator App reference for the host component API, requests, navigation, events and authenticated case access. These methods belong to your website, not model editor code.

App themes

See App themes for the eight palettes and densities, editor settings, versioned app metadata and integration examples.

Cash flow statements

In the presentation editor, use CashflowStatement({method: "indirect", period: "years"}) for reconciled profit, noncash adjustments, working capital, investing and financing. Exact-coverage groups and interleaved rows support explicit and cumulative sums. See the complete cash flow reference and callable examples for selections, defaults, validation and reconciliation.

return presentation({ cash: CashflowStatement({ method: "indirect", period: "years" }) });

Dashboard presentation widgets

Use DataCards({source}) for published card records or DataCards({cards}) for presentation-owned labels and metric/calculation selectors, RecordChart({source, xKey, series}) for published projections and UncertaintyChart({metrics, percentiles:[5,50,95]}) for actual Monte Carlo outcomes. See the complete dashboard widget reference and callable examples for arguments, units, timing, defaults and validation.

Initial Calculator run settings

Use deccf.defineModel({calculator:{defaultRun:{mode:"monte-carlo",trials:128,sampling:"sobol"}},currency:deccf.currencies.USD,timeline:deccf.periods.annual({from:"2026-01",count:1})}) to initialize new run controls. Saved selections take precedence. See the complete initial run settings reference for all supported fields, defaults and validation.

Static bindings and dynamic callbacks

Use declared bindings for calculation and flow reads, dynamic:true for the broad context, and deccf.prepare(model,{outputs}).run({parameters}) for repeated calculations with selected final values. Scope reusable validated data with prepared.withParameters(parameters) and project previous fields with deccf.bind.previous().project(path). See the complete execution reference for callable examples, history, once values, defaults and validation.