luca

package module
v0.0.0-...-b62973b Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 24, 2025 License: MIT Imports: 12 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

luca

This is a plain text go library to manipulate and record accounting journal entries. It inherits ideas from [Luca Pacioli translated by Geijsbeek][pacioli], [Martin Blais' Beancount][beancount] and a lot from [Kobetic's coin][coin].

beancount coin pacioli

Digital representations

There will be three representations of the data which will be supported:

  • A plain text account format (storage only)
  • An in memory version for fast transformation
  • A database format for larger scale
Plain text form .luca

This is a storage format and will be transformed to the in memory or database form for conversion.

Using Beancount as a reference there are a number of changes:

  1. Support for nanosecond based ordering of events
  2. Support for bitemporal functions which will be used to support a knowledge date
  3. Suport for digital twins for comparing two similar journal books.
In memory form

Operations will be defined on this:

  • Read from text and Db forms
  • creating balances at time X knowledge date y
  • reporting data eg P&L for a period

Differences from Coin

  • Different dateformats
  • Addition of Knowledge date
  • Uses commodity movements as core item rather than posting entries
  • Uses alecthomas/participle/ as parser rather than own version
  • Seperates Text representation models from core accounts model, Ledger or a Pacioloi had Quaderno

Knowledge date

This is used as the date the book keeper is aware of the information. you might also refer date as "value date" and Knowledge date as "insertion date". For accountants preparing books of accounts it allows them to say that as of date X we were told the accounts were Y but with new information on date P the accounts are now Q.

Journal Documents and Ledger

I am going to use ledger for the complete set of accounts. There are other meanings but this seems to be closest to historical meaning.

Journals can also be calculated on different basis eg models which can be much more compact, eg recurring entries.

The documents are defined as the collection of text files and we can parse into them and out. The books is an internal representation of the accunts which is built from the journals.

EBNF definition of text format

Using the language of Martin Blais Beancount https://beancount.github.io/docs/beancount_language_syntax.html#syntax-overview

Currently it is a lot simplified:

  • no option entries
  • no balance postings

Luca document its own usage. Note it has a more relaxed input format and a more precise output format. So for instance files can be input any order but will be saved in sorted order.
Open directives allow a default commodity but when saved it will be specified. The following is the output of the luca ebnf output:


Grammar:
Document = Entry* .
Entry = <comment>* <date> <knowledgedate>? (Transaction | Account | Commodity | GenericEntry) .
Transaction = ("txn" | "*") <string>? ("INDENT" Movement+ "DEDENT")? .
Movement = <ident> <number> <arrow> <ident> .
Account = "open" <ident> <ident>? ("INDENT" AccountDetail "DEDENT")? .
AccountDetail = ("description" <string>)? .
Commodity = "commodity" <ident> ("INDENT" CommodityDetail "DEDENT")? .
CommodityDetail = ("description" <string>)? ("subunit" <number>)? .
GenericEntry = "generic" <string>? <comment>? ("INDENT" SubDirective+ "DEDENT")? .
SubDirective = <string> .

Notes: For directives apart from transactions full_date is assumed at the start of the day, and for transactions one microsecond before the end of the day. Directives names are lower case.

The resolution of datetime is assumed to be 1 microsecond. Note that different versions might implement it with different resolutions to squeeze the amount of storage. Eg the default datetime uses Unix Epoch timestamps

Implementation details

Pacioli has 4 types of records which are used to hold the accounting data:

  • Inventory of goods and money
  • Day notebooks, voluminous contemporaneous diaries
  • Journal entries. In chonological order with notes (cross referenced to the ledger)
  • Ledgers Summary of activity by account

With a computer we are going to focus on the journal. The cross referencing and ledger balances can be produced by computation.

  • Commodity
  • Account
  • Transaction
  • Balance

The core concept is to take Pacioli's books and conentate on the journal entries. In order for this to be complete you need to be able to extne

There are a number of domains:

  • parsing
    • Serialisation to and from text
  • Core manipulation
  • Balance query functions
Serialisation
  • internal/datetime: Support LucaDateTimeString
  • directiveHeader: Generic directive header
Core
  • directive: interface
  • journal: list of entries
  • directives
    • commodity
    • account
    • transaction
    • balance
Road map
gantt
    title Luca Roadmap
    dateFormat  YYYY-MM-DD

    section Timelines
    Phase 0 Live         :t1,  2025-02-06, 6M
    Phase 1 Enhance reporting     :t2,  after t1, 6M

    section Phase 0 Live
    Text serialisation    : done, a1, 2025-02-06, 6w
    Single file ingestion and saving : a11, after a1, 1w
    Multiple file ingestion and saving : a12, after a11, 1w
    Balance reporting : a13, after a12, 1w
    AFP sample : a14, after a13, 1w
    Ofx Ingestion         :active, a2, after a14, 1M
    Plain reporting       :a3, after a2, 1M
    Web reporting         :a4, after a3, 1M
    Useful                :milestone, a5, after a4, 1d
    Sql query language    :a6, after a5, 1M

Features

The software architecture of Luca looks like this:

graph TB
    subgraph CLI["cmd/luca"]
        CLI_MAIN["main.go"]
        AFP["afp.go"]
        TEMPLATES["templates/"]
    end

    subgraph Core["github.com/drummonds/luca"]
        LEDGER["Ledger"]
        SUMMARY["summary.go"]
        ACCOUNT["Account"]
        TRANSACTION["Transaction"]
        MOVEMENT["Movement"]
    end

    subgraph Internal["internal/"]
        PARSER["parser/"]
        MERMAID["mermaid/"]
        DATETIME["datetime/"]
    end

    %% Relationships
    CLI_MAIN --> AFP
    AFP --> TEMPLATES
    AFP --> LEDGER
    AFP --> PARSER
    
    LEDGER --> SUMMARY
    SUMMARY --> MERMAID
    LEDGER --> ACCOUNT
    LEDGER --> TRANSACTION
    TRANSACTION --> MOVEMENT
    
    PARSER --> LEDGER
    PARSER --> DATETIME

    %% Styling
    classDef default fill:#f9f9f9,stroke:#333,stroke-width:2px;
    classDef core fill:#BCE,stroke:#333,stroke-width:2px;
    classDef cli fill:#CDA,stroke:#333,stroke-width:2px;
    classDef internal fill:#EEB,stroke:#333,stroke-width:2px;
    
    class CLI_MAIN,AFP,TEMPLATES cli;
    class LEDGER,SUMMARY,ACCOUNT,TRANSACTION,MOVEMENT core;
    class PARSER,MERMAID,DATETIME internal;

List of features that will get implmented

Directive Account
Commodity
  • Make sure default commodity is defined either explicitly or implicitly
  • Save file format use explicit commodity although input format

Allow list rather than single commodity/currency. This will generate multiple account for each commodity.
Worked example with Swedish Ore and Canadian dollar.

Sub unit clean up

Spring decimal uses nice rounding system and we should use this rather than subunit.

Ideas

Segmenting time

Segmenting by time period. This allows you to deal with all the data for a period in memory as well as handling longer time periods.

indexing account movements

It might be worth testing keeping all movements just as a slice and iterating through them for balances of different types.

There may be an interactiong with periods and having old immutable periods.

Appendix

References

date time format comes from https://www.rfc-editor.org/rfc/rfc3339

String concatenation

You could use either + or stringbuilder. This article https://dev.to/jonathanlawhh/golang-string-concatenation-what-how-why-3fcd shows that for adding 2 strings both methods are fast but

  • is twice as fast. However by the time you get to 10 strings stringbuilder is twice as fast.

So using "\t" + test.data + "/n" is clear and good practice but not much longer.

colophon

This is third version of luca. The first was a python sqlite implementation, the second a more generic Python version and this a go implmention of a plain text accounting format,

I have read Luca Paciolo's book in translation and think it is admirably clear. I used to worry that he was taking credit from Benedeto Cotrugli who wrote earlier and was ppublished later. However Paciolo's book is so clear that I am happy to call this luca.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AccountNameToList

func AccountNameToList(name string) []string

func ProduceEntries

func ProduceEntries(fs afero.Fs, filename string, entryChan chan<- Entry) error

ProduceEntries reads a journal file and sends entries through the provided channel. It skips empty lines and adds comments to the entry. It handles comments both for whole lines and for directives and argumentss. The caller is responsible for closing the provided channel.

func ReadJournalEntries

func ReadJournalEntries(fs afero.Fs, filename string, handlers []EntryHandler) error

ReadJournalEntries reads entries from a journal file and processes them using the provided handlers

func SplitComment

func SplitComment(line string) (data, comment string)

func ValidateAccount

func ValidateAccount(account *parser.Account, ledger *Ledger) (*parser.Account, error)

Types

type Account

type Account struct {
	*parser.Account
	Ledger *Ledger
	// contains filtered or unexported fields
}

func NewAccount

func NewAccount(account *parser.Account, ledger *Ledger) (*Account, error)

func (*Account) BalanceLatest

func (a *Account) BalanceLatest() decimal.Decimal

func (*Account) LinkMovement

func (a *Account) LinkMovement(pm *parser.Movement, tx *parser.Transaction) error

func (*Account) SortMovements

func (a *Account) SortMovements()

type Directive

type Directive interface {
	GetValueDate() time.Time
	GetKnowledgeDate() *time.Time
	GetName() string
	GetExtraParams() string // parsing will be specific to each directive
	GetComment() string
}

type DirectiveHeader

type DirectiveHeader struct {
	ValueDate     time.Time
	KnowledgeDate *time.Time // nil if not present
	Name          string
	ExtraParams   string
	Comment       string
}

This just descibes the data in the directive line which is common to all directives The entry part has all the extra arguments

func NewDirectiveHeader

func NewDirectiveHeader(line string) (directive DirectiveHeader, err error)

Take a full line

func (DirectiveHeader) GetComment

func (dd DirectiveHeader) GetComment() string

func (DirectiveHeader) GetExtraParams

func (dd DirectiveHeader) GetExtraParams() string

func (DirectiveHeader) GetKnowledgeDate

func (dd DirectiveHeader) GetKnowledgeDate() *time.Time

func (DirectiveHeader) GetName

func (dd DirectiveHeader) GetName() string

func (DirectiveHeader) GetValueDate

func (dd DirectiveHeader) GetValueDate() time.Time

func (DirectiveHeader) String

func (d DirectiveHeader) String() string

Convert a simple directive to the first lines of the plain text Unit tested in commodity_test

type Entry

type Entry struct {
	Lines         []string // Original lines for backwards compatibility
	Comments      []string
	ThisDirective DirectiveHeader
	Arguments     []RawArgument
}

Entry represents a parsed journal entry

func NewEntry

func NewEntry() Entry

func (*Entry) HasDirective

func (e *Entry) HasDirective() bool

type EntryHandler

type EntryHandler interface {
	// HandleEntry attempts to process an entry. Returns true if the entry
	// was successfully handled, false if the entry was not recognized
	HandleEntry(Entry) bool
}

EntryHandler defines the interface for processing journal entries

type Ledger

type Ledger struct {
	// Raw data
	Commodities  []*parser.Commodity
	Accounts     []*Account
	Transactions []*parser.Transaction
	// Helper data  Names are case insensitive
	CommoditiesMap   map[string]*parser.Commodity
	AccountsMap      map[string]*Account
	DefaultCommodity *parser.Commodity
}

A Ledger is a working list of all entries. Whereas the document is a list of all the entries in a raw form

func NewLedger

func NewLedger() (*Ledger, error)

Given a directory read all the .luca files and return a Ledger

func NewLedgerFrom

func NewLedgerFrom(dir string, autoCreate bool) (*Ledger, error)

Given a directory read all the .luca files and return a Ledger

func NewLedgerFromFs

func NewLedgerFromFs(fs afero.Fs, dir string, autoCreate bool) (*Ledger, error)

NewLedgerFromFs creates a new ledger from files in the given directory using the provided filesystem

func (*Ledger) AddAccount

func (l *Ledger) AddAccount(pa *parser.Account, autoCreate bool) error

func (*Ledger) AddCommodity

func (l *Ledger) AddCommodity(c *parser.Commodity) error

func (*Ledger) AddDocument

func (l *Ledger) AddDocument(doc *parser.Document, filename string, autoCreate bool) error

Assume that all entires are now in the document so if in mutiple files they need to be merged or added in sequence Commodities --> Accounts --> Transactions

func (*Ledger) AddTransaction

func (l *Ledger) AddTransaction(t *parser.Transaction, autoCreate bool) error

func (*Ledger) CheckAccountName

func (l *Ledger) CheckAccountName(name string, autoCreate bool) (bool, error)

func (*Ledger) CheckCommoditySymbol

func (l *Ledger) CheckCommoditySymbol(symbol string, autoCreate bool) (bool, error)

CheckCommodity used when adding an account. This can auto create the commodity if it doesn't exist It is assumed that by this point that all the commodities have been added that have been specified. and supplies default values if meaningful in which case it returns true

func (*Ledger) LinkAccountsTransactions

func (l *Ledger) LinkAccountsTransactions()

func (*Ledger) MermaidSummary

func (l *Ledger) MermaidSummary() string

func (*Ledger) SetDefaultCommodity

func (l *Ledger) SetDefaultCommodity() error

SetDefaultCommodity checks for a single default commodity and sets it

type Movement

type Movement struct {
	parser.Movement
	// contains filtered or unexported fields
}

type RawArgument

type RawArgument struct {
	Value   string
	Comment string
}

Argument represents a parsed argument line from an entry

func NewRawArgument

func NewRawArgument(line string) (argument RawArgument, err error)

Directories

Path Synopsis
cmd
luca command
internal

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址