SlideShare a Scribd company logo
1 of 34
Download to read offline
BUILDING A
POWERFUL DOUBLE-
ENTRY ACCOUNTING
SYSTEM
Lucas Cavalcanti
DOUBLE-ENTRY ACCOUNTING
ANCIENT, UBIQUITOUS TECHNOLOGY
USER BALANCES
Future bills
Open bill
Due bill
Available balance
OPERATIONS
Purchases
Chargebacks
Payments
BALANCE
SHEET
DEBIT CREDIT
General Ledger
USEFUL ABSTRACTIONS
Income statement
Cash flow statement
Balance sheet
LIABILITY
ASSET
EQUITY
Debits Credits
PROPERTY:
on each movement
Image © http://chestofbooks.com/business/reference/Home-Cyclopedia-Of-Business/Bill-Book.html
Credits (CR):
- $97 on liability payables
(we will pay the merchant)
- $3 Credit on P&L interchange
(our profit)
- $100 on off-balance
asset current-limit
EXAMPLE: A purchase of $100
Debits (DR):
- $100 on asset settled
(we will receive
it from the customer)
- $100 on off-balance
liability current-limit-cp
EXAMPLE: A payment of $100
Debits (DR):
- $100 on asset cash
(we received it
from the customer)
- $100 on off-balance
asset current-limit
Credits (CR):
- $100 on asset settled
(we paid the purchase)
- $100 on off balance
liability current-limit-cp
DOUBLE ENTRY ACCOUNTING
EVENTS TRIGGERING MOVEMENTS
• purchases
• payments
• bills
IMMUTABLE
• append-only
• entry log
• can fix past by compensating
INVARIANTS
• movements sums to zero
• a book-account balance is sum of credits
and debits
1 MOVEMENT => N ENTRIES
(s/defschema Entry {:entry/id s/Uuid

:entry/amount PositiveAmount 

:entry/debit-account BookAccount

:entry/credit-account BookAccount

:entry/post-date LocalDate

:entry/movement Movement})
So by design,
(ns double-entry.models.entry

(:require [schema.core :as s]))
1 BUSINESS EVENT => 1 MOVEMENT + META
e.g new-purchase, new-payment, new-bill
(s/defschema Movement {:movement/id s/Uuid

:movement/flow-id String

:movement/topic Topic

:movement/owner-account Account

:movement/produced-at LocalDateTime

:movement/consumed-at LocalDateTime

:movement/user String})
(s/defschema Meta {:meta/id s/Uuid

:meta/movement Movement

:meta/entity (s/either Payment Purchase Bill ...)})
DECLARATIVE RULES FOR MOVEMENTS
(ns common-schemata.wire)
(s/defschema Purchase

{:purchase {:id s/Uuid

:merchant String

:amount t-money/PositiveAmount
:interchange t-money/PositiveAmount

:time LocalDateTime

…}})
(s/defschema Payment

{:payment {:id s/Uuid

:amount t-money/PositiveAmount

:post-date LocalDate

…}})
DECLARATIVE RULES FOR MOVEMENTS
(def new-purchase

[{:entry/debit-account :book-account.asset/settled-brazil

:entry/credit-account :book-account.liability/payable-brazil

:entry/amount (comp :amount :purchase)

:entry/post-date (comp time->date :time :purchase)}
{:entry/debit-account :book-account.liability/payable-brazil

:entry/credit-account :book-account.profit-and-loss/interchange-brazil

:entry/amount (comp :interchange :purchase)

:entry/post-date (comp time->date :time :purchase)}


{:entry/debit-account :book-account.liability/current-limit-counterparty

:entry/credit-account :book-account.asset/current-limit

:entry/amount (comp :amount :purchase)

:entry/post-date (comp time->date :time :purchase)}])
DECLARATIVE RULES FOR MOVEMENTS
(def new-payment

[{:entry/debit-account :book-account.asset/transitory-bank

:entry/credit-account :book-account.asset/settled-brazil

:entry/amount (comp :amount :payment)

:entry/post-date (comp :post-date :payment)}


{:entry/debit-account :book-account.asset/current-limit

:entry/credit-account :book-account.liability/current-limit-counterparty

:entry/amount (comp :amount :payment)

:entry/post-date (comp :post-date :purchase)}])
[{:entry/id (uuid)

:entry/amount 100.0M

:entry/debit-account :book-account.asset/settled-brazil

:entry/credit-account :book-account.liability/payable-brazil

:entry/post-date #nu/date "2016-12-01"

:entry/movement new-purchase}


{:entry/id (uuid)

:entry/amount 3.0M

:entry/debit-account :book-account.liability/payable-brazil

:entry/credit-account :book-account.profit-and-loss/interchange-brazil

:entry/post-date #nu/date "2016-12-01"

:entry/movement new-purchase}
{:entry/id (uuid)

:entry/amount 100.0M

:entry/debit-account :book-account.liability/current-limit-counterparty

:entry/credit-account :book-account.asset/current-limit

:entry/post-date #nu/date "2016-12-01"

:entry/movement new-purchase}]
{:purchase

{:id (uuid)

:amount 100.0M

:interchange 3.0M

:time #nu/time "2016-12-01T13:37:42Z"}}
Rulebook
[{:entry/id (uuid)

:entry/amount 100.0M

:entry/debit-account :book-account.asset/transitory-bank

:entry/credit-account :book-account.asset/settled-brazil

:entry/post-date #nu/date "2016-12-01"

:entry/movement new-payment}
{:entry/id (uuid)

:entry/amount 100.0M

:entry/debit-account :book-account.asset/current-limit

:entry/credit-account :book-account.liability/current-limit-counterparty

:entry/post-date #nu/date "2016-12-01"

:entry/movement new-payment}]
{:payment

{:id (uuid)

:amount 100.0M

:post-date #nu/date "2016-12-01"}}
Rulebook
Cumulative cache
(balance sheet)
Event
(log)
2 LOGS AND A CACHE
ACTUAL TIME
audit trail / Datomic log
“when did we know”day 0 day 30 day 90
SYSTEM OF RECORD TIME
official version of events
uses business-relevant “post dates”
can correct after the fact
day 90
day 0day 0
day 30
SANITY CHECKS / BUSINESS INVARIANTS
• Balances must be always positive or always negative
• Cannot have a “late” balance there is a “prepaid” balance
• A purchase should “move” exactly the purchase amount on
assets and on current limit
(def balances-property
(prop/for-all [account (g/generator Account)

events (gen/vector (gen/one-of [(g/generator Purchase)

(g/generator Payment)

...]))]

(->> (empty-db)

(save-all! account events)

:db-after

(balances-are-positive!)))
(fact (tc/quick-check 50 balances-property) => (th/embeds {:result true}))
GENERATIVE TESTING
(ns double-entry.controllers.rulebook-test

(:require [midje.sweet :refer :all]
[clojure.test.check.properties :as prop]

[clojure.test.check :as tc]

[schema-generators.generators :as g]

[clojure.test.check.generators :as gen]))
EVENT STREAM FOR
A SINGLE CUSTOMER
1. Business events generate idempotent Kafka
messages
2. For each event, apply functions to convert the
event data into a movement with 1+ entries
• Movements balance by design
• Movements associate provenance metadata
3. Pre-check guarantees invariants against db value
4. Eagerly cache resulting balances
debit-account credit-account amount
a/max-limit
a/current-limit
l/max-limit-cp
l/current-limit-cp
initial-limit
15000.00
15000.00
CARD ISSUED
debit-account credit-account amount
new-purchase / settle-brazil
100.00
100.00
100.00
100.00
CARD ISSUED FIRST PURCHASE
l/current-limit-cp
a/unsettled
l/unsettled-cp
a/settled-brazil
a/current-limit
l/unsettled-cp
a/unsettled
l/payable-brazil
debit-account credit-account amount
closed-bill
15.00
100.00
CARD ISSUED FIRST PURCHASE
a/minimum-payment
a/closed
l/minimum-payment-cp
a/settled-brazil
FIRST BILL CLOSES
debit-account credit-account amount
new-payment
10.00
10.00
10.00
CARD ISSUED FIRST PURCHASE
a/current-limit
l/minimum-payment-cp
a/transitory-bank
l/current-limit-cp
a/minimum-payment
a/late
FIRST BILL CLOSES PARTIAL PAYMENT
debit-account credit-account amount
new-adjustment
7.00
7.00
CARD ISSUED FIRST PURCHASE
l/current-limit-cp
a/settled-financed
a/current-limit
e/revolving-interest
FIRST BILL CLOSES PARTIAL PAYMENT INTEREST ASSESSED
debit-account credit-account amount
closed-bill
7.00
5.00
14.55
7.00
90.00
5.00
7.00
90.00
7.00
7.00
7.00
2.55
7.00
CARD ISSUED FIRST PURCHASE
a/late
l/minimum-payment-cp
a/minimum-payment
a/closed
a/current-limit
l/minimum-payment-cp
a/transitory-bank
a/transitory-bank
l/prepaid
a/current-limit
l/minimum-payment-cp
l/minimum-payment-cp
a/closed
a/closed
a/minimum-payment
l/minimum-payment-cp
a/settled-financed
l/current-limit-cp
a/minimum-payment
l/prepaid
a/late
a/closed
l/current-limit-cp
a/minimum-payment
a/minimum-payment
a/late
FIRST BILL CLOSES PARTIAL PAYMENT INTEREST ASSESSED PAYMENT IN FULL
ZOOMING OUT
2015-01 2015-04 2015-07 2015-10 2015-01 2016-03
DETECTING OPERATIONAL MISTAKES
USE CASES
MANAGEMENT ACCOUNTING
• delinquency tables by cohort and aging
• receivables (domestic, foreign, financed)
• revenue per customer (interchange, interest, fx spread)
REPORTING
• covenants
• regulatory
FINANCIAL ACCOUNTING
• consolidate to ERP
Declarative rules are extensible for additional financial products
(e.g., already extending to rewards, debt financing)
Financial analysis applies at a micro level (negative balances,
weird ratios, operational problems)
Business-specific invariants provide safety (declare mutually
exclusive and impossible states,alert unexpected situations)
Generative testing finds real bugs
Service is shardable by customer account (no interactions
between accounts)
WHAT DO WE LIKE?
33
IF YOU ARE ENTRUSTED WITH A CUSTOMER’S
FINANCIAL RELATIONSHIP, CONSIDER BUILDING A
DOUBLE-ENTRY SYSTEM FOR YOUR DOMAIN
Thank you!
Lucas Cavalcanti
@lucascs
IF YOU CHOOSE TO DO SO, USE ALL THE POWER
FUNCTIONAL PROGRAMMING GIVES YOU

More Related Content

What's hot

Top 5 mistakes when writing Spark applications
Top 5 mistakes when writing Spark applicationsTop 5 mistakes when writing Spark applications
Top 5 mistakes when writing Spark applicationshadooparchbook
 
Advanced c programming in Linux
Advanced c programming in Linux Advanced c programming in Linux
Advanced c programming in Linux Mohammad Golyani
 
L2 over l3 ecnaspsulations (english)
L2 over l3 ecnaspsulations (english)L2 over l3 ecnaspsulations (english)
L2 over l3 ecnaspsulations (english)Motonori Shindo
 
Java troubleshooting thread dump
Java troubleshooting thread dumpJava troubleshooting thread dump
Java troubleshooting thread dumpejlp12
 
Flash for Apache Spark Shuffle with Cosco
Flash for Apache Spark Shuffle with CoscoFlash for Apache Spark Shuffle with Cosco
Flash for Apache Spark Shuffle with CoscoDatabricks
 
Linux Kernel vs DPDK: HTTP Performance Showdown
Linux Kernel vs DPDK: HTTP Performance ShowdownLinux Kernel vs DPDK: HTTP Performance Showdown
Linux Kernel vs DPDK: HTTP Performance ShowdownScyllaDB
 
Introduction to DPDK
Introduction to DPDKIntroduction to DPDK
Introduction to DPDKKernel TLV
 
Introducing DataFrames in Spark for Large Scale Data Science
Introducing DataFrames in Spark for Large Scale Data ScienceIntroducing DataFrames in Spark for Large Scale Data Science
Introducing DataFrames in Spark for Large Scale Data ScienceDatabricks
 
High-speed Database Throughput Using Apache Arrow Flight SQL
High-speed Database Throughput Using Apache Arrow Flight SQLHigh-speed Database Throughput Using Apache Arrow Flight SQL
High-speed Database Throughput Using Apache Arrow Flight SQLScyllaDB
 
01 ip oc180 e1_1 zxr10 m6000_t8000 basic operation (v1.00.20)
01 ip oc180 e1_1 zxr10 m6000_t8000 basic operation (v1.00.20)01 ip oc180 e1_1 zxr10 m6000_t8000 basic operation (v1.00.20)
01 ip oc180 e1_1 zxr10 m6000_t8000 basic operation (v1.00.20)legasu zemene
 
nftables - the evolution of Linux Firewall
nftables - the evolution of Linux Firewallnftables - the evolution of Linux Firewall
nftables - the evolution of Linux FirewallMarian Marinov
 
Using eBPF for High-Performance Networking in Cilium
Using eBPF for High-Performance Networking in CiliumUsing eBPF for High-Performance Networking in Cilium
Using eBPF for High-Performance Networking in CiliumScyllaDB
 
Kernel Recipes 2017 - 20 years of Linux Virtual Memory - Andrea Arcangeli
Kernel Recipes 2017 - 20 years of Linux Virtual Memory - Andrea ArcangeliKernel Recipes 2017 - 20 years of Linux Virtual Memory - Andrea Arcangeli
Kernel Recipes 2017 - 20 years of Linux Virtual Memory - Andrea ArcangeliAnne Nicolas
 
PostgreSQL Streaming Replication Cheatsheet
PostgreSQL Streaming Replication CheatsheetPostgreSQL Streaming Replication Cheatsheet
PostgreSQL Streaming Replication CheatsheetAlexey Lesovsky
 
How to build a virtual machine
How to build a virtual machineHow to build a virtual machine
How to build a virtual machineTerence Parr
 
Zeus: Uber’s Highly Scalable and Distributed Shuffle as a Service
Zeus: Uber’s Highly Scalable and Distributed Shuffle as a ServiceZeus: Uber’s Highly Scalable and Distributed Shuffle as a Service
Zeus: Uber’s Highly Scalable and Distributed Shuffle as a ServiceDatabricks
 

What's hot (20)

Top 5 mistakes when writing Spark applications
Top 5 mistakes when writing Spark applicationsTop 5 mistakes when writing Spark applications
Top 5 mistakes when writing Spark applications
 
Advanced c programming in Linux
Advanced c programming in Linux Advanced c programming in Linux
Advanced c programming in Linux
 
L2 over l3 ecnaspsulations (english)
L2 over l3 ecnaspsulations (english)L2 over l3 ecnaspsulations (english)
L2 over l3 ecnaspsulations (english)
 
Apache spark
Apache sparkApache spark
Apache spark
 
Java troubleshooting thread dump
Java troubleshooting thread dumpJava troubleshooting thread dump
Java troubleshooting thread dump
 
Mmap failure analysis
Mmap failure analysisMmap failure analysis
Mmap failure analysis
 
Flash for Apache Spark Shuffle with Cosco
Flash for Apache Spark Shuffle with CoscoFlash for Apache Spark Shuffle with Cosco
Flash for Apache Spark Shuffle with Cosco
 
Linux Kernel vs DPDK: HTTP Performance Showdown
Linux Kernel vs DPDK: HTTP Performance ShowdownLinux Kernel vs DPDK: HTTP Performance Showdown
Linux Kernel vs DPDK: HTTP Performance Showdown
 
Introduction to DPDK
Introduction to DPDKIntroduction to DPDK
Introduction to DPDK
 
Introducing DataFrames in Spark for Large Scale Data Science
Introducing DataFrames in Spark for Large Scale Data ScienceIntroducing DataFrames in Spark for Large Scale Data Science
Introducing DataFrames in Spark for Large Scale Data Science
 
Kamailio - SIP Routing in Lua
Kamailio - SIP Routing in LuaKamailio - SIP Routing in Lua
Kamailio - SIP Routing in Lua
 
High-speed Database Throughput Using Apache Arrow Flight SQL
High-speed Database Throughput Using Apache Arrow Flight SQLHigh-speed Database Throughput Using Apache Arrow Flight SQL
High-speed Database Throughput Using Apache Arrow Flight SQL
 
01 ip oc180 e1_1 zxr10 m6000_t8000 basic operation (v1.00.20)
01 ip oc180 e1_1 zxr10 m6000_t8000 basic operation (v1.00.20)01 ip oc180 e1_1 zxr10 m6000_t8000 basic operation (v1.00.20)
01 ip oc180 e1_1 zxr10 m6000_t8000 basic operation (v1.00.20)
 
nftables - the evolution of Linux Firewall
nftables - the evolution of Linux Firewallnftables - the evolution of Linux Firewall
nftables - the evolution of Linux Firewall
 
Core Banking System on Apache Kafka
Core Banking System on Apache KafkaCore Banking System on Apache Kafka
Core Banking System on Apache Kafka
 
Using eBPF for High-Performance Networking in Cilium
Using eBPF for High-Performance Networking in CiliumUsing eBPF for High-Performance Networking in Cilium
Using eBPF for High-Performance Networking in Cilium
 
Kernel Recipes 2017 - 20 years of Linux Virtual Memory - Andrea Arcangeli
Kernel Recipes 2017 - 20 years of Linux Virtual Memory - Andrea ArcangeliKernel Recipes 2017 - 20 years of Linux Virtual Memory - Andrea Arcangeli
Kernel Recipes 2017 - 20 years of Linux Virtual Memory - Andrea Arcangeli
 
PostgreSQL Streaming Replication Cheatsheet
PostgreSQL Streaming Replication CheatsheetPostgreSQL Streaming Replication Cheatsheet
PostgreSQL Streaming Replication Cheatsheet
 
How to build a virtual machine
How to build a virtual machineHow to build a virtual machine
How to build a virtual machine
 
Zeus: Uber’s Highly Scalable and Distributed Shuffle as a Service
Zeus: Uber’s Highly Scalable and Distributed Shuffle as a ServiceZeus: Uber’s Highly Scalable and Distributed Shuffle as a Service
Zeus: Uber’s Highly Scalable and Distributed Shuffle as a Service
 

Similar to Building a powerful double entry accounting system

Accounting for Non-Accountants
Accounting for Non-AccountantsAccounting for Non-Accountants
Accounting for Non-AccountantsHelen Weeber
 
Sap business-one-down-payment-invoices-setup-and-processing
Sap business-one-down-payment-invoices-setup-and-processingSap business-one-down-payment-invoices-setup-and-processing
Sap business-one-down-payment-invoices-setup-and-processingKeith Taylor
 
Accounting & finance bankers
Accounting & finance  bankersAccounting & finance  bankers
Accounting & finance bankersBabasab Patil
 
Fa term paper sanmeet dhokay - 2015 pgpmx025
Fa term paper   sanmeet dhokay - 2015 pgpmx025Fa term paper   sanmeet dhokay - 2015 pgpmx025
Fa term paper sanmeet dhokay - 2015 pgpmx025Sanmeet Dhokay
 
Accounting and finance ppt @ bec doms bagalkot mba finance
Accounting and finance  ppt @ bec doms bagalkot mba financeAccounting and finance  ppt @ bec doms bagalkot mba finance
Accounting and finance ppt @ bec doms bagalkot mba financeBabasab Patil
 
working capital
working capitalworking capital
working capitalparag vora
 
A C C O U N T I N G L A K S H A N
A C C O U N T I N G  L A K S H A NA C C O U N T I N G  L A K S H A N
A C C O U N T I N G L A K S H A NLakshan Cooray
 
A C C O U N T I N G L A K S H A N
A C C O U N T I N G  L A K S H A NA C C O U N T I N G  L A K S H A N
A C C O U N T I N G L A K S H A NLakshan Cooray
 
A C C O U N T I N G L A K S H A N
A C C O U N T I N G  L A K S H A NA C C O U N T I N G  L A K S H A N
A C C O U N T I N G L A K S H A NLakshan Cooray
 
Accounting_Accruals_and_Deferrals_ppt.pdf
Accounting_Accruals_and_Deferrals_ppt.pdfAccounting_Accruals_and_Deferrals_ppt.pdf
Accounting_Accruals_and_Deferrals_ppt.pdfMaiSaleh20
 
Inventory acount group
Inventory acount groupInventory acount group
Inventory acount groupBabulu Dasari
 
Sh. aseem sir (workshop of financial managment held on 20 27.03.2013)
Sh. aseem sir (workshop of financial managment held on 20 27.03.2013)Sh. aseem sir (workshop of financial managment held on 20 27.03.2013)
Sh. aseem sir (workshop of financial managment held on 20 27.03.2013)Mukut Deori
 
Billing Process
Billing ProcessBilling Process
Billing Processonearbaein
 
Finance-Presentation-CRP1.pdf
Finance-Presentation-CRP1.pdfFinance-Presentation-CRP1.pdf
Finance-Presentation-CRP1.pdfPrasoonMohanty1
 

Similar to Building a powerful double entry accounting system (20)

Accounting for Non-Accountants
Accounting for Non-AccountantsAccounting for Non-Accountants
Accounting for Non-Accountants
 
Sap business-one-down-payment-invoices-setup-and-processing
Sap business-one-down-payment-invoices-setup-and-processingSap business-one-down-payment-invoices-setup-and-processing
Sap business-one-down-payment-invoices-setup-and-processing
 
Accounting & finance bankers
Accounting & finance  bankersAccounting & finance  bankers
Accounting & finance bankers
 
Fa term paper sanmeet dhokay - 2015 pgpmx025
Fa term paper   sanmeet dhokay - 2015 pgpmx025Fa term paper   sanmeet dhokay - 2015 pgpmx025
Fa term paper sanmeet dhokay - 2015 pgpmx025
 
Accounting and finance ppt @ bec doms bagalkot mba finance
Accounting and finance  ppt @ bec doms bagalkot mba financeAccounting and finance  ppt @ bec doms bagalkot mba finance
Accounting and finance ppt @ bec doms bagalkot mba finance
 
working capital
working capitalworking capital
working capital
 
Finance for bankers
Finance for bankersFinance for bankers
Finance for bankers
 
Chap020
Chap020Chap020
Chap020
 
Accounting lakshan
Accounting lakshanAccounting lakshan
Accounting lakshan
 
A C C O U N T I N G L A K S H A N
A C C O U N T I N G  L A K S H A NA C C O U N T I N G  L A K S H A N
A C C O U N T I N G L A K S H A N
 
A C C O U N T I N G L A K S H A N
A C C O U N T I N G  L A K S H A NA C C O U N T I N G  L A K S H A N
A C C O U N T I N G L A K S H A N
 
A C C O U N T I N G L A K S H A N
A C C O U N T I N G  L A K S H A NA C C O U N T I N G  L A K S H A N
A C C O U N T I N G L A K S H A N
 
SAP ERP Structure
SAP ERP StructureSAP ERP Structure
SAP ERP Structure
 
Accounting_Accruals_and_Deferrals_ppt.pdf
Accounting_Accruals_and_Deferrals_ppt.pdfAccounting_Accruals_and_Deferrals_ppt.pdf
Accounting_Accruals_and_Deferrals_ppt.pdf
 
Inventory acount group
Inventory acount groupInventory acount group
Inventory acount group
 
Sh. aseem sir (workshop of financial managment held on 20 27.03.2013)
Sh. aseem sir (workshop of financial managment held on 20 27.03.2013)Sh. aseem sir (workshop of financial managment held on 20 27.03.2013)
Sh. aseem sir (workshop of financial managment held on 20 27.03.2013)
 
Billing Process
Billing ProcessBilling Process
Billing Process
 
Finance-Presentation-CRP1.pdf
Finance-Presentation-CRP1.pdfFinance-Presentation-CRP1.pdf
Finance-Presentation-CRP1.pdf
 
Language of business
Language of businessLanguage of business
Language of business
 
My Portfolio
My PortfolioMy Portfolio
My Portfolio
 

More from Lucas Cavalcanti dos Santos

More from Lucas Cavalcanti dos Santos (6)

Arquitetando uma instituição financeira moderna
Arquitetando uma instituição financeira modernaArquitetando uma instituição financeira moderna
Arquitetando uma instituição financeira moderna
 
Arquitetura funcional em microservices, 4 anos depois
Arquitetura funcional em microservices, 4 anos depoisArquitetura funcional em microservices, 4 anos depois
Arquitetura funcional em microservices, 4 anos depois
 
Microservices in Clojure
Microservices in ClojureMicroservices in Clojure
Microservices in Clojure
 
Testando a integracao entre serviços - Agile Brazil 2014
Testando a integracao entre serviços - Agile Brazil 2014Testando a integracao entre serviços - Agile Brazil 2014
Testando a integracao entre serviços - Agile Brazil 2014
 
O poder da linguagem Ruby e as suas consequências
O poder da linguagem Ruby e as suas consequênciasO poder da linguagem Ruby e as suas consequências
O poder da linguagem Ruby e as suas consequências
 
Otimizacao prematura-agile-brazil-12
Otimizacao prematura-agile-brazil-12Otimizacao prematura-agile-brazil-12
Otimizacao prematura-agile-brazil-12
 

Recently uploaded

WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...masabamasaba
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...masabamasaba
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in sowetomasabamasaba
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...masabamasaba
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 

Recently uploaded (20)

Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 

Building a powerful double entry accounting system

  • 1. BUILDING A POWERFUL DOUBLE- ENTRY ACCOUNTING SYSTEM Lucas Cavalcanti
  • 3.
  • 4.
  • 5. USER BALANCES Future bills Open bill Due bill Available balance
  • 8. DEBIT CREDIT General Ledger USEFUL ABSTRACTIONS Income statement Cash flow statement Balance sheet LIABILITY ASSET EQUITY Debits Credits
  • 9. PROPERTY: on each movement Image © http://chestofbooks.com/business/reference/Home-Cyclopedia-Of-Business/Bill-Book.html
  • 10. Credits (CR): - $97 on liability payables (we will pay the merchant) - $3 Credit on P&L interchange (our profit) - $100 on off-balance asset current-limit EXAMPLE: A purchase of $100 Debits (DR): - $100 on asset settled (we will receive it from the customer) - $100 on off-balance liability current-limit-cp
  • 11. EXAMPLE: A payment of $100 Debits (DR): - $100 on asset cash (we received it from the customer) - $100 on off-balance asset current-limit Credits (CR): - $100 on asset settled (we paid the purchase) - $100 on off balance liability current-limit-cp
  • 12. DOUBLE ENTRY ACCOUNTING EVENTS TRIGGERING MOVEMENTS • purchases • payments • bills IMMUTABLE • append-only • entry log • can fix past by compensating INVARIANTS • movements sums to zero • a book-account balance is sum of credits and debits
  • 13. 1 MOVEMENT => N ENTRIES (s/defschema Entry {:entry/id s/Uuid
 :entry/amount PositiveAmount 
 :entry/debit-account BookAccount
 :entry/credit-account BookAccount
 :entry/post-date LocalDate
 :entry/movement Movement}) So by design, (ns double-entry.models.entry
 (:require [schema.core :as s]))
  • 14. 1 BUSINESS EVENT => 1 MOVEMENT + META e.g new-purchase, new-payment, new-bill (s/defschema Movement {:movement/id s/Uuid
 :movement/flow-id String
 :movement/topic Topic
 :movement/owner-account Account
 :movement/produced-at LocalDateTime
 :movement/consumed-at LocalDateTime
 :movement/user String}) (s/defschema Meta {:meta/id s/Uuid
 :meta/movement Movement
 :meta/entity (s/either Payment Purchase Bill ...)})
  • 15. DECLARATIVE RULES FOR MOVEMENTS (ns common-schemata.wire) (s/defschema Purchase
 {:purchase {:id s/Uuid
 :merchant String
 :amount t-money/PositiveAmount :interchange t-money/PositiveAmount
 :time LocalDateTime
 …}}) (s/defschema Payment
 {:payment {:id s/Uuid
 :amount t-money/PositiveAmount
 :post-date LocalDate
 …}})
  • 16. DECLARATIVE RULES FOR MOVEMENTS (def new-purchase
 [{:entry/debit-account :book-account.asset/settled-brazil
 :entry/credit-account :book-account.liability/payable-brazil
 :entry/amount (comp :amount :purchase)
 :entry/post-date (comp time->date :time :purchase)} {:entry/debit-account :book-account.liability/payable-brazil
 :entry/credit-account :book-account.profit-and-loss/interchange-brazil
 :entry/amount (comp :interchange :purchase)
 :entry/post-date (comp time->date :time :purchase)} 
 {:entry/debit-account :book-account.liability/current-limit-counterparty
 :entry/credit-account :book-account.asset/current-limit
 :entry/amount (comp :amount :purchase)
 :entry/post-date (comp time->date :time :purchase)}])
  • 17. DECLARATIVE RULES FOR MOVEMENTS (def new-payment
 [{:entry/debit-account :book-account.asset/transitory-bank
 :entry/credit-account :book-account.asset/settled-brazil
 :entry/amount (comp :amount :payment)
 :entry/post-date (comp :post-date :payment)} 
 {:entry/debit-account :book-account.asset/current-limit
 :entry/credit-account :book-account.liability/current-limit-counterparty
 :entry/amount (comp :amount :payment)
 :entry/post-date (comp :post-date :purchase)}])
  • 18. [{:entry/id (uuid)
 :entry/amount 100.0M
 :entry/debit-account :book-account.asset/settled-brazil
 :entry/credit-account :book-account.liability/payable-brazil
 :entry/post-date #nu/date "2016-12-01"
 :entry/movement new-purchase} 
 {:entry/id (uuid)
 :entry/amount 3.0M
 :entry/debit-account :book-account.liability/payable-brazil
 :entry/credit-account :book-account.profit-and-loss/interchange-brazil
 :entry/post-date #nu/date "2016-12-01"
 :entry/movement new-purchase} {:entry/id (uuid)
 :entry/amount 100.0M
 :entry/debit-account :book-account.liability/current-limit-counterparty
 :entry/credit-account :book-account.asset/current-limit
 :entry/post-date #nu/date "2016-12-01"
 :entry/movement new-purchase}] {:purchase
 {:id (uuid)
 :amount 100.0M
 :interchange 3.0M
 :time #nu/time "2016-12-01T13:37:42Z"}} Rulebook
  • 19. [{:entry/id (uuid)
 :entry/amount 100.0M
 :entry/debit-account :book-account.asset/transitory-bank
 :entry/credit-account :book-account.asset/settled-brazil
 :entry/post-date #nu/date "2016-12-01"
 :entry/movement new-payment} {:entry/id (uuid)
 :entry/amount 100.0M
 :entry/debit-account :book-account.asset/current-limit
 :entry/credit-account :book-account.liability/current-limit-counterparty
 :entry/post-date #nu/date "2016-12-01"
 :entry/movement new-payment}] {:payment
 {:id (uuid)
 :amount 100.0M
 :post-date #nu/date "2016-12-01"}} Rulebook
  • 20. Cumulative cache (balance sheet) Event (log) 2 LOGS AND A CACHE ACTUAL TIME audit trail / Datomic log “when did we know”day 0 day 30 day 90 SYSTEM OF RECORD TIME official version of events uses business-relevant “post dates” can correct after the fact day 90 day 0day 0 day 30
  • 21. SANITY CHECKS / BUSINESS INVARIANTS • Balances must be always positive or always negative • Cannot have a “late” balance there is a “prepaid” balance • A purchase should “move” exactly the purchase amount on assets and on current limit
  • 22. (def balances-property (prop/for-all [account (g/generator Account)
 events (gen/vector (gen/one-of [(g/generator Purchase)
 (g/generator Payment)
 ...]))]
 (->> (empty-db)
 (save-all! account events)
 :db-after
 (balances-are-positive!))) (fact (tc/quick-check 50 balances-property) => (th/embeds {:result true})) GENERATIVE TESTING (ns double-entry.controllers.rulebook-test
 (:require [midje.sweet :refer :all] [clojure.test.check.properties :as prop]
 [clojure.test.check :as tc]
 [schema-generators.generators :as g]
 [clojure.test.check.generators :as gen]))
  • 23. EVENT STREAM FOR A SINGLE CUSTOMER
  • 24. 1. Business events generate idempotent Kafka messages 2. For each event, apply functions to convert the event data into a movement with 1+ entries • Movements balance by design • Movements associate provenance metadata 3. Pre-check guarantees invariants against db value 4. Eagerly cache resulting balances debit-account credit-account amount a/max-limit a/current-limit l/max-limit-cp l/current-limit-cp initial-limit 15000.00 15000.00 CARD ISSUED
  • 25. debit-account credit-account amount new-purchase / settle-brazil 100.00 100.00 100.00 100.00 CARD ISSUED FIRST PURCHASE l/current-limit-cp a/unsettled l/unsettled-cp a/settled-brazil a/current-limit l/unsettled-cp a/unsettled l/payable-brazil
  • 26. debit-account credit-account amount closed-bill 15.00 100.00 CARD ISSUED FIRST PURCHASE a/minimum-payment a/closed l/minimum-payment-cp a/settled-brazil FIRST BILL CLOSES
  • 27. debit-account credit-account amount new-payment 10.00 10.00 10.00 CARD ISSUED FIRST PURCHASE a/current-limit l/minimum-payment-cp a/transitory-bank l/current-limit-cp a/minimum-payment a/late FIRST BILL CLOSES PARTIAL PAYMENT
  • 28. debit-account credit-account amount new-adjustment 7.00 7.00 CARD ISSUED FIRST PURCHASE l/current-limit-cp a/settled-financed a/current-limit e/revolving-interest FIRST BILL CLOSES PARTIAL PAYMENT INTEREST ASSESSED
  • 29. debit-account credit-account amount closed-bill 7.00 5.00 14.55 7.00 90.00 5.00 7.00 90.00 7.00 7.00 7.00 2.55 7.00 CARD ISSUED FIRST PURCHASE a/late l/minimum-payment-cp a/minimum-payment a/closed a/current-limit l/minimum-payment-cp a/transitory-bank a/transitory-bank l/prepaid a/current-limit l/minimum-payment-cp l/minimum-payment-cp a/closed a/closed a/minimum-payment l/minimum-payment-cp a/settled-financed l/current-limit-cp a/minimum-payment l/prepaid a/late a/closed l/current-limit-cp a/minimum-payment a/minimum-payment a/late FIRST BILL CLOSES PARTIAL PAYMENT INTEREST ASSESSED PAYMENT IN FULL
  • 30. ZOOMING OUT 2015-01 2015-04 2015-07 2015-10 2015-01 2016-03
  • 31. DETECTING OPERATIONAL MISTAKES USE CASES MANAGEMENT ACCOUNTING • delinquency tables by cohort and aging • receivables (domestic, foreign, financed) • revenue per customer (interchange, interest, fx spread) REPORTING • covenants • regulatory FINANCIAL ACCOUNTING • consolidate to ERP
  • 32. Declarative rules are extensible for additional financial products (e.g., already extending to rewards, debt financing) Financial analysis applies at a micro level (negative balances, weird ratios, operational problems) Business-specific invariants provide safety (declare mutually exclusive and impossible states,alert unexpected situations) Generative testing finds real bugs Service is shardable by customer account (no interactions between accounts) WHAT DO WE LIKE?
  • 33. 33 IF YOU ARE ENTRUSTED WITH A CUSTOMER’S FINANCIAL RELATIONSHIP, CONSIDER BUILDING A DOUBLE-ENTRY SYSTEM FOR YOUR DOMAIN
  • 34. Thank you! Lucas Cavalcanti @lucascs IF YOU CHOOSE TO DO SO, USE ALL THE POWER FUNCTIONAL PROGRAMMING GIVES YOU