1
0

ledger.lisp 23 KB

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