pta-ledger.lisp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. (in-package #:pta-ledger)
  2. (defstruct amount quantity commodity)
  3. (defstruct posting
  4. status account amount unit-price total-price comment)
  5. (defstruct entry
  6. date secondary-date status code description comment postings)
  7. (defvar *default-year* nil "Initialized to current year on parsing start. Could be set with directive")
  8. (defvar *default-commodity* "RUB" "Could be set with directive")
  9. (defparameter +day+ (* 60 60 24) "day in seconds")
  10. (defun get-date (universal-time)
  11. (nreverse (subseq (multiple-value-list (decode-universal-time universal-time)) 3 6)))
  12. (defun get-ut (year month day)
  13. (encode-universal-time 0 0 0 day month year))
  14. (defun strip-space (text)
  15. (subseq text (or (position #\Space text :test-not 'eql) 0)
  16. (1+ (or (position #\Space text :test-not 'eql :from-end t) -1))))
  17. (defun .date-delimiter ()
  18. (.is #'member '(#\/ #\- #\.)))
  19. (defun .chars (&rest chars)
  20. (.is #'member chars))
  21. ;; optimized (.first (.map 'list parser at-least))
  22. (defun .while (parser &key result-type (at-least 1))
  23. (lambda (input)
  24. (loop
  25. for inp = input then (input-rest inp)
  26. for count from 0
  27. until (input-empty-p inp)
  28. while (funcall parser inp)
  29. finally (return (when (>= count at-least)
  30. (list (cons (when result-type
  31. (coerce (subseq input 0 count) result-type))
  32. inp)))))))
  33. (defun .until (parser &key result-type (at-least 1))
  34. (.while (.not parser) :result-type result-type :at-least at-least))
  35. (defun .mapcar* (parser &optional skip)
  36. (lambda (input)
  37. (loop
  38. with results
  39. until (input-empty-p input)
  40. for result = (run parser input)
  41. while result
  42. do
  43. (unless skip (push (caar result) results))
  44. (setf input (cdar result))
  45. finally (return (list (cons (unless skip (nreverse results)) input))))))
  46. (defun .list (&rest parsers)
  47. (if (not parsers)
  48. (.fail)
  49. (.let* ((first (first parsers))
  50. (rest (if (rest parsers)
  51. (apply #'.list (rest parsers))
  52. (.identity nil))))
  53. (.identity (cons first rest)))))
  54. (defun .number (&optional (at-least 1))
  55. (.let* ((digits (.while (.is #'digit-char-p) :result-type 'string :at-least at-least)))
  56. (.identity (parse-integer digits))))
  57. (defun .spaces (&key (at-least 1) result-type)
  58. (.while (.char= #\Space) :result-type result-type :at-least at-least))
  59. (defun .whitespace (&key (at-least 1) result-type)
  60. (.while (.chars #\Space #\Tab) :result-type result-type :at-least at-least))
  61. (defun .eol ()
  62. (.or (.char= #\Newline)
  63. (.and (.not (.item))
  64. (.identity '()))))
  65. (defun .line-comment ()
  66. (.let* ((_ (.whitespace :at-least 0))
  67. (_ (.chars #\; #\# #\*))
  68. (text (.until (.char= #\Newline) :at-least 0 :result-type 'string))
  69. (_ (.eol)))
  70. (.identity (strip-space text))))
  71. (defun .multi-line-comment ()
  72. (.let* ((_ (.string= "comment"))
  73. (text (.until (.progn (.eol) (.string= "end comment")) :result-type 'string))
  74. (_ (.optional (.progn (.eol) (.string= "end comment"))))
  75. (_ (.eol)))
  76. (.identity (strip-space text))))
  77. (defun .comment ()
  78. (.let* ((_ (.char= #\;))
  79. (text (.until (.char= #\Newline) :at-least 0 :result-type 'string)))
  80. (.identity (strip-space text))))
  81. (defun .empty-lines ()
  82. (.mapcar*
  83. (.or (.progn (.whitespace :at-least 0) (.eol))
  84. (.line-comment)
  85. (.multi-line-comment))
  86. t))
  87. (defun .simple-date (&optional default-year)
  88. (.let* ((year (.optional (.prog1 (.number 4) (.date-delimiter))))
  89. (month (.prog1 (.number) (.date-delimiter)))
  90. (day (.number)))
  91. (handler-case
  92. (.identity (get-ut (or year default-year *default-year*) month day))
  93. (error () (.fail)))))
  94. (defun .status ()
  95. (.is 'member '(#\! #\*)))
  96. (defun .code ()
  97. (.prog2 (.char= #\()
  98. (.until (.char= #\)) :result-type 'string :at-least 0)
  99. (.char= #\))))
  100. (defun .description ()
  101. (.let* ((text (.until (.chars #\Newline #\;) :result-type 'string)))
  102. (.identity (strip-space text))))
  103. (defun .account ()
  104. (.let* ((account (.until (.or (.string= " ")
  105. (.char= #\Newline)) :result-type 'string)))
  106. (.identity (strip-space account))))
  107. (defun .money-number (thousands-sep decimal-sep)
  108. (.let* ((first-part (.while (.is 'digit-char-p) :result-type 'string))
  109. (rest-parts (.mapcar* (.progn (.char= thousands-sep)
  110. (.while (.is 'digit-char-p) :result-type 'string))))
  111. (decimals (.optional (.progn (.char= decimal-sep)
  112. (.while (.is 'digit-char-p) :result-type 'list :at-least 0)))))
  113. ;; One thousands separator and no decimals - is other way around, fail for other to succeceed
  114. (if (and (= 1 (length rest-parts))
  115. (null decimals))
  116. (.fail)
  117. (.identity
  118. (+
  119. (parse-integer (apply 'concatenate 'string (cons first-part rest-parts)))
  120. (if decimals
  121. (* (parse-integer (coerce decimals 'string))
  122. (expt 10 (- (length decimals))))
  123. 0))))))
  124. (defun .money ()
  125. (.plus (.money-number #\, #\.)
  126. (.money-number #\. #\,)))
  127. (defun .commodity ()
  128. (.or (.until (.or (.chars #\. #\, #\Space #\" #\; #\Newline #\- #\+ #\@)
  129. (.is 'digit-char-p))
  130. :result-type 'string)
  131. (.prog2 (.char= #\")
  132. (.until (.char= #\") :result-type 'string)
  133. (.char= #\"))))
  134. (defun .amount ()
  135. (.or
  136. (.let* ((sign1 (.optional (.chars #\- #\+)))
  137. (commodity (.prog1 (.commodity) (.optional (.whitespace))))
  138. (sign2 (.optional (.chars #\- #\+)))
  139. (quantity (.money)))
  140. (if (and sign1 sign2)
  141. (.fail)
  142. (.identity
  143. (make-amount :quantity (if (or (equal sign1 #\-)
  144. (equal sign2 #\-))
  145. (- quantity)
  146. quantity)
  147. :commodity commodity))))
  148. (.let* ((sign (.optional (.chars #\- #\+)))
  149. (quantity (.money))
  150. (commodity (.optional (.progn (.optional (.whitespace))
  151. (.commodity)))))
  152. (.identity
  153. (make-amount :quantity (if (equal sign #\-)
  154. (- quantity)
  155. quantity)
  156. :commodity commodity)))))
  157. (defun .posting ()
  158. (.let* ((_ (.whitespace))
  159. (status (.optional (.prog1 (.status) (.optional (.spaces)))))
  160. (account (.account))
  161. (amount (.optional (.prog2 (.whitespace :at-least 2) (.amount) (.optional (.whitespace)))))
  162. (unit-price (.optional (.progn (.char= #\@)
  163. (.not (.char= #\@))
  164. (.optional (.whitespace))
  165. (.amount))))
  166. (_ (.optional (.whitespace)))
  167. (total-price (.optional (.progn (.string= "@@")
  168. (.optional (.whitespace))
  169. (.amount))))
  170. (_ (.optional (.whitespace)))
  171. (comment (.optional (.comment)))
  172. (_ (.eol))
  173. (comments (.mapcar* (.prog2 (.whitespace) (.comment) (.eol)))))
  174. (if (and unit-price total-price) (.fail)
  175. (.identity (make-posting
  176. :status status
  177. :account account
  178. :amount amount
  179. :unit-price unit-price
  180. :total-price total-price
  181. :comment (when (or comment comments)
  182. (format nil "~{~A~^~%~}" (remove nil (list* comment comments)))))))))
  183. (defun .entry ()
  184. (.let* ((date (.simple-date))
  185. (secondary-date (.optional (.progn (.char= #\=)
  186. (.simple-date (car (get-date date))))))
  187. (status (.optional (.progn (.spaces) (.status))))
  188. (code (.optional (.progn (.spaces) (.code))))
  189. (_ (.optional (.whitespace)))
  190. (description (.optional (.description)))
  191. (_ (.optional (.whitespace)))
  192. (comment (.optional (.comment)))
  193. (_ (.eol))
  194. (comments (.mapcar* (.prog2 (.whitespace) (.comment) (.eol))))
  195. (postings (.mapcar* (.posting))))
  196. (.identity (make-entry :date date
  197. :secondary-date secondary-date
  198. :status status
  199. :code code
  200. :description description
  201. :comment (when (or comment comments)
  202. (format nil "~{~A~^~%~}" (remove nil (list* comment comments))))
  203. :postings postings))))
  204. (defun .wrap (prefix parser)
  205. (.let* ((value parser))
  206. (.identity (cons prefix value))))
  207. (defun .journal ()
  208. (.prog1
  209. (.mapcar*
  210. (.progn
  211. (.empty-lines)
  212. (.or
  213. (.wrap :entry (.entry))
  214. (.prog1
  215. (.or
  216. (.wrap :market-price
  217. (.progn (.char= #\P)
  218. (.optional (.whitespace))
  219. (.let* ((date (.simple-date))
  220. (_ (.whitespace))
  221. (commodity (.commodity))
  222. (_ (.whitespace))
  223. (unit-price (.amount)))
  224. (.identity (list date commodity unit-price)))))
  225. (.wrap :commodity
  226. (.progn (.string= "commodity")
  227. (.whitespace)
  228. (.amount)))
  229. (.wrap :default-commodity
  230. (.progn (.char= #\D)
  231. (.optional (.whitespace))
  232. (.amount)))
  233. (.wrap :default-year
  234. (.progn (.char= #\Y)
  235. (.optional (.whitespace))
  236. (.number))))
  237. (.optional (.whitespace))
  238. (.eol)))))
  239. (.empty-lines)))
  240. (defun parse-journal (str)
  241. (let ((*default-year* (car (get-date (get-universal-time)))))
  242. (parse (.journal) str)))
  243. (defun .query-coloned (type key-parser value-parser)
  244. (.let* ((key key-parser)
  245. (_ (.char= #\:))
  246. (value value-parser))
  247. (.identity (cons type
  248. #'(lambda (entry posting)
  249. (let ((key-value (funcall key entry posting)))
  250. (or (eql key-value :t)
  251. (funcall value key-value))))))))
  252. (defun .query-entryp (prefix key)
  253. (.progn (.string= prefix) (.identity #'(lambda (e p) (declare (ignore p)) (funcall key e)))))
  254. (defun .query-postingp (prefix key)
  255. (.progn (.string= prefix) (.identity #'(lambda (e p) (declare (ignore e)) (funcall key p)))))
  256. (defun .query-value-regex ()
  257. (.let* ((regex (.until (.eol) :result-type 'string)))
  258. (handler-case
  259. (let ((matcher (cl-ppcre:create-scanner regex :case-insensitive-mode t)))
  260. (.identity #'(lambda (value)
  261. (cl-ppcre:scan matcher value))))
  262. (error ()
  263. (.fail)))))
  264. (defun .query-value-amount ()
  265. (.let* ((op (.or (.string= ">=")
  266. (.string= "<=")
  267. (.char= #\=)
  268. (.char= #\<)
  269. (.char= #\>)
  270. (.identity #\=)))
  271. (value (.number)))
  272. (.identity #'(lambda (v)
  273. (funcall (find-symbol (string op)) v value)))))
  274. (defun .month ()
  275. (.or (.progn (.or (.string= "january") (.string= "jan")) (.identity 1))
  276. (.progn (.or (.string= "february") (.string= "feb")) (.identity 2))
  277. (.progn (.or (.string= "march") (.string= "mar")) (.identity 3))
  278. (.progn (.or (.string= "april") (.string= "apr")) (.identity 4))
  279. (.progn (.string= "may") (.identity 5))
  280. (.progn (.or (.string= "june") (.string= "jun")) (.identity 6))
  281. (.progn (.or (.string= "july") (.string= "jul")) (.identity 7))
  282. (.progn (.or (.string= "august") (.string= "aug")) (.identity 8))
  283. (.progn (.or (.string= "september") (.string= "sep")) (.identity 9))
  284. (.progn (.or (.string= "october") (.string= "oct")) (.identity 10))
  285. (.progn (.or (.string= "november") (.string= "nov")) (.identity 11))
  286. (.progn (.or (.string= "december") (.string= "dec")) (.identity 12))))
  287. (defun week-start-date (universal-time &optional offset)
  288. (get-date (- universal-time (* +day+ (+ (nth 6 (multiple-value-list (decode-universal-time universal-time)))
  289. (- (* 7 (or offset 0))))))))
  290. (defun month-start-date (year month &optional offset)
  291. (multiple-value-bind (year-offset month) (floor (+ month (or offset 0) -1) 12)
  292. (list (+ year year-offset) (1+ month) 1)))
  293. (defun .smart-range (parser &optional duration)
  294. (.let* ((date parser))
  295. (destructuring-bind (&optional year month day) date
  296. (handler-case
  297. (let* ((ut (get-ut (or year (car (get-date (get-universal-time))))
  298. (or month 1) (or day 1)))
  299. (date (get-date ut)))
  300. (.identity (cons ut
  301. (if duration (+ ut duration)
  302. (if day (+ ut +day+)
  303. (if month (apply #'get-ut (month-start-date (car date) (cadr date) 1))
  304. (get-ut (1+ year) 1 1)))))))
  305. (error () (.fail))))))
  306. (defun .smart-date ()
  307. (let* ((now (get-universal-time))
  308. (date-now (get-date now)))
  309. (.or (.smart-range (.list (.prog1 (.number 4) (.date-delimiter))
  310. (.prog1 (.number) (.date-delimiter))
  311. (.number)))
  312. (.smart-range (.list (.prog1 (.number 4) (.date-delimiter))
  313. (.number)
  314. (.identity nil)))
  315. (.smart-range (.list (.number 4) (.identity nil) (.identity nil)))
  316. (.smart-range (.list (.identity nil)
  317. (.prog1 (.number) (.date-delimiter))
  318. (.number)))
  319. (.smart-range (.list (.identity nil) (.month) (.identity nil)))
  320. (.smart-range (.progn (.string= "today") (.identity date-now)))
  321. (.smart-range (.progn (.string= "yesterday") (.identity (get-date (- now +day+)))))
  322. (.smart-range (.progn (.string= "tomorrow") (.identity (get-date (+ now +day+)))))
  323. (.let* ((offset (.or (.progn (.string= "this") (.identity 0))
  324. (.progn (.string= "last") (.identity -1))
  325. (.progn (.string= "next") (.identity 1))
  326. (.identity 0)))
  327. (_ (.optional (.whitespace))))
  328. (.or (.smart-range (.progn (.string= "year")
  329. (.identity (list (+ (car date-now) offset) nil nil))))
  330. (.smart-range (.progn (.string= "month")
  331. (.identity (subseq (month-start-date (car date-now) (cadr date-now) offset)
  332. 0 2))))
  333. (.smart-range (.progn (.string= "week")
  334. (.identity (week-start-date now offset)))
  335. (* +day+ 7)))))))
  336. (defun .query-value-period ()
  337. (.let* ((period (.or (.let* ((start (.optional (.smart-date)))
  338. (_ (.optional (.whitespace)))
  339. (_ (.or (.char= #\-) (.string= "to")))
  340. (_ (.optional (.whitespace)))
  341. (end (.optional (.smart-date))))
  342. (if (or start end)
  343. (.identity (cons (car start) (car end)))
  344. (.fail)))
  345. (.smart-date))))
  346. (destructuring-bind (start . end) period
  347. (.identity #'(lambda (value)
  348. (and
  349. (or (not start) (>= value start))
  350. (or (not end) (< value end))))))))
  351. (defun .query-term ()
  352. (.or (.query-coloned :acct (.query-postingp "acct" #'posting-account)
  353. (.query-value-regex))
  354. (.query-coloned :amt (.progn (.string= "amt")
  355. (.identity
  356. #'(lambda (e p)
  357. (let ((amounts (get-amounts p (entry-postings e))))
  358. (if (> (length amounts) 1) :t
  359. (amount-quantity (car amounts)))))))
  360. (.query-value-amount))
  361. (.query-coloned :code (.query-entryp "code" #'entry-code)
  362. (.query-value-regex))
  363. (.query-coloned :cur (.progn (.string= "cur")
  364. (.identity
  365. #'(lambda (e p)
  366. (get-amounts p (entry-postings e)))))
  367. (.let* ((regexp (.query-value-regex)))
  368. (.identity #'(lambda (amounts)
  369. (find-if regexp amounts :key #'amount-commodity)))))
  370. (.query-coloned :desc (.query-entryp "desc" #'entry-description)
  371. (.query-value-regex))
  372. (.query-coloned :date (.query-entryp "date" #'entry-date)
  373. (.query-value-period))
  374. (.let* ((value (.query-value-regex)))
  375. (.identity (cons :acct
  376. #'(lambda (entry posting)
  377. (declare (ignore entry))
  378. (let ((account (posting-account posting)))
  379. (funcall value account))))))))
  380. (defun .arg ()
  381. (.let* ((word (.until (.chars #\' #\" #\Space #\Tab) :result-type 'string :at-least 0))
  382. (quoted (.optional (.let* ((quote (.chars #\' #\"))
  383. (text (.until (.char= quote) :result-type 'string :at-least 0))
  384. (_ (.char= quote)))
  385. (.identity text)))))
  386. (.identity (if quoted (concatenate 'string word quoted)
  387. word))))
  388. (defun make-query-predicate (terms)
  389. (let (desc acct status other)
  390. (loop for (type . f) in terms
  391. do (case type
  392. (:desc (push f desc))
  393. (:acct (push f acct))
  394. (:status (push f status))
  395. (otherwise (push f other))))
  396. #'(lambda (entry posting)
  397. (labels ((any (predicates)
  398. (or (not predicates)
  399. (find-if #'(lambda (p) (funcall p entry posting)) predicates)))
  400. (all (predicates)
  401. (not (find-if-not #'(lambda (p) (funcall p entry posting)) predicates))))
  402. (and (any desc) (any acct) (any status) (all other))))))
  403. (defun .query ()
  404. (.let* ((args (.mapcar* (.prog1 (.arg) (.optional (.whitespace))))))
  405. (loop for arg in args with terms
  406. do (multiple-value-bind (pred left)
  407. (parse (.query-term) arg)
  408. (if (and pred (input-empty-p left))
  409. (push pred terms)
  410. (return (.fail))))
  411. finally (return (.identity (make-query-predicate terms))))))
  412. (defun parse-query (query)
  413. (let ((predicate (parse (.query) query)))
  414. (unless predicate
  415. (error "bad query: ~A" query))
  416. predicate))
  417. (defun get-commodity (amount)
  418. (let ((com (amount-commodity amount)))
  419. (cond
  420. ((null com) *default-commodity*)
  421. ((equal com "$") "USD")
  422. ((equal com "€") "EUR")
  423. (t com))))
  424. (defun add-amounts! (sum amounts)
  425. (dolist (a amounts sum)
  426. (let* ((commodity (get-commodity a))
  427. (same (find commodity sum :key #'amount-commodity :test #'equal)))
  428. (unless same (setf same (car (push (make-amount :quantity 0 :commodity commodity)
  429. sum))))
  430. (incf (amount-quantity same)
  431. (amount-quantity a)))))
  432. (defun complement-amounts (postings &optional cost)
  433. (let ((sum
  434. (reduce #'add-amounts! postings :initial-value nil
  435. :key #'(lambda (p) (when (posting-amount p)
  436. (get-amounts p cost))))))
  437. (dolist (a sum sum)
  438. (setf (amount-quantity a)
  439. (- (amount-quantity a))))))
  440. (defun get-amounts (posting postings &optional cost)
  441. (let ((amount (posting-amount posting))
  442. (unit-price (posting-unit-price posting))
  443. (total-price (posting-total-price posting)))
  444. (if amount
  445. (if cost
  446. (if total-price (list total-price)
  447. (if unit-price
  448. (list (make-amount :commodity (amount-commodity unit-price)
  449. :quantity (* (amount-quantity amount)
  450. (amount-quantity unit-price))))
  451. (list amount)))
  452. (list amount))
  453. (complement-amounts postings cost))))
  454. (defun entries (journal)
  455. (mapcar #'cdr (remove :entry journal :key #'car :test-not #'eql)))
  456. (defun balance (entries &key predicate cost)
  457. (let ((balance (make-hash-table :test #'equal)))
  458. (dolist (entry entries balance)
  459. (dolist (posting (entry-postings entry))
  460. (when (or (null predicate)
  461. (funcall predicate entry posting))
  462. (let* ((account (posting-account posting))
  463. (amounts (get-amounts posting (entry-postings entry) cost)))
  464. (setf (gethash account balance)
  465. (add-amounts! (gethash account balance) amounts)
  466. (gethash "TOTALS" balance)
  467. (add-amounts! (gethash "TOTALS" balance) amounts))))))))
  468. (defun format-balance (balance)
  469. (let* ((accounts (alexandria:hash-table-keys balance))
  470. (max-account-length (apply #'max (mapcar #'length accounts))))
  471. (with-output-to-string (s)
  472. (loop for account in (sort accounts #'string<)
  473. for amounts = (gethash account balance)
  474. when (find 0 amounts :test-not #'= :key #'amount-quantity)
  475. do (format s "~vA ~$ ~A~{~%~va ~$ ~A~}~%" max-account-length account
  476. (amount-quantity (car amounts)) (amount-commodity (car amounts))
  477. (apply #'append (mapcar #'(lambda (a)
  478. (list max-account-length ""
  479. (amount-quantity a)
  480. (amount-commodity a)))
  481. (rest amounts))))))))