Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Consolidation

On February 1, the shop uses 3,000 yen from its bank deposits to form a wholly owned subsidiary. Prepare an opening consolidated balance sheet at that date from the two companies’ trial balances. A consolidation worksheet keeps the two source balances and the group adjustments (WorksheetAdjustment) as separate inputs.

Use exchangealgebra-0.6.1.1 in the project prepared in Add the package to a Stack project. Save the Haskell blocks in their displayed order as Main.hs.

Prepare the two trial balances

Carry forward the shop’s January balance-sheet amounts from Build the balance sheet. The program checks that the January ledger is in yen before dropping the currency element. Both February entries use the resulting reporting base, HatBase AccountTitles, with amounts in yen.

Code carried over from earlier chapters

{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}

module Main where

import Control.Monad (unless)
import Data.List.NonEmpty (NonEmpty((:|)))

import ExchangeAlgebra hiding (Yen, Dollar, map)
import qualified ExchangeAlgebra.Algebra.Core as Algebra
import ExchangeAlgebra.Journal ((.|))
import qualified ExchangeAlgebra.Journal as Journal
import qualified ExchangeAlgebra.IO.Input.Admission as Admission
import qualified ExchangeAlgebra.Accounting.Entries as Entries
import qualified ExchangeAlgebra.Accounting.Closing as Closing

import qualified ExchangeAlgebra.Accounting.TrialBalance as TrialBalance
import qualified ExchangeAlgebra.Accounting.Statements as Statements
import qualified ExchangeAlgebra.Accounting.Consolidation as Consolidation

-- | Currency element retained in the source journal.
data Unit
    = Yen       -- ^ Japanese yen.
    | Dollar    -- ^ US dollars.
    | Unit      -- ^ Inapplicable in an entry; unrestricted in a query.
    deriving (Eq, Ord, Show, Generic, Hashable)

instance Element Unit where
    wildcard = Unit

instance ExBaseClass (HatBase (AccountTitles, Unit)) where
    getAccountTitle (_ :< (account, _)) = account
    setAccountTitle (direction :< (_, unit)) account = direction :< (account, unit)

-- | Date and description; the example supplies valid calendar dates.
data EntryNote = EntryNote (Integer, Int, Int) String
    deriving (Eq, Ord, Show, Generic, Hashable)

instance Journal.Note EntryNote where
    plank = EntryNote (0, 0, 0) ""

-- | One entry with account and currency elements; the alias adds no validation.
type Entry = Alg MoneyDecimal (HatBase (AccountTitles, Unit))

-- | January journal with one distinct note per transaction.
type Book = Journal.Journal EntryNote MoneyDecimal (HatBase (AccountTitles, Unit))
-- | Attach a January date and description after constructing all terms.
record :: Int -> String -> Entry -> Book
record day description algebra = algebra .| EntryNote (2026, 1, day) description

-- | January 1: capital paid into Bank A's savings account.
opening :: Book
opening = record 1 "Opening capital"
    (10000 .@ Not :< (Deposits, Yen)
  .+ 10000 .@ Not :< (CapitalStock, Yen))

-- | Transactions through January 30, before adjusting entries.
sourceJournal :: Book
sourceJournal = opening
    .+ record 10 "Withdrawal from Bank A"
        (3000 .@ Not :< (Cash, Yen) .+ 3000 .@ Hat :< (Deposits, Yen))
    .+ record 15 "Withdrawal from Bank A"
        (2000 .@ Not :< (Cash, Yen) .+ 2000 .@ Hat :< (Deposits, Yen))
    .+ record 20 "Purchase of goods"
        (500 .@ Not :< (Purchases, Yen) .+ 500 .@ Hat :< (Cash, Yen))
    .+ record 25 "Yen-dollar exchange"
        (1500 .@ Hat :< (Cash, Yen) .+ 10 .@ Not :< (Cash, Dollar))
    .+ record 28 "Cash sale"
        (2000 .@ Not :< (Cash, Yen) .+ 2000 .@ Not :< (Sales, Yen))
    .+ record 30 "January and February rent"
        (1200 .@ Not :< (RentExpense, Yen) .+ 1200 .@ Hat :< (Cash, Yen))
-- | Express dollars in yen at 150 yen per dollar, preserving account and side.
toYen :: MoneyDecimal
      -> HatBase (AccountTitles, Unit)
      -> (MoneyDecimal, HatBase (AccountTitles, Unit))
toYen amount (direction :< (account, Dollar)) = (amount * 150, direction :< (account, Yen))
toYen amount basis = (amount, basis)

-- | Reporting representation at the January 31 rate, equal to the exchange rate.
yenJournal :: Book
yenJournal = Journal.map (Algebra.mapPosting toYen) sourceJournal

-- | Check the converted journal without changing its notes or term sequences.
acceptedJanuary :: Either String (Admission.Admitted EntryNote (HatBase (AccountTitles, Unit)))
acceptedJanuary = either (Left . show . Admission.failureErrors) Right
    (Admission.admit yenJournal)
-- | Print a labeled result, retaining the library's diagnostic constructors.
printNamed :: Show a => String -> a -> IO ()
printNamed label value = putStrLn (label ++ ": " ++ show value)

-- | Stop the example on an unexpected checked failure.
require :: Show e => Either e a -> IO a
require = either (ioError . userError . show) pure

-- | Drop the currency element only after checking every term is in yen.
-- This reporting projection removes the currency element; it does not net terms.
auditLedger :: Entry -> Either String (Alg MoneyDecimal (HatBase AccountTitles))
auditLedger ledger
    | Algebra.foldEntries allYen True ledger = Right (Algebra.mapPosting dropUnit ledger)
    | otherwise = Left "Audit requires yen on every term"
  where
    allYen :: Bool -> MoneyDecimal -> HatBase (AccountTitles, Unit) -> Bool
    allYen result _ (_ :< (_, unit)) = result && unit == Yen

    dropUnit :: MoneyDecimal
             -> HatBase (AccountTitles, Unit)
             -> (MoneyDecimal, HatBase AccountTitles)
    dropUnit amount (direction :< (account, _)) = (amount, direction :< account)
-- | January 31: defer February's half of the rent, using the rent transfer table.
rentAdjustment :: Entry -> Either String Entry
rentAdjustment ledger = do
    table <- either (Left . show) Right $ mkTransferTable
        [(RentExpense, (.#)) .-> (PrepaidExpenses, (.#)) |% Portion 1 2]
    either (Left . show) Right (transferEntries table ledger)

-- | Keep the currency element when building the periodic inventory adjustment.
yenBase :: Entries.MkBase (HatBase (AccountTitles, Unit))
yenBase direction account = direction :< (account, Yen)

-- | No beginning inventory; the January 31 physical count is worth 200 yen at cost.
inventoryAdjustment :: Entry
inventoryAdjustment = Entries.cogsAdjustmentEntries yenBase 0 200

-- | Add adjustments under distinct notes and check the resulting journal again.
adjustedJanuary :: Book -> Either String Book
adjustedJanuary journal = do
    rent <- rentAdjustment (Journal.toAlg journal)
    let adjusted :: Book
        adjusted = journal
                .+ record 31 "Defer February rent" rent
                .+ record 31 "Ending inventory" inventoryAdjustment
    admitted <- either (Left . show . Admission.failureErrors) Right (Admission.admit adjusted)
    pure (Admission.admittedJournal admitted)
-- | Generate additional closing entries from the adjusted ledger, then check the resulting journal.
closedJanuary :: Book -> Either String Book
closedJanuary journal = do
    additions <- either (Left . show) Right (Closing.closingEntries (Journal.toAlg journal))
    let closed :: Book
        closed = journal .+ record 31 "Close January" additions
    admitted <- either (Left . show . Admission.failureErrors) Right (Admission.admit closed)
    pure (Admission.admittedJournal admitted)
-- | Print the balance-sheet lines and totals for this example.
printBalanceSheet :: Statements.FinancialStatements MoneyDecimal -> IO ()
printBalanceSheet statements = do
    let lines' = Statements._statementLines statements
        inSections sections =
            [ line | section <- sections
                   , line <- lines'
                   , Statements._lineSection line == section
            ]
        assets = inSections [Statements.CurrentAssetsSection, Statements.NoncurrentAssetsSection]
        liabilitiesAndEquity = inSections
            [ Statements.CurrentLiabilitiesSection
            , Statements.NoncurrentLiabilitiesSection
            , Statements.EquitySection
            ]
    mapM_ printLine assets
    printNamed "Total assets" (sum (map Statements._lineAmount assets))
    mapM_ printLine liabilitiesAndEquity
    printNamed "Total liabilities and equity"
        (sum (map Statements._lineAmount liabilitiesAndEquity))

-- | Keep the displayed section, account label, side, and magnitude visible.
printLine :: Statements.StatementLine MoneyDecimal -> IO ()
printLine line = putStrLn $ unwords
    [ show (Statements._lineSection line)
    , show (Statements._lineLabel line)
    , show (Statements._lineSide line)
    , showValue (Statements._lineAmount line)
    ]

In the parent’s books, debit subsidiary shares and credit deposits for 3,000 yen. In the parent’s standalone balance sheet, SubsidiaryStocks represents subsidiary shares carried at acquisition cost, with no equity-method adjustment. In the subsidiary’s books, debit cash and credit capital stock for 3,000 yen. Use bar to obtain the parent’s February 1 balances, then identify each entity’s balances with a TrialBalanceSource.

-- | Parent and subsidiary trial balances immediately after the February 1 contribution.
entityBalances :: Alg MoneyDecimal (HatBase AccountTitles)
               -> NonEmpty (Consolidation.TrialBalanceSource String MoneyDecimal)
entityBalances januaryEnd =
    Consolidation.TrialBalanceSource "shop" parent :|
    [Consolidation.TrialBalanceSource "subsidiary" subsidiary]
  where
    parent = bar (januaryEnd
        .+ (3000 .@ Not :< SubsidiaryStocks)
        .+ (3000 .@ Hat :< Deposits))
    subsidiary = (3000 .@ Not :< Cash)
               .+ (3000 .@ Not :< CapitalStock)

Eliminate the investment and subsidiary capital

The parent’s subsidiary shares and the subsidiary’s capital stock record the same contribution within the group. Eliminate them with a debit to CapitalStock and a credit to SubsidiaryStocks, each for 3,000 yen. Both terms decrease a balance, so both use Hat. Record the entry as a WorksheetAdjustment linked to both companies. The adjustment belongs to the consolidated worksheet.

-- | Debit the subsidiary's capital and credit the parent's investment.
elimination :: Consolidation.WorksheetAdjustment String String MoneyDecimal
elimination = Consolidation.WorksheetAdjustment
    "investment against subsidiary capital"
    ("shop" :| ["subsidiary"])
    ((3000 .@ Hat :< CapitalStock)
  .+ (3000 .@ Hat :< SubsidiaryStocks))

Supply the period result, its attribution, and the equity roll-forwards in a WorksheetLinkage. February’s result is zero at incorporation. January’s 1,100 yen is February’s opening retained earnings. With zero dividends and a zero February result, the closing figure used in the roll-forward and the balance-sheet figure are also 1,100 yen at the reporting date. The parent owns all the shares, so the noncontrolling-interest fields have zero amounts or NoBalance.

validateConsolidationWorksheet checks the balance of each source and adjustment, the adjustment’s source IDs and permitted accounts, and the equations among the supplied linkage figures. Cross-check those figures against the statement balances separately. The example takes retained earnings from the January ledger and checks the consolidated balances after combining.

-- | Link February's opening and reporting balances at the formation date.
linkage :: TrialBalance.AccountBalance MoneyDecimal -> Consolidation.WorksheetLinkage MoneyDecimal
linkage retained = Consolidation.WorksheetLinkage
    { Consolidation._profitOrLossNetIncome = Statements.PeriodBreakEven
    , Consolidation._profitOrLossNetIncomeAttributableToOwners = Statements.PeriodBreakEven
    , Consolidation._statementOfChangesNetIncomeAttributableToOwners = Statements.PeriodBreakEven
    , Consolidation._openingRetainedEarnings = retained
    , Consolidation._retainedEarningsDividends = 0
    , Consolidation._statementOfChangesClosingRetainedEarnings = retained
    , Consolidation._balanceSheetRetainedEarnings = retained
    , Consolidation._openingNonControllingInterests = TrialBalance.NoBalance
    , Consolidation._nonControllingInterestsPeriodShare = Statements.PeriodBreakEven
    , Consolidation._nonControllingInterestsDividends = 0
    , Consolidation._statementOfChangesClosingNonControllingInterests = TrialBalance.NoBalance
    , Consolidation._balanceSheetNonControllingInterests = TrialBalance.NoBalance
    }

Inspect the consolidated balance sheet

combinedWorksheet adds the two trial balances and the elimination with .+, retaining terms on the same base. Apply bar explicitly to inspect the net totals, and present the combined ledger as a Combined balance sheet.

main :: IO ()
main = do
    accepted <- require acceptedJanuary
    adjusted <- require (adjustedJanuary (Admission.admittedJournal accepted))
    closed <- require (closedJanuary adjusted)
    januaryEnd <- require (auditLedger (Journal.toAlg closed))
    let retained = TrialBalance.balanceFor RetainedEarnings
            (TrialBalance.accountBalances januaryEnd)
        input = Consolidation.WorksheetInput
            (entityBalances januaryEnd) [elimination] (linkage retained)
    worksheet <- require (Consolidation.validateConsolidationWorksheet input)
    let combined = Consolidation.combinedWorksheet worksheet
        net = bar combined
        context = (Statements.jcciSecondGradeContext Statements.Combined)
            { Statements._presentationProfile = Statements.CanonicalEnglish }
        balances = TrialBalance.accountBalances net
    unless (TrialBalance.balanceFor RetainedEarnings balances == retained) $
        ioError (userError "Combined retained earnings do not match the worksheet linkage")
    printNamed "Combined net totals (debit, credit)" (norm (decL net), norm (decR net))
    printNamed "Investment balance" (TrialBalance.balanceFor SubsidiaryStocks balances)
    printNamed "Group capital stock" (TrialBalance.balanceFor CapitalStock balances)
    statement <- require (Statements.present context TrialBalance.AfterClosing combined)
    putStrLn "\nOpening consolidated balance sheet at February 1 (yen)"
    printBalanceSheet statement

In your project directory, run stack exec -- ghc -Wall -Werror Main.hs -o consolidation-example, then run ./consolidation-example.

Combined net totals (debit, credit): (11100,11100)
Investment balance: NoBalance
Group capital stock: CreditBalance 10000

Opening consolidated balance sheet at February 1 (yen)
CurrentAssetsSection "Cash" Debit 8300
CurrentAssetsSection "Savings deposits" Debit 2000
CurrentAssetsSection "Merchandise inventory" Debit 200
CurrentAssetsSection "Prepaid expenses" Debit 600
Total assets: 11100
EquitySection "Capital stock" Credit 10000
EquitySection "Retained earnings" Credit 1100
Total liabilities and equity: 11100

The investment has no remaining balance. Capital stock is 10,000 yen, the parent’s own capital. The group shows cash of 8,300 yen and deposits of 2,000 yen. Together with inventory of 200 yen and prepaid expenses of 600 yen, assets total 11,100 yen. There are no liabilities, and equity totals 11,100 yen.

Tested with exchangealgebra-0.6.1.1 on 2026-11-20.

Reference

Type or operationInputs and result
TrialBalanceSourceIdentify one entity and supply its balanced trial balance over HatBase AccountTitles.
WorksheetAdjustmentSupply an independently balanced adjustment with its own ID and the nonempty list of source IDs it affects.
WorksheetLinkageSupply the period result and its attribution, and reconcile opening balances, period movements, dividends, and closing balances for retained earnings and noncontrolling interests.
validateConsolidationWorksheet inputValidate the worksheet or return a nonempty list of WorksheetError values identifying the rejected inputs.
combinedWorksheet, validatedSources, and validatedAdjustmentsProject the combined ledger, or retrieve the original source and adjustment columns to trace each contribution.