ledger.lisp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  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. (def-message-cmd-handler hander-add-report (:add_report)
  174. (bot-send-message chat-id "Введи название"
  175. :reply-markup (telegram-force-reply))
  176. (on-next-message chat-id
  177. (let ((name text))
  178. (bot-send-message chat-id "Введи запрос"
  179. :reply-markup (telegram-force-reply))
  180. (on-next-message chat-id
  181. (let ((query text))
  182. (pta-ledger:parse-query query) ;; Validate query
  183. (bot-send-message chat-id "Введи расписание, ex: (:day-of-week 0 :hour 10), (:day * :hour 10)"
  184. :reply-markup (telegram-force-reply))
  185. (on-next-message chat-id
  186. (let* ((schedule text))
  187. (add-chat-cron :ledger-report chat-id schedule name query)
  188. (bot-send-message chat-id "Добавил"))))))))
  189. (defun run-report (chat-id name query)
  190. (with-chat-journal (chat-id journal updated)
  191. (bot-send-message chat-id
  192. (text-chunks (split-sequence:split-sequence
  193. #\Newline
  194. (format nil "*~A*~%~%~A" name
  195. (pta-ledger:journal-balance journal query)))
  196. :text-sep "
  197. ")
  198. :parse-mode "markdown")))
  199. (def-chat-cron-handler handler-chat-cron (:ledger-report chat-id schedule name query)
  200. (run-report chat-id name query))
  201. (def-message-cmd-handler handler-reports (:reports)
  202. (let ((crons (get-chat-crons :ledger-report chat-id)))
  203. (if crons
  204. (bot-send-message
  205. chat-id "Отчёты"
  206. :parse-mode "markdown"
  207. :reply-markup
  208. (get-inline-keyboard
  209. chat-id
  210. (append
  211. (loop for (schedule name query) in crons
  212. for idx from 0
  213. collect
  214. (let ((cron-index idx)
  215. (cron-name name))
  216. (list (inline-button ((format nil "Удалить '~A'" cron-name))
  217. (delete-chat-cron :ledger-report chat-id cron-index)
  218. (bot-send-message chat-id (format nil "Удалил *~A*" cron-name)
  219. :parse-mode "markdown")))))
  220. (list (list (inline-button ("Отмена")
  221. (telegram-edit-message-reply-markup
  222. nil :chat-id source-chat-id :message-id source-message-id)))))))
  223. (bot-send-message
  224. chat-id "Отчётов пока нет"
  225. :reply-markup (telegram-reply-keyboard-markup (list (list (list :text "/add_report")))
  226. :one-time-keyboard t)))))
  227. (defun match-entry (text journal)
  228. (labels ((two-post (entries)
  229. (remove-if-not #'(lambda (e)
  230. (= 2 (length (pta-ledger:entry-postings e))))
  231. entries)))
  232. (let ((desc (two-post
  233. (pta-ledger:journal-entries journal (format nil "desc:'~A'" text)))))
  234. (if desc (car (last desc))
  235. (let ((comment (two-post
  236. (pta-ledger:journal-entries journal (format nil "comment:'~A'" text)))))
  237. (when comment (car (last comment))))))))
  238. (defun create-entry (chat-id text amount currency)
  239. (with-chat-journal (chat-id journal updated)
  240. (let* ((old (match-entry text journal))
  241. (new (or (when old (pta-ledger:clone-entry old))
  242. (pta-ledger:make-entry
  243. :description text
  244. :postings (list
  245. (pta-ledger:make-posting :account "expenses")
  246. (pta-ledger:make-posting)))))
  247. (postings (pta-ledger:entry-postings new)))
  248. (setf (pta-ledger:entry-date new) (get-universal-time)
  249. (pta-ledger:posting-amount (car postings)) (pta-ledger:make-amount
  250. :quantity amount
  251. :commodity currency)
  252. (pta-ledger:posting-amount (cadr postings)) (pta-ledger:make-amount
  253. :quantity (- amount)
  254. :commodity currency)
  255. (pta-ledger:posting-account (cadr postings)) (format nil "assets:Cash:~A" currency))
  256. new)))
  257. (def-message-cmd-handler handler-create (:rub :usd :eur :thb :btc)
  258. (cond
  259. ((>= (length args) 2)
  260. (ledger/new-chat-entry chat-id (create-entry chat-id
  261. (spaced (subseq args 1))
  262. (parse-float (car args))
  263. (symbol-name cmd))))
  264. (:otherwise (bot-send-message chat-id (format nil "/~A <amount> <description>" cmd)))))
  265. (def-webhook-handler ledger/handle-webhook ("ledger")
  266. (when (= 2 (length paths))
  267. (destructuring-bind (chat-id hmac) paths
  268. (let ((true-hmac (token-hmac chat-id)))
  269. (when (string= true-hmac hmac)
  270. (with-secret (info (list :ledger chat-id))
  271. (when info
  272. (let ((chat-id (parse-integer chat-id)))
  273. (log:info "Updating ledger for ~A" chat-id)
  274. (setf (gethash chat-id *ledger/chat-journals*) nil)
  275. (get-chat-journal-info chat-id info)
  276. "OK"))))))))
  277. ;; New entries
  278. (defun format-entry (entry)
  279. (let ((pta-ledger:*posting-length* 40))
  280. (format nil "```~%~A```" (pta-ledger:render entry))))
  281. (defun ledger/format-add-entry-message (from)
  282. (format nil "Ledger add from ~A ~A at ~A"
  283. (aget "first_name" from) (aget "last_name" from)
  284. (ledger/format-time (get-universal-time))))
  285. (defun ledger/process-add-entry (chat-id from entry)
  286. (with-secret (info (list :ledger chat-id))
  287. (if info
  288. (cond
  289. ((consp info)
  290. (handler-case (progn
  291. (ledger/add-git
  292. chat-id
  293. (car info) (cadr info)
  294. (pta-ledger:render entry)
  295. (ledger/format-add-entry-message from))
  296. "Добавил!")
  297. (error (e)
  298. (log:error "~A" e)
  299. "Не смог :(")))
  300. (:otherwise "Добавляю только в git журнал :("))
  301. "Добавь git журнал.")))
  302. (defun ledger/new-chat-entry (chat-id entry)
  303. (bot-send-message
  304. chat-id (format-entry entry)
  305. :parse-mode "markdown"
  306. :reply-markup (keyboard/entry chat-id entry)))
  307. (defun entry-edit (chat-id message-id entry)
  308. (telegram-edit-message-text
  309. (format-entry entry)
  310. :chat-id chat-id :message-id message-id
  311. :parse-mode "markdown"
  312. :reply-markup (keyboard/edit-entry chat-id entry)))
  313. (defun keyboard/entry (chat-id entry)
  314. (get-inline-keyboard
  315. chat-id
  316. (list
  317. (list (inline-button ("➕")
  318. (telegram-answer-callback-query query-id :text "Добавляю...")
  319. (telegram-send-message source-chat-id (ledger/process-add-entry
  320. source-chat-id from entry))
  321. (telegram-edit-message-reply-markup
  322. nil :chat-id source-chat-id :message-id source-message-id))
  323. (inline-button ("💲")
  324. (entry-edit source-chat-id source-message-id entry))
  325. (inline-button ("✖️")
  326. (telegram-delete-message source-chat-id source-message-id))))))
  327. (defun def (str default)
  328. (if (or (null str) (string= "" str)) default
  329. str))
  330. (defun keyboard/edit-entry (chat-id entry)
  331. (get-inline-keyboard
  332. chat-id
  333. (append
  334. (list
  335. (list (inline-button ((format-date (pta-ledger:entry-date entry)))
  336. (bot-send-message chat-id "Введите дату"
  337. :reply-markup (telegram-force-reply))
  338. (on-next-message chat-id
  339. (let ((date (pta-ledger:parse-date text (get-year
  340. (pta-ledger:entry-date entry)))))
  341. (if date
  342. (progn
  343. (setf (pta-ledger:entry-date entry) date)
  344. (entry-edit chat-id source-message-id entry))
  345. (bot-send-message chat-id "Не разобрал")))))
  346. (inline-button ((def (pta-ledger:entry-description entry) "Описание"))
  347. (bot-send-message chat-id "Введите описание"
  348. :reply-markup (telegram-force-reply))
  349. (on-next-message chat-id
  350. (setf (pta-ledger:entry-description entry) text)
  351. (entry-edit chat-id source-message-id entry)))
  352. (inline-button ((def (pta-ledger:entry-comment entry) "Коммент"))
  353. (bot-send-message chat-id "Введите комментарий"
  354. :reply-markup (telegram-force-reply))
  355. (on-next-message chat-id
  356. (setf (pta-ledger:entry-comment entry) text)
  357. (entry-edit chat-id source-message-id entry)))))
  358. (loop for posting in (pta-ledger:entry-postings entry)
  359. collect
  360. (let ((this-posting posting))
  361. (list (inline-button ((pta-ledger:posting-account posting))
  362. (account-edit chat-id source-message-id entry this-posting
  363. (pta-ledger:posting-account this-posting)))
  364. (inline-button ((def (pta-ledger:render
  365. (pta-ledger:posting-amount posting))
  366. "Сумма"))
  367. (bot-send-message chat-id "Введите сумму"
  368. :reply-markup (telegram-force-reply))
  369. (on-next-message chat-id
  370. (let ((amount (pta-ledger:parse-amount text)))
  371. (setf (pta-ledger:posting-amount this-posting) amount)
  372. (entry-edit chat-id source-message-id entry)))))))
  373. (list (list (inline-button ("Готово")
  374. (telegram-edit-message-reply-markup
  375. (keyboard/entry chat-id entry)
  376. :chat-id chat-id :message-id source-message-id)))))))
  377. (defun accounts/nav (account accounts &optional (offset 0) (count 5))
  378. (let* ((len (1+ (length account)))
  379. (sep-pos (position #\: account :from-end t))
  380. (parent (when sep-pos (subseq account 0 sep-pos)))
  381. (head (when account (concatenate 'string account ":")))
  382. (descendants (remove-if #'(lambda (a)
  383. (when head
  384. (not (equal head
  385. (subseq a 0 (min (length a) len))))))
  386. accounts)))
  387. (if descendants
  388. (let* ((children (sort (remove-duplicates
  389. (mapcar #'(lambda (d)
  390. (subseq d 0 (or (position #\: d :start len)
  391. (length d))))
  392. descendants)
  393. :test #'equal) #'string<))
  394. (total (length children)))
  395. (when (stringp offset)
  396. (let ((off (position offset children :test #'equal)))
  397. (setf offset (if off (max 0 (- off (round count 2))) 0))))
  398. (values account parent
  399. (mapcar
  400. #'(lambda (c)
  401. (let* ((needle (concatenate 'string c ":"))
  402. (n-l (length needle)))
  403. (cons c
  404. (not
  405. (find needle accounts :test #'equal
  406. :key #'(lambda (a)
  407. (subseq a 0 (min n-l (length a)))))))))
  408. (subseq children offset
  409. (min total (+ offset count))))
  410. (unless (zerop offset) (max 0 (- offset count)))
  411. (when (< (+ offset count) total) (+ offset count))))
  412. (when parent (accounts/nav parent accounts account)))))
  413. (defun account-edit (chat-id message-id entry posting account &optional (offset 0))
  414. (with-chat-journal (chat-id journal updated)
  415. (let* ((accounts (pta-ledger:journal-accounts journal))
  416. (nav-list (multiple-value-list
  417. (accounts/nav account accounts offset))))
  418. (telegram-edit-message-reply-markup
  419. (apply #'keyboard/account chat-id entry posting nav-list)
  420. :chat-id chat-id :message-id message-id))))
  421. (defun keyboard/account (chat-id entry posting account parent children prev next)
  422. (get-inline-keyboard
  423. chat-id
  424. (append
  425. (list (list (when account
  426. (inline-button (account)
  427. (setf (pta-ledger:posting-account posting) account)
  428. (entry-edit chat-id source-message-id entry)))
  429. (inline-button ("Ввести")
  430. (bot-send-message chat-id "Введите счёт"
  431. :reply-markup (telegram-force-reply))
  432. (on-next-message chat-id
  433. (let ((account (pta-ledger:parse-account text)))
  434. (if account
  435. (progn
  436. (setf (pta-ledger:posting-account posting) account)
  437. (entry-edit chat-id source-message-id entry))
  438. (bot-send-message chat-id "Не разобрал")))))))
  439. (loop for (acc . leaf) in children
  440. collect (let ((this-account acc))
  441. (list (if leaf
  442. (inline-button (this-account)
  443. (setf (pta-ledger:posting-account posting) this-account)
  444. (entry-edit chat-id source-message-id entry))
  445. (inline-button ((format nil "~A ..." this-account))
  446. (account-edit chat-id source-message-id entry posting
  447. this-account))))))
  448. (list (list (when prev
  449. (inline-button ("<<")
  450. (account-edit chat-id source-message-id entry posting
  451. account prev)))
  452. (when (or parent account)
  453. (inline-button ((or parent "ACC"))
  454. (account-edit chat-id source-message-id entry posting
  455. parent account)))
  456. (when next
  457. (inline-button (">>")
  458. (account-edit chat-id source-message-id entry posting
  459. account next))))))))