ledger.lisp 23 KB

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