1 ;;;(ql:quickload "cl-store")
2 (ql:quickload "yason")
3 (ql:quickload "cl-ppcre")
4 (ql:quickload "unix-opts")
5 (ql:quickload "ironclad")
6 (ql:quickload "dexador")
7
8
9 ;;; All records exist in this data structure
10 ;;; nil on start and loaded in from file
11 ;;; *records* represents as hash of months,
12 ;;; where the key is the month stamp, eg 20210701
13 ;;; and the value is the monthly expenses hash
14 (defvar *records* (make-hash-table :test 'equalp))
15 (defvar *api-config-path* "./auth.json")
16 (defvar *api-url* NIL)
17 (defvar *api-key* NIL)
18
19 ;;; Used for input checking (mostly)
20 (defvar *old-month-line-regex* (ppcre:create-scanner "^([A-Z][a-z]{1,})[0-9]{4}$"))
21 (defvar *old-exp-line-regex* (ppcre:create-scanner "^([A-Z].*)\ -\ \\\$([0-9]{1,4}) - PAID"))
22 (defvar *new-month-line-regex* (ppcre:create-scanner "20[0-9]{4}"))
23
24 ;;; Taken from: https://gist.github.com/WetHat/a49e6f2140b401a190d45d31e052af8f
25 ;;; Used for pretty printing output
26 (defconstant +CELL-FORMATS+ '(:left "~vA"
27 :center "~v:@<~A~>"
28 :right "~v@A"))
29
30 (defun format-table (stream data &key (column-label (loop for i from 1 to (length (car data))
31 collect (format nil "COL~D" i)))
32 (column-align (loop for i from 1 to (length (car data))
33 collect :left)))
34 (let* ((col-count (length column-label))
35 (strtable (cons column-label ; table header
36 (loop for row in data ; table body with all cells as strings
37 collect (loop for cell in row
38 collect (if (stringp cell)
39 cell
40 ;else
41 (format nil "~A" cell))))))
42 (col-widths (loop with widths = (make-array col-count :initial-element 0)
43 for row in strtable
44 do (loop for cell in row
45 for i from 0
46 do (setf (aref widths i)
47 (max (aref widths i) (length cell))))
48 finally (return widths))))
49 ;------------------------------------------------------------------------------------
50 ; splice in the header separator
51 (setq strtable
52 (nconc (list (car strtable) ; table header
53 (loop for align in column-align ; generate separator
54 for width across col-widths
55 collect (case align
56 (:left (format nil ":~v@{~A~:*~}"
57 (1- width) "-"))
58 (:right (format nil "~v@{~A~:*~}:"
59 (1- width) "-"))
60 (:center (format nil ":~v@{~A~:*~}:"
61 (- width 2) "-")))))
62 (cdr strtable))) ; table body
63 ;------------------------------------------------------------------------------------
64 ; Generate the formatted table
65 (let ((row-fmt (format nil "| ~{~A~^ | ~} |~~%" ; compile the row format
66 (loop for align in column-align
67 collect (getf +CELL-FORMATS+ align))))
68 (widths (loop for w across col-widths collect w)))
69 ; write each line to the given stream
70 (dolist (row strtable)
71 (apply #'format stream row-fmt (mapcan #'list widths row))))))
72
73 ;;; Used by "print-month" arg to validate
74 ;;; the user provided a valid key
75 (defun check-month (month-key)
76 (if (stringp month-key) month-key
77 (return-from check-month NIL))
78 (if (ppcre:scan *old-month-line-regex* month-key) month-key
79 (if (ppcre:scan *new-month-line-regex* month-key) month-key
80 (return-from check-month NIL))))
81
82 ;; Called like: (add-month '202107)
83 (defun add-month (month-key)
84 (if (check-month month-key)
85 (if (not (gethash month-key *records*))
86 (progn
87 (setf (gethash month-key *records*)
88 (make-hash-table :test 'equalp))
89 month-key))))
90
91 (defun add-expense-to-month (expense value month)
92 (if (gethash month *records*)
93 (setf (gethash expense (gethash month *records*)) value)
94 (progn
95 (print (concatenate 'string "Adding" month))
96 (if (add-month month)
97 (setf (gethash expense (gethash month *records*)) value)
98 (print (concatenate 'string "Failed to add" month))))))
99
100 (opts:define-opts
101 (:name :help
102 :description "Print help text"
103 :short #\h
104 :long "help")
105 (:name :print-month
106 :description "Print records for given month. Must conform to either MonthYear or YYYYMM semantics."
107 :short #\p
108 :long "print-month"
109 :arg-parser #'check-month)
110 (:name :add-expense
111 :description "Non interactive interface for recording an expense. Expects expense name as an argument, and requires -v|--value and -m|month"
112 :short #\e
113 :long "add-expense"
114 :arg-parser #'identity)
115 (:name :value
116 :description "Used with -e|--add-expense. Must be an integer."
117 :short #\v
118 :long "value"
119 :arg-parser #'parse-integer)
120 (:name :month
121 :description "Used with -e|--add-expense. Must be a valid month key."
122 :short #\m
123 :long "month"
124 :arg-parser #'check-month)
125 (:name :interactive-mode
126 :description "Run in interactive mode"
127 :short #\i
128 :long "interactive"))
129
130 ;; See: https://github.com/libre-man/unix-opts/blob/master/example/example.lisp
131 (defmacro when-option ((options opt) &body body)
132 `(let ((it (getf ,options ,opt)))
133 (when it
134 ,@body)))
135
136 (defun reload ()
137 (load "~/Repos/fin-lisp/fin-lisp.lisp"))
138
139 (defun parse-api-config (path)
140 (let ((api-config-hash (yason:parse (uiop:read-file-string path)))
141 (ret-tuple '())) ; I think this probably can be done in the let binding
142 (push (gethash "token" api-config-hash) ret-tuple)
143 (push (gethash "url" api-config-hash) ret-tuple)
144 ret-tuple))
145
146 ;;;;;;;;;;;;;;;;;;;;;;;;
147 ;;; Encryption stuff ;;;
148 ;;;;;;;;;;;;;;;;;;;;;;;;
149 ;;; See: https://www.cliki.net/Ironclad
150
151 ;;; Return cipher when provided key
152 ;;; Currently, this is 'insecure' as we are using a string
153 ;;; coerced into a byte array as the key, aka a non-random secret.
154 ;;; Should use twofish
155 (defun get-cipher (key)
156 (ironclad:make-cipher
157 :blowfish
158 :mode :ecb
159 :key (ironclad:ascii-string-to-byte-array key)))
160
161 (defun encrypt-records (key)
162 (let* ((cipher (get-cipher key))
163 (content (ironclad:ascii-string-to-byte-array (with-output-to-string (json)
164 (yason:encode *records* json)))))
165 (ironclad:encrypt-in-place cipher content)
166 (write-to-string (ironclad:octets-to-integer content))))
167
168 (defun decrypt-records (key enc-record-string)
169 (let ((cipher (get-cipher key)))
170 (let ((content (ironclad:integer-to-octets (parse-integer enc-record-string))))
171 (ironclad:decrypt-in-place cipher content)
172 (coerce (mapcar #'code-char (coerce content 'list)) 'string))))
173
174 (defun download-records ()
175 (let* ((api-config (parse-api-config *api-config-path*))
176 (dl-records (yason:parse (dex:get (concatenate 'string (first api-config) "download")
177 :headers (list (cons "X-Token" (second api-config)))))))
178 dl-records))
179
180 (defun upload-records (enc-records-string)
181 (let* ((api-config (parse-api-config *api-config-path*))
182 (result (dex:post (concatenate 'string (first api-config) "upload")
183 :headers (list (cons "X-Token" (second api-config))
184 (cons "Content-Type" "application/json"))
185 :content (concatenate 'string "{\"content\": \"" enc-records-string "\"}"))))
186 result))
187
188 ;;; Serialization and communicating with the web API
189 (defun push-records (key)
190 "Upload records to remote server"
191 (upload-records (encrypt-records key)))
192
193 (defun get-records (key)
194 "Get records from remote server"
195 (setf *records* (yason:parse (decrypt-records key (gethash "content" (download-records))))))
196
197 ;;; Taken from practical common lisp
198 (defun prompt-read (prompt)
199 (format *query-io* "~a: " prompt)
200 (force-output *query-io*)
201 (read-line *query-io*))
202
203 (defun prompt-for-expense ()
204 (list
205 (prompt-read "Enter expense name")
206 (parse-integer
207 (prompt-read "Enter expense value"))))
208
209 ;;; Given key for *records* hash,
210 ;;; print expenses/values for month
211 (defun dump-month (month-key)
212 (let ((month-hash)
213 (exp-keys))
214 (setf month-hash (gethash month-key *records*))
215 (setf exp-keys (loop for key being the hash-keys of month-hash collect key))
216 (format t "~C" #\linefeed)
217 (format t "~a~C" month-key #\linefeed)
218 (dolist (exp-key exp-keys)
219 (format t "~a : ~a~C" exp-key (gethash exp-key month-hash) #\linefeed))
220 (format t "~C" #\linefeed)))
221
222 ;;; Given key for *records* hash,
223 ;;; print expenses/values for month
224 (defun dump-month-table (month-key)
225 (let* ((month-hash (gethash month-key *records*))
226 (exp-keys (loop for key being the hash-keys of month-hash collect key))
227 (flist))
228 (dolist (exp-key exp-keys)
229 (setq flist (append flist (list (list exp-key (gethash exp-key month-hash))))))
230 (format-table T flist :column-label '("Expense" "Amount"))))
231
232
233 ;;; Dump all records.
234 (defun dump-records ()
235 (let ((record-key-list (loop for key being the hash-keys of *records* collect key)))
236 (dolist (month-key record-key-list) (dump-month month-key))))
237
238 (defmacro generic-handler (form error-string)
239 `(handler-case ,form
240 (error (e)
241 (format t "Invalid input: ~a ~%" ,error-string)
242 (values 0 e))))
243
244 ;; Util screen clearer
245 (defun cls()
246 (format t "~A[H~@*~A[J" #\escape))
247
248 (defun interactive-mode ()
249 (format t "~%")
250 (format t "Available options:~%")
251 (format t "1. Enter expense~%")
252 (format t "2. Display month~%")
253 (format t "3. Push records~%")
254 (format t "4. Get records~%")
255 (format t "5. Quit~%")
256 (let
257 ((answer (prompt-read "Select an option")))
258 (if (string= answer "1")
259 (generic-handler
260 (let ((month-input (prompt-read "Enter month"))
261 (expense-input (prompt-for-expense)))
262 (add-expense-to-month (first expense-input)
263 (second expense-input)
264 month-input))
265 "Invalid Input"))
266 (if (string= answer "2")
267 (generic-handler
268 (dump-month-table (prompt-read "Enter month"))
269 "Invalid month"))
270 (if (string= answer "3")
271 (generic-handler
272 (push-records (prompt-read "Enter encryption key"))
273 "Serialization error or invalid filename"))
274 (if (string= answer "4")
275 (generic-handler
276 (get-records (prompt-read "Enter decryption key"))
277 "Deserialization error or invalid filename"))
278 (if (string= answer "5")
279 (return-from interactive-mode nil)))
280 (interactive-mode))
281
282 (defun display-help ()
283 (opts:describe
284 :prefix "fin-lisp.lisp - Basic expense tracker in lisp"
285 :usage-of "fin-lisp.lisp"
286 :args "[FREE-ARGS]")
287 (quit))
288
289 ;; Entry point
290 (defun main ()
291 (if (= 1 (length sb-ext:*posix-argv*)) (interactive-mode))
292 (let ((matches (opts:get-opts)))
293 ;;(format t "~a ~%" matches)
294 (when-option (matches :help)
295 (display-help))
296 (when-option (matches :print-month)
297 (let ((key (prompt-read "Enter decryption key"))
298 (month-key (destructuring-bind (&key print-month) matches
299 print-month)))
300 (get-records key)
301 (dump-month-table month-key)
302 (quit)))
303 (when-option (matches :add-expense) ;; This is probably the wrong way to resolve the arguments
304 (when-option (matches :value)
305 (when-option (matches :month)
306 (let ((key (prompt-read "Enter decryption key"))
307 (name-value-month (destructuring-bind (&key add-expense value month) matches
308 (list add-expense value month))))
309 (get-records key)
310 (if (add-expense-to-month
311 (first name-value-month)
312 (second name-value-month)
313 (third name-value-month))
314 (push-records key)
315 (print "Invalid month input"))))))
316 (when-option (matches :interactive-mode)
317 (progn
318 (interactive-mode)
319 (quit)))))
320
321 ;;; Can only be called from the REPL,
322 ;;; used for importing according to the old schema
323 (defun import-records (filename)
324 (let ((old-file-lines
325 (with-open-file (stream filename)
326 (loop for line = (read-line stream nil)
327 while line
328 collect line)))
329 (cur-mon)
330 (cur-exp))
331 (loop for line in old-file-lines
332 do (progn
333 (if (ppcre:scan *old-month-line-regex* line) (setf cur-mon line))
334 (if (ppcre:scan *old-exp-line-regex* line)
335 (progn
336 (setf cur-exp (ppcre:register-groups-bind (first second) (*old-exp-line-regex* line) :sharedp t (list first second)))
337 (print cur-exp)
338 (if (gethash cur-mon *records*)
339 (let ((innerhash (gethash cur-mon *records*)))
340 (setf (gethash (first cur-exp) innerhash) (second cur-exp))))
341 (if (not (gethash cur-mon *records*))
342 (progn
343 (add-month cur-mon)
344 (let ((innerhash (gethash cur-mon *records*)))
345 (setf (gethash (first cur-exp) innerhash) (second cur-exp)))))))))))
346
347 (defun reset-records ()
348 "Used for debugging, just resets the *records* hash to NIL"
349 (setf *records* (make-hash-table :test 'equal)))