aboutsummaryrefslogtreecommitdiff
path: root/quickLedger.sh
blob: 88f410f21f35248f866ce87bef31542b2e30e61c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#!/bin/sh

# quickLedger.sh: Quickly create a new entry for ledger
#
# Usage: quickLedger.sh [-t] [-f LEDGER_FILE] [-r REMOTE_LEDGER_FILE] [-c CURRENCY_SYMBOL]

usageMessage='Usage: quickLedger.sh [-d] [-f LEDGER_FILE] [-r REMOTE_LEDGER_FILE] [-c CURRENCY_SYMBOL]'

ledgerFile="$LEDGER_FILE"
remoteLedgerFile="$REMOTE_LEDGER_FILE"
currencySymbol='€'
debug=''

# $1: message
# $2: exit code
fatalError() {
	printf "Error: $1" 1>&2
	exit "$2"
}

organizeLines() {
	sort | uniq -c | sort -nr | sed 's/^\s*[0-9]* //'
}

getPayee() {
	grep '^\w' "$ledgerFile" | cut -d' ' -f2- | organizeLines | fzf --prompt 'Payee: '
}

# $1: fzf prompt
getAccount() {
	grep '^\s' "$ledgerFile" | awk '{print $1}' | organizeLines | fzf --prompt "$1" --no-clear
}

getComment() {
	grep -o ';.*$' "$ledgerFile" | organizeLines | fzf --prompt "Comment: "
}

getAmount() {
	read amount
	while ! echo "$amount" | grep -Eq '[0-9]+(\.[0-9][0-9])?'; do
		read amount
	done
	echo "$amount" | grep -Fq '.' || amount="${amount}.00"
	amount="${amount}${currencySymbol}"
	echo "$amount"
}

getTransaction() {
	printf '%s %s\n\t%s\t%s\t%s\n\t%s\n' "$date" "$payee" "$targetAccount" "$amount" "$comment" "$originAccount"
}

# Process options
while getopts ':tf:r:c:' opt; do
	case $opt in

		't' )
			debug='y' ;;

		'f' )
			ledgerFile="$OPTARG" ;;

		'r' )
			remoteLedgerFile="$OPTARG" ;;

		'c' )
			currencySymbol="$OPTARG" ;;

		'?' )
			printf "${usageMessage}\n"
			exit 1

	esac
done
shift $(($OPTIND - 1))

[ -z "$ledgerFile" ] &&
	fatalError 'No ledger file. Set ledger file as $LEDGER_FILE or with -f option.\n' 2
[ ! -f "$ledgerFile" ] && fatalError "No file [${ledgerFile}] found to use as ledger.\n" 3

targetAccount="$(getAccount 'Target account: ')"
[ -z "$targetAccount" ] && tput rmcup && exit 0
originAccount="$(getAccount 'Origin account: ')"
[ -z "$originAccount" ] && tput rmcup && exit 0

payee="$(getPayee)"

printf 'Amount: '
amount="$(getAmount)"
[ -z "$amount" ] && exit 0

comment="$(getComment)"

date="$(date '+%Y/%m/%d')"

getTransaction

printf 'Correct? [Yn]: '
read correct
[ "$correct" = "n" ] && exit 0

[ -n "$debug" ] && exit 0

echo >> "$ledgerFile"
getTransaction >> "$ledgerFile"
rsync -t "$ledgerFile" "$remoteLedgerFile" || fatalError 'rsync failed.' 4