ledger.lisp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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. (send-response 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. (send-response chat-id (format nil "Добавил журнал с ~D записями. Веб-хук для обновления: ~A"
  127. (length journal)
  128. (ledger/get-hook-url chat-id))))
  129. (pta-ledger:journal-failed (e)
  130. (send-response chat-id (format nil "Не смог спарсить: ~A" e)))
  131. (dex:http-request-failed (e)
  132. (send-response 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. (send-response ,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 (format nil "```~%~A~%```Обновлено: ~A"
  148. (pta-ledger:journal-balance journal query)
  149. (ledger/format-time updated))
  150. :parse-mode "markdown")))
  151. (def-message-cmd-handler handler-balance (:balance :bal)
  152. (cond
  153. ((null args) (ledger/handle-balance chat-id "assets"))
  154. (:otherwise (ledger/handle-balance chat-id (spaced args)))))
  155. (defun ledger/handle-journal (chat-id query)
  156. (with-chat-journal (chat-id journal updated)
  157. (let* ((entries (pta-ledger:journal-print journal query))
  158. (len (length entries))
  159. (count (min len 20)))
  160. (bot-send-message chat-id (format nil "```~%~{~A~^ ~%~%~}```Обновлено: ~A"
  161. (subseq entries (- len count) len)
  162. (ledger/format-time updated))
  163. :parse-mode "markdown"))))
  164. (def-message-cmd-handler handler-journal (:journal)
  165. (cond
  166. ((null args) (ledger/handle-journal chat-id "date:thisweek"))
  167. (:otherwise (ledger/handle-journal chat-id (spaced args)))))
  168. (def-webhook-handler ledger/handle-webhook ("ledger")
  169. (when (= 2 (length paths))
  170. (destructuring-bind (chat-id hmac) paths
  171. (let ((true-hmac (token-hmac chat-id)))
  172. (when (string= true-hmac hmac)
  173. (with-secret (info (list :ledger chat-id))
  174. (when info
  175. (let ((chat-id (parse-integer chat-id)))
  176. (log:info "Updating ledger for ~A" chat-id)
  177. (setf (gethash chat-id *ledger/chat-journals*) nil)
  178. (get-chat-journal-info chat-id info)
  179. "OK"))))))))
  180. ;; New entries
  181. (defun format-entry (entry)
  182. (let ((pta-ledger:*posting-length* 40))
  183. (format nil "```~%~A```" (pta-ledger:render entry))))
  184. (defun ledger/format-add-entry-message (from)
  185. (format nil "Ledger add from ~A ~A at ~A"
  186. (aget "first_name" from) (aget "last_name" from)
  187. (ledger/format-time (get-universal-time))))
  188. (defun ledger/process-add-entry (chat-id callback)
  189. (with-secret (info (list :ledger chat-id))
  190. (if info
  191. (cond
  192. ((consp info)
  193. (handler-case (progn
  194. (ledger/add-git
  195. chat-id
  196. (car info) (cadr info)
  197. (agets callback "message" "text")
  198. (ledger/format-add-entry-message (agets callback "from")))
  199. "Добавил!")
  200. (error (e)
  201. (log:error "~A" e)
  202. "Не смог :(")))
  203. (:otherwise "Добавляю только в git журнал :("))
  204. "Добавь git журнал.")))
  205. (defun ledger/new-chat-entry (chat-id entry)
  206. (bot-send-message
  207. chat-id (format-entry entry)
  208. :parse-mode "markdown"
  209. :reply-markup (keyboard/entry chat-id entry)))
  210. (defun entry-edit (chat-id message-id entry)
  211. (telegram-edit-message-text
  212. (format-entry entry)
  213. :chat-id chat-id :message-id message-id
  214. :parse-mode "markdown"
  215. :reply-markup (keyboard/edit-entry chat-id entry)))
  216. (defun keyboard/entry (chat-id entry)
  217. (get-inline-keyboard
  218. chat-id
  219. (list
  220. (list (inline-button ("➕")
  221. (telegram-answer-callback-query query-id :text "Добавляю...")
  222. (telegram-send-message source-chat-id (ledger/process-add-entry
  223. source-chat-id callback))
  224. (telegram-edit-message-reply-markup
  225. nil :chat-id source-chat-id :message-id source-message-id))
  226. (inline-button ("💲")
  227. (entry-edit source-chat-id source-message-id entry))
  228. (inline-button ("✖️")
  229. (telegram-delete-message source-chat-id source-message-id))))))
  230. (defun def (str default)
  231. (if (or (null str) (string= "" str)) default
  232. str))
  233. (defun keyboard/edit-entry (chat-id entry)
  234. (get-inline-keyboard
  235. chat-id
  236. (append
  237. (list
  238. (list (inline-button ((format-date (pta-ledger:entry-date entry)))
  239. (bot-send-message chat-id "Введите дату"
  240. :reply-markup (telegram-force-reply))
  241. (on-next-message chat-id
  242. (let ((date (pta-ledger:parse-date text (get-year
  243. (pta-ledger:entry-date entry)))))
  244. (if date
  245. (progn
  246. (setf (pta-ledger:entry-date entry) date)
  247. (entry-edit chat-id source-message-id entry))
  248. (bot-send-message chat-id "Не разобрал")))))
  249. (inline-button ((def (pta-ledger:entry-description entry) "Описание"))
  250. (bot-send-message chat-id "Введите описание"
  251. :reply-markup (telegram-force-reply))
  252. (on-next-message chat-id
  253. (setf (pta-ledger:entry-description entry) text)
  254. (entry-edit chat-id source-message-id entry)))
  255. (inline-button ((def (pta-ledger:entry-comment entry) "Коммент"))
  256. (bot-send-message chat-id "Введите комментарий"
  257. :reply-markup (telegram-force-reply))
  258. (on-next-message chat-id
  259. (setf (pta-ledger:entry-comment entry) text)
  260. (entry-edit chat-id source-message-id entry)))))
  261. (loop for posting in (pta-ledger:entry-postings entry)
  262. collect
  263. (let ((this-posting posting))
  264. (list (inline-button ((pta-ledger:posting-account posting))
  265. (account-edit chat-id source-message-id entry this-posting
  266. (pta-ledger:posting-account this-posting)))
  267. (inline-button ((def (pta-ledger:render
  268. (pta-ledger:posting-amount posting))
  269. "Сумма"))
  270. (bot-send-message chat-id "Введите сумму"
  271. :reply-markup (telegram-force-reply))
  272. (on-next-message chat-id
  273. (let ((amount (pta-ledger:parse-amount text)))
  274. (setf (pta-ledger:posting-amount this-posting) amount)
  275. (entry-edit chat-id source-message-id entry)))))))
  276. (list (list (inline-button ("Готово")
  277. (telegram-edit-message-reply-markup
  278. (keyboard/entry chat-id entry)
  279. :chat-id chat-id :message-id source-message-id)))))))
  280. (defun accounts/nav (account accounts &optional (offset 0) (count 5))
  281. (let* ((len (1+ (length account)))
  282. (sep-pos (position #\: account :from-end t))
  283. (parent (when sep-pos (subseq account 0 sep-pos)))
  284. (head (when account (concatenate 'string account ":")))
  285. (descendants (remove-if #'(lambda (a)
  286. (when head
  287. (not (equal head
  288. (subseq a 0 (min (length a) len))))))
  289. accounts)))
  290. (if descendants
  291. (let* ((children (sort (remove-duplicates
  292. (mapcar #'(lambda (d)
  293. (subseq d 0 (or (position #\: d :start len)
  294. (length d))))
  295. descendants)
  296. :test #'equal) #'string<))
  297. (total (length children)))
  298. (when (stringp offset)
  299. (alexandria:when-let (off (position offset children :test #'equal))
  300. (setf offset (max 0 (- off (round count 2))))))
  301. (values account parent
  302. (mapcar
  303. #'(lambda (c)
  304. (let* ((needle (concatenate 'string c ":"))
  305. (n-l (length needle)))
  306. (cons c
  307. (not
  308. (find needle accounts :test #'equal
  309. :key #'(lambda (a)
  310. (subseq a 0 (min n-l (length a)))))))))
  311. (subseq children offset
  312. (min total (+ offset count))))
  313. (unless (zerop offset) (max 0 (- offset count)))
  314. (when (< (+ offset count) total) (+ offset count))))
  315. (when parent (accounts/nav parent accounts account)))))
  316. (defun account-edit (chat-id message-id entry posting account &optional (offset 0))
  317. (with-chat-journal (chat-id journal updated)
  318. (let* ((accounts (pta-ledger:journal-accounts journal))
  319. (nav-list (multiple-value-list
  320. (accounts/nav account accounts offset))))
  321. (telegram-edit-message-reply-markup
  322. (apply #'keyboard/account chat-id entry posting nav-list)
  323. :chat-id chat-id :message-id message-id))))
  324. (defun keyboard/account (chat-id entry posting account parent children prev next)
  325. (get-inline-keyboard
  326. chat-id
  327. (append
  328. (list (list (when account
  329. (inline-button (account)
  330. (setf (pta-ledger:posting-account posting) account)
  331. (entry-edit chat-id source-message-id entry)))
  332. (inline-button ("Ввести")
  333. (bot-send-message chat-id "Введите счёт"
  334. :reply-markup (telegram-force-reply))
  335. (on-next-message chat-id
  336. (let ((account (pta-ledger:parse-account text)))
  337. (if account
  338. (progn
  339. (setf (pta-ledger:posting-account posting) account)
  340. (entry-edit chat-id source-message-id entry))
  341. (bot-send-message chat-id "Не разобрал")))))))
  342. (loop for (acc . leaf) in children
  343. collect (let ((this-account acc))
  344. (list (if leaf
  345. (inline-button (this-account)
  346. (setf (pta-ledger:posting-account posting) this-account)
  347. (entry-edit chat-id source-message-id entry))
  348. (inline-button ((format nil "~A ..." this-account))
  349. (account-edit chat-id source-message-id entry posting
  350. this-account))))))
  351. (list (list (when prev
  352. (inline-button ("<<")
  353. (account-edit chat-id source-message-id entry posting
  354. account prev)))
  355. (when (or parent account)
  356. (inline-button ((or parent "ACC"))
  357. (account-edit chat-id source-message-id entry posting
  358. parent account)))
  359. (when next
  360. (inline-button (">>")
  361. (account-edit chat-id source-message-id entry posting
  362. account next))))))))