1
0

ledger.lisp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. (in-package :cl-user)
  2. (defpackage chatikbot.plugins.ledger
  3. (:use :cl :chatikbot.common))
  4. (in-package :chatikbot.plugins.ledger)
  5. (eval-when (:compile-toplevel :load-toplevel :execute)
  6. (ql:quickload '(:pta-ledger :legit)))
  7. (defsetting *ledger/default-timezone* -3 "Default timezone for time display. GMT+3")
  8. (defvar *ledger/chat-journals* (make-hash-table))
  9. (defvar *git-repo-locks* (make-hash-table :test #'equal))
  10. (defun git-get-repo-lock (repo)
  11. (let ((key (legit:location repo)))
  12. (setf key
  13. (etypecase key
  14. (string key)
  15. (pathname (namestring key))))
  16. (or (gethash key *git-repo-locks*)
  17. (setf (gethash key *git-repo-locks*)
  18. (bt:make-recursive-lock key)))))
  19. (defun git-get-repo (location remote)
  20. (let ((repo (make-instance 'legit:repository :location location)))
  21. (bt:with-recursive-lock-held ((git-get-repo-lock repo))
  22. (legit:init repo :remote remote :if-does-not-exist :clone))
  23. repo))
  24. (defsetting *git-repos-root* "/tmp/ledger-repos/")
  25. (defun git-get-chat-location (chat-id remote)
  26. (namestring (uiop:ensure-directory-pathname
  27. (merge-pathnames (format nil "~A-~A" chat-id (token-hmac remote))
  28. *git-repos-root*))))
  29. (defun git-read-latest-file (repo path)
  30. (bt:with-recursive-lock-held ((git-get-repo-lock repo))
  31. (legit:fetch repo :branch "master" :remote "origin")
  32. (legit:reset repo :hard t :to "origin/master")
  33. (uiop:read-file-string (merge-pathnames path (legit:location repo)))))
  34. (defun ledger/refresh-git (chat-id remote path)
  35. (let* ((location (git-get-chat-location chat-id remote))
  36. (repo (git-get-repo location remote))
  37. (content (git-read-latest-file repo path))
  38. (journal (pta-ledger:parse-journal content))
  39. (updated (legit:current-age repo)))
  40. (setf (gethash chat-id *ledger/chat-journals*)
  41. (cons journal updated))))
  42. (defun git-append-latest-file (repo path text message)
  43. (bt:with-recursive-lock-held ((git-get-repo-lock repo))
  44. (let ((repo-path (merge-pathnames path (legit:location repo))))
  45. (dotimes (tries 5)
  46. (let ((current (or (ignore-errors (git-read-latest-file repo path)) "")))
  47. (uiop/stream:with-output-file (s repo-path
  48. :if-exists :supersede
  49. :if-does-not-exist :create)
  50. (format s "~A~A" current text)))
  51. (legit:add repo (namestring repo-path))
  52. (legit:commit repo message)
  53. (handler-case
  54. (progn
  55. (legit:push repo)
  56. (return-from git-append-latest-file path))
  57. (legit:git-error ())))
  58. (error "Tried 5 times to push ~A to ~A" path (legit:remote-url repo)))))
  59. (defun ledger/add-git (chat-id remote path text message)
  60. (let* ((location (git-get-chat-location chat-id remote))
  61. (repo (git-get-repo location remote)))
  62. (git-append-latest-file repo path
  63. (format nil "~%~A~%" text)
  64. message)))
  65. (defun ledger/get-hook-url (chat-id)
  66. (get-webhook-url "ledger" chat-id (token-hmac (write-to-string chat-id))))
  67. (defun ledger/format-uri (url)
  68. (let ((uri (quri:uri url)))
  69. (quri:render-uri (quri:make-uri :userinfo (when (quri:uri-userinfo uri) "*:*")
  70. :defaults url))))
  71. (defun ledger/format-time (universal-time)
  72. (when universal-time
  73. (multiple-value-bind (sec min hour day month year dow dst-p tz)
  74. (decode-universal-time universal-time *ledger/default-timezone*)
  75. (declare (ignore dow dst-p tz))
  76. (format nil "~4,'0D-~2,'0D-~2,'0D ~2,'0D:~2,'0D:~2,'0D"
  77. year month day hour min sec))))
  78. (defun format-date (ut)
  79. (multiple-value-bind (sec min hour day month year)
  80. (decode-universal-time ut)
  81. (declare (ignore sec min hour))
  82. (format nil "~4,'0D-~2,'0D-~2,'0D"
  83. year month day)))
  84. (defun get-year (ut)
  85. (multiple-value-bind (sec min hour day month year)
  86. (decode-universal-time ut)
  87. (declare (ignore sec min hour day month))
  88. year))
  89. (defun ledger/refresh-uri (chat-id uri)
  90. (setf (gethash chat-id *ledger/chat-journals*)
  91. (cons (pta-ledger:parse-journal (http-request uri))
  92. (get-universal-time))))
  93. (defun get-chat-journal-info (chat-id &optional info)
  94. (labels ((process-info (info)
  95. (cond
  96. ((stringp info) (ledger/refresh-uri chat-id info))
  97. ((consp info) (apply #'ledger/refresh-git chat-id info))
  98. (:otherwise nil))))
  99. (let ((journal-info (gethash chat-id *ledger/chat-journals*)))
  100. (if journal-info journal-info
  101. (if info (process-info info)
  102. (with-secret (info (list :ledger chat-id))
  103. (process-info info)))))))
  104. (Defun ledger/handle-info (chat-id)
  105. (with-secret (info (list :ledger chat-id))
  106. (if info
  107. (destructuring-bind (journal . ut)
  108. (get-chat-journal-info chat-id info)
  109. (let ((uri (cond
  110. ((consp info) (car info))
  111. ((stringp info) info))))
  112. (bot-send-message chat-id (format nil "Журнал с ~D записями, из ~A, обновлён ~A.~%Веб-хук: ~A"
  113. (length journal)
  114. (ledger/format-uri uri)
  115. (ledger/format-time ut)
  116. (ledger/get-hook-url chat-id))
  117. :disable-web-preview t)))
  118. (bot-send-message chat-id "Добавь журнал: uri - /ledger <url>; git - /ledger <remote> <path>"))))
  119. (defun ledger/handle-set-info (chat-id info)
  120. (setf (gethash chat-id *ledger/chat-journals*) nil)
  121. (handler-case
  122. (destructuring-bind (journal . ut)
  123. (get-chat-journal-info chat-id info)
  124. (declare (ignore ut))
  125. (secret-set (list :ledger chat-id) info)
  126. (bot-send-message chat-id (format nil "Добавил журнал с ~D записями. Веб-хук для обновления: ~A"
  127. (length journal)
  128. (ledger/get-hook-url chat-id))))
  129. (pta-ledger:journal-failed (e)
  130. (bot-send-message chat-id (format nil "Не смог спарсить: ~A" e)))
  131. (dex:http-request-failed (e)
  132. (bot-send-message chat-id (format nil "Не смог в урл: ~A" (dex:response-body e))))))
  133. (def-message-cmd-handler handler-ledger (:ledger)
  134. (cond
  135. ((<= 1 (length args) 2) (ledger/handle-set-info chat-id args))
  136. (:otherwise (ledger/handle-info chat-id))))
  137. (defmacro with-chat-journal ((chat-id journal updated) &body body)
  138. (let ((info (gensym "info")))
  139. `(let ((,info (get-chat-journal-info ,chat-id)))
  140. (if ,info
  141. (destructuring-bind (,journal . ,updated) ,info
  142. (declare (ignorable ,journal ,updated))
  143. ,@body)
  144. (bot-send-message ,chat-id "Добавь журнал: uri - /ledger <url>; git - /ledger <remote> <path>")))))
  145. (defun ledger/handle-balance (chat-id query)
  146. (with-chat-journal (chat-id journal updated)
  147. (bot-send-message chat-id
  148. (text-chunks (split-sequence:split-sequence
  149. #\Newline
  150. (pta-ledger:journal-balance journal query))
  151. :text-sep "
  152. ")
  153. :parse-mode "markdown")))
  154. (def-message-cmd-handler handler-balance (:balance :bal)
  155. (cond
  156. ((null args) (ledger/handle-balance chat-id "assets"))
  157. (:otherwise (ledger/handle-balance chat-id (spaced args)))))
  158. (defun ledger/handle-journal (chat-id query)
  159. (with-chat-journal (chat-id journal updated)
  160. (let* ((pta-ledger:*posting-length* 40)
  161. (entries (pta-ledger:journal-print journal query))
  162. (len (length entries))
  163. (count (min len 50)))
  164. (bot-send-message chat-id
  165. (if entries
  166. (text-chunks (subseq entries (- len count) len))
  167. "Не нашлось")
  168. :parse-mode "markdown"))))
  169. (def-message-cmd-handler handler-journal (:journal)
  170. (cond
  171. ((null args) (ledger/handle-journal chat-id "date:thisweek"))
  172. (:otherwise (ledger/handle-journal chat-id (spaced args)))))
  173. (defun match-entry (text journal)
  174. (labels ((two-post (entries)
  175. (remove-if-not #'(lambda (e)
  176. (= 2 (length (pta-ledger:entry-postings e))))
  177. entries)))
  178. (let ((desc (two-post
  179. (pta-ledger:journal-entries journal (format nil "desc:'~A'" text)))))
  180. (if desc (car (last desc))
  181. (let ((comment (two-post
  182. (pta-ledger:journal-entries journal (format nil "comment:'~A'" text)))))
  183. (when comment (car (last comment))))))))
  184. (defun create-entry (chat-id text amount currency)
  185. (with-chat-journal (chat-id journal updated)
  186. (let* ((old (match-entry text journal))
  187. (new (or (when old (pta-ledger:clone-entry old))
  188. (pta-ledger:make-entry
  189. :description text
  190. :postings (list
  191. (pta-ledger:make-posting :account "expenses")
  192. (pta-ledger:make-posting)))))
  193. (postings (pta-ledger:entry-postings new)))
  194. (setf (pta-ledger:entry-date new) (get-universal-time)
  195. (pta-ledger:posting-amount (car postings)) (pta-ledger:make-amount
  196. :quantity amount
  197. :commodity currency)
  198. (pta-ledger:posting-amount (cadr postings)) (pta-ledger:make-amount
  199. :quantity (- amount)
  200. :commodity currency)
  201. (pta-ledger:posting-account (cadr postings)) (format nil "assets:Cash:~A" currency))
  202. new)))
  203. (def-message-cmd-handler handler-create (:rub :usd :eur :thb :btc)
  204. (cond
  205. ((>= (length args) 2)
  206. (ledger/new-chat-entry chat-id (create-entry chat-id
  207. (spaced (subseq args 1))
  208. (parse-float (car args))
  209. (symbol-name cmd))))
  210. (:otherwise (bot-send-message chat-id (format nil "/~A <amount> <description>" cmd)))))
  211. (def-webhook-handler ledger/handle-webhook ("ledger")
  212. (when (= 2 (length paths))
  213. (destructuring-bind (chat-id hmac) paths
  214. (let ((true-hmac (token-hmac chat-id)))
  215. (when (string= true-hmac hmac)
  216. (with-secret (info (list :ledger chat-id))
  217. (when info
  218. (let ((chat-id (parse-integer chat-id)))
  219. (log:info "Updating ledger for ~A" chat-id)
  220. (setf (gethash chat-id *ledger/chat-journals*) nil)
  221. (get-chat-journal-info chat-id info)
  222. "OK"))))))))
  223. ;; New entries
  224. (defun format-entry (entry)
  225. (let ((pta-ledger:*posting-length* 40))
  226. (format nil "```~%~A```" (pta-ledger:render entry))))
  227. (defun ledger/format-add-entry-message (from)
  228. (format nil "Ledger add from ~A ~A at ~A"
  229. (aget "first_name" from) (aget "last_name" from)
  230. (ledger/format-time (get-universal-time))))
  231. (defun ledger/process-add-entry (chat-id from entry)
  232. (with-secret (info (list :ledger chat-id))
  233. (if info
  234. (cond
  235. ((consp info)
  236. (handler-case (progn
  237. (ledger/add-git
  238. chat-id
  239. (car info) (cadr info)
  240. (pta-ledger:render entry)
  241. (ledger/format-add-entry-message from))
  242. "Добавил!")
  243. (error (e)
  244. (log:error "~A" e)
  245. "Не смог :(")))
  246. (:otherwise "Добавляю только в git журнал :("))
  247. "Добавь git журнал.")))
  248. (defun ledger/new-chat-entry (chat-id entry)
  249. (bot-send-message
  250. chat-id (format-entry entry)
  251. :parse-mode "markdown"
  252. :reply-markup (keyboard/entry chat-id entry)))
  253. (defun entry-edit (chat-id message-id entry)
  254. (telegram-edit-message-text
  255. (format-entry entry)
  256. :chat-id chat-id :message-id message-id
  257. :parse-mode "markdown"
  258. :reply-markup (keyboard/edit-entry chat-id entry)))
  259. (defun keyboard/entry (chat-id entry)
  260. (get-inline-keyboard
  261. chat-id
  262. (list
  263. (list (inline-button ("➕")
  264. (telegram-answer-callback-query query-id :text "Добавляю...")
  265. (telegram-send-message source-chat-id (ledger/process-add-entry
  266. source-chat-id from entry))
  267. (telegram-edit-message-reply-markup
  268. nil :chat-id source-chat-id :message-id source-message-id))
  269. (inline-button ("💲")
  270. (entry-edit source-chat-id source-message-id entry))
  271. (inline-button ("✖️")
  272. (telegram-delete-message source-chat-id source-message-id))))))
  273. (defun def (str default)
  274. (if (or (null str) (string= "" str)) default
  275. str))
  276. (defun keyboard/edit-entry (chat-id entry)
  277. (get-inline-keyboard
  278. chat-id
  279. (append
  280. (list
  281. (list (inline-button ((format-date (pta-ledger:entry-date entry)))
  282. (bot-send-message chat-id "Введите дату"
  283. :reply-markup (telegram-force-reply))
  284. (on-next-message chat-id
  285. (let ((date (pta-ledger:parse-date text (get-year
  286. (pta-ledger:entry-date entry)))))
  287. (if date
  288. (progn
  289. (setf (pta-ledger:entry-date entry) date)
  290. (entry-edit chat-id source-message-id entry))
  291. (bot-send-message chat-id "Не разобрал")))))
  292. (inline-button ((def (pta-ledger:entry-description entry) "Описание"))
  293. (bot-send-message chat-id "Введите описание"
  294. :reply-markup (telegram-force-reply))
  295. (on-next-message chat-id
  296. (setf (pta-ledger:entry-description entry) text)
  297. (entry-edit chat-id source-message-id entry)))
  298. (inline-button ((def (pta-ledger:entry-comment entry) "Коммент"))
  299. (bot-send-message chat-id "Введите комментарий"
  300. :reply-markup (telegram-force-reply))
  301. (on-next-message chat-id
  302. (setf (pta-ledger:entry-comment entry) text)
  303. (entry-edit chat-id source-message-id entry)))))
  304. (loop for posting in (pta-ledger:entry-postings entry)
  305. collect
  306. (let ((this-posting posting))
  307. (list (inline-button ((pta-ledger:posting-account posting))
  308. (account-edit chat-id source-message-id entry this-posting
  309. (pta-ledger:posting-account this-posting)))
  310. (inline-button ((def (pta-ledger:render
  311. (pta-ledger:posting-amount posting))
  312. "Сумма"))
  313. (bot-send-message chat-id "Введите сумму"
  314. :reply-markup (telegram-force-reply))
  315. (on-next-message chat-id
  316. (let ((amount (pta-ledger:parse-amount text)))
  317. (setf (pta-ledger:posting-amount this-posting) amount)
  318. (entry-edit chat-id source-message-id entry)))))))
  319. (list (list (inline-button ("Готово")
  320. (telegram-edit-message-reply-markup
  321. (keyboard/entry chat-id entry)
  322. :chat-id chat-id :message-id source-message-id)))))))
  323. (defun accounts/nav (account accounts &optional (offset 0) (count 5))
  324. (let* ((len (1+ (length account)))
  325. (sep-pos (position #\: account :from-end t))
  326. (parent (when sep-pos (subseq account 0 sep-pos)))
  327. (head (when account (concatenate 'string account ":")))
  328. (descendants (remove-if #'(lambda (a)
  329. (when head
  330. (not (equal head
  331. (subseq a 0 (min (length a) len))))))
  332. accounts)))
  333. (if descendants
  334. (let* ((children (sort (remove-duplicates
  335. (mapcar #'(lambda (d)
  336. (subseq d 0 (or (position #\: d :start len)
  337. (length d))))
  338. descendants)
  339. :test #'equal) #'string<))
  340. (total (length children)))
  341. (when (stringp offset)
  342. (let ((off (position offset children :test #'equal)))
  343. (setf offset (if off (max 0 (- off (round count 2))) 0))))
  344. (values account parent
  345. (mapcar
  346. #'(lambda (c)
  347. (let* ((needle (concatenate 'string c ":"))
  348. (n-l (length needle)))
  349. (cons c
  350. (not
  351. (find needle accounts :test #'equal
  352. :key #'(lambda (a)
  353. (subseq a 0 (min n-l (length a)))))))))
  354. (subseq children offset
  355. (min total (+ offset count))))
  356. (unless (zerop offset) (max 0 (- offset count)))
  357. (when (< (+ offset count) total) (+ offset count))))
  358. (when parent (accounts/nav parent accounts account)))))
  359. (defun account-edit (chat-id message-id entry posting account &optional (offset 0))
  360. (with-chat-journal (chat-id journal updated)
  361. (let* ((accounts (pta-ledger:journal-accounts journal))
  362. (nav-list (multiple-value-list
  363. (accounts/nav account accounts offset))))
  364. (telegram-edit-message-reply-markup
  365. (apply #'keyboard/account chat-id entry posting nav-list)
  366. :chat-id chat-id :message-id message-id))))
  367. (defun keyboard/account (chat-id entry posting account parent children prev next)
  368. (get-inline-keyboard
  369. chat-id
  370. (append
  371. (list (list (when account
  372. (inline-button (account)
  373. (setf (pta-ledger:posting-account posting) account)
  374. (entry-edit chat-id source-message-id entry)))
  375. (inline-button ("Ввести")
  376. (bot-send-message chat-id "Введите счёт"
  377. :reply-markup (telegram-force-reply))
  378. (on-next-message chat-id
  379. (let ((account (pta-ledger:parse-account text)))
  380. (if account
  381. (progn
  382. (setf (pta-ledger:posting-account posting) account)
  383. (entry-edit chat-id source-message-id entry))
  384. (bot-send-message chat-id "Не разобрал")))))))
  385. (loop for (acc . leaf) in children
  386. collect (let ((this-account acc))
  387. (list (if leaf
  388. (inline-button (this-account)
  389. (setf (pta-ledger:posting-account posting) this-account)
  390. (entry-edit chat-id source-message-id entry))
  391. (inline-button ((format nil "~A ..." this-account))
  392. (account-edit chat-id source-message-id entry posting
  393. this-account))))))
  394. (list (list (when prev
  395. (inline-button ("<<")
  396. (account-edit chat-id source-message-id entry posting
  397. account prev)))
  398. (when (or parent account)
  399. (inline-button ((or parent "ACC"))
  400. (account-edit chat-id source-message-id entry posting
  401. parent account)))
  402. (when next
  403. (inline-button (">>")
  404. (account-edit chat-id source-message-id entry posting
  405. account next))))))))