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

Closing entries

Prepare January’s closing entries after the rent and inventory adjustments in Adjusting entries. Sales of 2,000 yen less cost of goods sold of 300 yen and rent expense of 600 yen give a profit of 1,100 yen. Transfer the revenue and expense balances to retained earnings, the equity account that accumulates undistributed profits.

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

Recover the adjusted journal

The program begins with the code from Adjusting entries and the chapters before it.

Code carried over from earlier chapters

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

module Main where

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.TrialBalance as TrialBalance
import qualified ExchangeAlgebra.Accounting.Entries as Entries
import qualified ExchangeAlgebra.Accounting.Closing as Closing

-- | 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

-- | Show gross debit and credit totals in yen, without netting the source.
printTotals :: Entry -> IO ()
printTotals ledger = do
    printNamed "Term totals (debit, credit)" (norm (decL ledger), norm (decR ledger))
    printNamed "Balanced" (balance ledger)
-- | Accounts used in the shop, ordered for repeatable output including zero balances.
accounts :: [AccountTitles]
accounts = [Cash, Deposits, PrepaidExpenses, MerchandiseInventory,
            Purchases, RentExpense, Sales, CapitalStock, RetainedEarnings]

-- | 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)

-- | Print account debit and credit totals, net balances, balance totals, and accounting findings.
printTrial :: TrialBalance.TrialBalanceStage -> Entry -> IO ()
printTrial stage ledger = do
    reporting <- require (auditLedger ledger)
    let balances = TrialBalance.accountBalances reporting
        pairs :: [(MoneyDecimal, MoneyDecimal)]
        pairs = map (TrialBalance.balancePair . (`TrialBalance.balanceFor` balances)) accounts
        totals :: (MoneyDecimal, MoneyDecimal)
        totals = foldr TrialBalance.addPair (0, 0) pairs
        row :: AccountTitles -> IO ()
        row account = do
            let selected = projByAccountTitle account ledger
            printNamed (show account)
                (norm (decL selected), norm (decR selected),
                 TrialBalance.balanceFor account balances)
    putStrLn "Account: (debit turnover, credit turnover, balance)"
    mapM_ row accounts
    printNamed "Balance totals (debit, credit)" totals
    printTotals ledger
    printNamed "Findings" $ TrialBalance.trialBalanceFindings
        (TrialBalance.TrialBalanceInput reporting stage mempty [] mempty)
-- | 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 closing entries

Closing.closingEntries reads the ledger through the closing date and returns only additional entries. For each eligible account-and-currency base, it computes the exact net, reverses that balance, and adds a term with the matching amount to RetainedEarnings. Other elements of the base are preserved. It sums source balances internally, without calling bar; separate contributions from different expense and revenue accounts remain separate terms.

See Account titles and their attributes for the closing rule and division used to select accounts for transfer to RetainedEarnings.

-- | 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)

For Sales, debit 2,000 yen by reversing its Not balance with Hat, and credit RetainedEarnings. For Purchases and RentExpense, credit 300 and 600 yen to cancel their debit balances, and debit RetainedEarnings for the same amounts. RetainedEarnings therefore has credits of 2,000 yen and debits of 900 yen, leaving a credit balance of 1,100 yen. Japanese bookkeeping textbooks collect revenue and expenses in an income summary account before transferring the result to retained earnings, whereas exchangealgebra-0.6.1.1’s closingEntries transfers those balances directly to RetainedEarnings, producing the same final balances.

Inspect the post-closing trial balance

-- | Run the January procedure and print its checked results.
main :: IO ()
main = do
    accepted <- require acceptedJanuary
    adjusted <- require
              $ adjustedJanuary
              $ Admission.admittedJournal accepted
    additions <- require
               $ Closing.closingEntries
               $ Journal.toAlg adjusted
    printNamed "Closing entries" additions
    closed <- require (closedJanuary adjusted)
    printTrial TrialBalance.AfterClosing (Journal.toAlg closed)
    printNamed "Closing again" (Closing.closingEntries (Journal.toAlg closed))

Run stack exec -- ghc -Wall -Werror Main.hs -o closing-example, then run ./closing-example in your project directory. The program prints:

Closing entries: 300:@Hat:<(RetainedEarnings,Yen) .+ 600:@Hat:<(RetainedEarnings,Yen) .+ 2000:@Not:<(RetainedEarnings,Yen) .+ 600:@Hat:<(RentExpense,Yen) .+ 300:@Hat:<(Purchases,Yen) .+ 2000:@Hat:<(Sales,Yen)
Account: (debit turnover, credit turnover, balance)
Cash: (8500,3200,DebitBalance 5300)
Deposits: (10000,5000,DebitBalance 5000)
PrepaidExpenses: (600,0,DebitBalance 600)
MerchandiseInventory: (200,0,DebitBalance 200)
Purchases: (500,500,NoBalance)
RentExpense: (1200,1200,NoBalance)
Sales: (2000,2000,NoBalance)
CapitalStock: (0,10000,CreditBalance 10000)
RetainedEarnings: (900,2000,CreditBalance 1100)
Balance totals (debit, credit): (11100,11100)
Term totals (debit, credit): (23900,23900)
Balanced: True
Findings: []
Closing again: Right 0

Sales, Purchases, and RentExpense each have NoBalance; their original and closing terms remain in the columns for debit and credit totals. Cash, Deposits, PrepaidExpenses, and MerchandiseInventory total 11,100 yen on the debit side. CapitalStock of 10,000 yen and RetainedEarnings of 1,100 yen total 11,100 yen on the credit side. Only assets and equity have balances in this example; there are no liabilities.

Check with AfterClosing so residual revenue and expense balances are findings. Checking the journal again alone cannot establish that closing was complete. The empty findings and Closing again: Right 0 confirm that no eligible balance remains for another closing entry. Keep the checked closed journal with all dated entries; a balance report is not a replacement for that record.

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

Reference

Type or operationInputs and result
Closing.closingEntries ledgerReturn additional entries to RetainedEarnings, or Left for an invalid eligible balance.
TrialBalance.AfterClosingCheck the post-closing trial balance, including unclosed revenue and expense accounts.
additions .| note and journal .+ closingJournalAttach a closing note to the additions, then add them to the adjusted journal.