(in-package :cl-user) (defpackage chatikbot.plugins.ledger (:use :cl :chatikbot.common)) (in-package :chatikbot.plugins.ledger) (eval-when (:compile-toplevel :load-toplevel :execute) (ql:quickload '(:pta-ledger :legit))) (defsetting *ledger/default-timezone* -3 "Default timezone for time display. GMT+3") (defvar *ledger/chat-journals* (make-hash-table)) (defvar *git-repo-locks* (make-hash-table :test #'equal)) (defun git-get-repo-lock (repo) (let ((key (legit:location repo))) (setf key (etypecase key (string key) (pathname (namestring key)))) (or (gethash key *git-repo-locks*) (setf (gethash key *git-repo-locks*) (bt:make-recursive-lock key))))) (defun git-get-repo (location remote) (let ((repo (make-instance 'legit:repository :location location))) (bt:with-recursive-lock-held ((git-get-repo-lock repo)) (legit:init repo :remote remote :if-does-not-exist :clone)) repo)) (defsetting *git-repos-root* "/tmp/ledger-repos/") (defun git-get-chat-location (chat-id remote) (namestring (uiop:ensure-directory-pathname (merge-pathnames (format nil "~A-~A" chat-id (token-hmac remote)) *git-repos-root*)))) (defun git-read-latest-file (repo path) (bt:with-recursive-lock-held ((git-get-repo-lock repo)) (legit:fetch repo :branch "master" :remote "origin") (legit:reset repo :hard t :to "origin/master") (uiop:read-file-string (merge-pathnames path (legit:location repo))))) (defun ledger/refresh-git (chat-id remote path) (let* ((location (git-get-chat-location chat-id remote)) (repo (git-get-repo location remote)) (content (git-read-latest-file repo path)) (journal (pta-ledger:parse-journal content)) (updated (legit:current-age repo))) (setf (gethash chat-id *ledger/chat-journals*) (cons journal updated)))) (defun git-append-latest-file (repo path text message) (bt:with-recursive-lock-held ((git-get-repo-lock repo)) (let ((repo-path (merge-pathnames path (legit:location repo)))) (dotimes (tries 5) (let ((current (or (ignore-errors (git-read-latest-file repo path)) ""))) (uiop/stream:with-output-file (s repo-path :if-exists :supersede :if-does-not-exist :create) (format s "~A~A" current text))) (legit:add repo (namestring repo-path)) (legit:commit repo message) (handler-case (progn (legit:push repo) (return-from git-append-latest-file path)) (legit:git-error ()))) (error "Tried 5 times to push ~A to ~A" path (legit:remote-url repo))))) (defun ledger/add-git (chat-id remote path text message) (let* ((location (git-get-chat-location chat-id remote)) (repo (git-get-repo location remote))) (git-append-latest-file repo path (format nil "~%~A~%" text) message))) (defun ledger/get-hook-url (chat-id) (get-webhook-url "ledger" chat-id (token-hmac (write-to-string chat-id)))) (defun ledger/format-uri (url) (let ((uri (quri:uri url))) (quri:render-uri (quri:make-uri :userinfo (when (quri:uri-userinfo uri) "*:*") :defaults url)))) (defun ledger/format-time (universal-time) (when universal-time (multiple-value-bind (sec min hour day month year dow dst-p tz) (decode-universal-time universal-time *ledger/default-timezone*) (declare (ignore dow dst-p tz)) (format nil "~4,'0D-~2,'0D-~2,'0D ~2,'0D:~2,'0D:~2,'0D" year month day hour min sec)))) (defun format-date (ut) (multiple-value-bind (sec min hour day month year) (decode-universal-time ut) (declare (ignore sec min hour)) (format nil "~4,'0D-~2,'0D-~2,'0D" year month day))) (defun get-year (ut) (multiple-value-bind (sec min hour day month year) (decode-universal-time ut) (declare (ignore sec min hour day month)) year)) (defun ledger/refresh-uri (chat-id uri) (setf (gethash chat-id *ledger/chat-journals*) (cons (pta-ledger:parse-journal (http-request uri)) (get-universal-time)))) (defun get-chat-journal-info (chat-id &optional info) (labels ((process-info (info) (cond ((stringp info) (ledger/refresh-uri chat-id info)) ((consp info) (apply #'ledger/refresh-git chat-id info)) (:otherwise nil)))) (let ((journal-info (gethash chat-id *ledger/chat-journals*))) (if journal-info journal-info (if info (process-info info) (with-secret (info (list :ledger chat-id)) (process-info info))))))) (Defun ledger/handle-info (chat-id) (with-secret (info (list :ledger chat-id)) (if info (destructuring-bind (journal . ut) (get-chat-journal-info chat-id info) (let ((uri (cond ((consp info) (car info)) ((stringp info) info)))) (bot-send-message chat-id (format nil "Журнал с ~D записями, из ~A, обновлён ~A.~%Веб-хук: ~A" (length journal) (ledger/format-uri uri) (ledger/format-time ut) (ledger/get-hook-url chat-id)) :disable-web-preview t))) (bot-send-message chat-id "Добавь журнал: uri - /ledger ; git - /ledger ")))) (defun ledger/handle-set-info (chat-id info) (setf (gethash chat-id *ledger/chat-journals*) nil) (handler-case (destructuring-bind (journal . ut) (get-chat-journal-info chat-id info) (declare (ignore ut)) (secret-set (list :ledger chat-id) info) (bot-send-message chat-id (format nil "Добавил журнал с ~D записями. Веб-хук для обновления: ~A" (length journal) (ledger/get-hook-url chat-id)))) (pta-ledger:journal-failed (e) (bot-send-message chat-id (format nil "Не смог спарсить: ~A" e))) (dex:http-request-failed (e) (bot-send-message chat-id (format nil "Не смог в урл: ~A" (dex:response-body e)))))) (def-message-cmd-handler handler-ledger (:ledger) (cond ((<= 1 (length args) 2) (ledger/handle-set-info chat-id args)) (:otherwise (ledger/handle-info chat-id)))) (defmacro with-chat-journal ((chat-id journal updated) &body body) (let ((info (gensym "info"))) `(let ((,info (get-chat-journal-info ,chat-id))) (if ,info (destructuring-bind (,journal . ,updated) ,info (declare (ignorable ,journal ,updated)) ,@body) (bot-send-message ,chat-id "Добавь журнал: uri - /ledger ; git - /ledger "))))) (defun ledger/handle-balance (chat-id query) (with-chat-journal (chat-id journal updated) (bot-send-message chat-id (format nil "```~%~A~%```Обновлено: ~A" (pta-ledger:journal-balance journal query) (ledger/format-time updated)) :parse-mode "markdown"))) (def-message-cmd-handler handler-balance (:balance :bal) (cond ((null args) (ledger/handle-balance chat-id "assets")) (:otherwise (ledger/handle-balance chat-id (spaced args))))) (defun ledger/handle-journal (chat-id query) (with-chat-journal (chat-id journal updated) (let* ((pta-ledger:*posting-length* 40) (entries (pta-ledger:journal-print journal query)) (len (length entries)) (count (min len 20))) (bot-send-message chat-id (format nil "```~%~{~A~^ ~%~%~}```Обновлено: ~A" (subseq entries (- len count) len) (ledger/format-time updated)) :parse-mode "markdown")))) (def-message-cmd-handler handler-journal (:journal) (cond ((null args) (ledger/handle-journal chat-id "date:thisweek")) (:otherwise (ledger/handle-journal chat-id (spaced args))))) (defun match-entry (text journal) (labels ((two-post (entries) (remove-if-not #'(lambda (e) (= 2 (length (pta-ledger:entry-postings e)))) entries))) (let ((desc (two-post (pta-ledger:journal-entries journal (format nil "desc:'~A'" text))))) (if desc (car (last desc)) (let ((comment (two-post (pta-ledger:journal-entries journal (format nil "comment:'~A'" text))))) (when comment (car (last comment)))))))) (defun create-entry (chat-id text amount currency) (with-chat-journal (chat-id journal updated) (let* ((old (match-entry text journal)) (new (or (when old (pta-ledger:clone-entry old)) (pta-ledger:make-entry :description text :postings (list (pta-ledger:make-posting :account "expenses") (pta-ledger:make-posting))))) (postings (pta-ledger:entry-postings new))) (setf (pta-ledger:entry-date new) (get-universal-time) (pta-ledger:posting-amount (car postings)) (pta-ledger:make-amount :quantity amount :commodity currency) (pta-ledger:posting-amount (cadr postings)) (pta-ledger:make-amount :quantity (- amount) :commodity currency) (pta-ledger:posting-account (cadr postings)) (format nil "assets:Cash:~A" currency)) new))) (def-message-cmd-handler handler-create (:rub :usd :eur :thb :btc) (cond ((>= (length args) 2) (ledger/new-chat-entry chat-id (create-entry chat-id (spaced (subseq args 1)) (parse-float (car args)) (symbol-name cmd)))) (:otherwise (bot-send-message chat-id (format nil "/~A " cmd))))) (def-webhook-handler ledger/handle-webhook ("ledger") (when (= 2 (length paths)) (destructuring-bind (chat-id hmac) paths (let ((true-hmac (token-hmac chat-id))) (when (string= true-hmac hmac) (with-secret (info (list :ledger chat-id)) (when info (let ((chat-id (parse-integer chat-id))) (log:info "Updating ledger for ~A" chat-id) (setf (gethash chat-id *ledger/chat-journals*) nil) (get-chat-journal-info chat-id info) "OK")))))))) ;; New entries (defun format-entry (entry) (let ((pta-ledger:*posting-length* 40)) (format nil "```~%~A```" (pta-ledger:render entry)))) (defun ledger/format-add-entry-message (from) (format nil "Ledger add from ~A ~A at ~A" (aget "first_name" from) (aget "last_name" from) (ledger/format-time (get-universal-time)))) (defun ledger/process-add-entry (chat-id from entry) (with-secret (info (list :ledger chat-id)) (if info (cond ((consp info) (handler-case (progn (ledger/add-git chat-id (car info) (cadr info) (pta-ledger:render entry) (ledger/format-add-entry-message from)) "Добавил!") (error (e) (log:error "~A" e) "Не смог :("))) (:otherwise "Добавляю только в git журнал :(")) "Добавь git журнал."))) (defun ledger/new-chat-entry (chat-id entry) (bot-send-message chat-id (format-entry entry) :parse-mode "markdown" :reply-markup (keyboard/entry chat-id entry))) (defun entry-edit (chat-id message-id entry) (telegram-edit-message-text (format-entry entry) :chat-id chat-id :message-id message-id :parse-mode "markdown" :reply-markup (keyboard/edit-entry chat-id entry))) (defun keyboard/entry (chat-id entry) (get-inline-keyboard chat-id (list (list (inline-button ("➕") (telegram-answer-callback-query query-id :text "Добавляю...") (telegram-send-message source-chat-id (ledger/process-add-entry source-chat-id from entry)) (telegram-edit-message-reply-markup nil :chat-id source-chat-id :message-id source-message-id)) (inline-button ("💲") (entry-edit source-chat-id source-message-id entry)) (inline-button ("✖️") (telegram-delete-message source-chat-id source-message-id)))))) (defun def (str default) (if (or (null str) (string= "" str)) default str)) (defun keyboard/edit-entry (chat-id entry) (get-inline-keyboard chat-id (append (list (list (inline-button ((format-date (pta-ledger:entry-date entry))) (bot-send-message chat-id "Введите дату" :reply-markup (telegram-force-reply)) (on-next-message chat-id (let ((date (pta-ledger:parse-date text (get-year (pta-ledger:entry-date entry))))) (if date (progn (setf (pta-ledger:entry-date entry) date) (entry-edit chat-id source-message-id entry)) (bot-send-message chat-id "Не разобрал"))))) (inline-button ((def (pta-ledger:entry-description entry) "Описание")) (bot-send-message chat-id "Введите описание" :reply-markup (telegram-force-reply)) (on-next-message chat-id (setf (pta-ledger:entry-description entry) text) (entry-edit chat-id source-message-id entry))) (inline-button ((def (pta-ledger:entry-comment entry) "Коммент")) (bot-send-message chat-id "Введите комментарий" :reply-markup (telegram-force-reply)) (on-next-message chat-id (setf (pta-ledger:entry-comment entry) text) (entry-edit chat-id source-message-id entry))))) (loop for posting in (pta-ledger:entry-postings entry) collect (let ((this-posting posting)) (list (inline-button ((pta-ledger:posting-account posting)) (account-edit chat-id source-message-id entry this-posting (pta-ledger:posting-account this-posting))) (inline-button ((def (pta-ledger:render (pta-ledger:posting-amount posting)) "Сумма")) (bot-send-message chat-id "Введите сумму" :reply-markup (telegram-force-reply)) (on-next-message chat-id (let ((amount (pta-ledger:parse-amount text))) (setf (pta-ledger:posting-amount this-posting) amount) (entry-edit chat-id source-message-id entry))))))) (list (list (inline-button ("Готово") (telegram-edit-message-reply-markup (keyboard/entry chat-id entry) :chat-id chat-id :message-id source-message-id))))))) (defun accounts/nav (account accounts &optional (offset 0) (count 5)) (let* ((len (1+ (length account))) (sep-pos (position #\: account :from-end t)) (parent (when sep-pos (subseq account 0 sep-pos))) (head (when account (concatenate 'string account ":"))) (descendants (remove-if #'(lambda (a) (when head (not (equal head (subseq a 0 (min (length a) len)))))) accounts))) (if descendants (let* ((children (sort (remove-duplicates (mapcar #'(lambda (d) (subseq d 0 (or (position #\: d :start len) (length d)))) descendants) :test #'equal) #'string<)) (total (length children))) (when (stringp offset) (let ((off (position offset children :test #'equal))) (setf offset (if off (max 0 (- off (round count 2))) 0)))) (values account parent (mapcar #'(lambda (c) (let* ((needle (concatenate 'string c ":")) (n-l (length needle))) (cons c (not (find needle accounts :test #'equal :key #'(lambda (a) (subseq a 0 (min n-l (length a))))))))) (subseq children offset (min total (+ offset count)))) (unless (zerop offset) (max 0 (- offset count))) (when (< (+ offset count) total) (+ offset count)))) (when parent (accounts/nav parent accounts account))))) (defun account-edit (chat-id message-id entry posting account &optional (offset 0)) (with-chat-journal (chat-id journal updated) (let* ((accounts (pta-ledger:journal-accounts journal)) (nav-list (multiple-value-list (accounts/nav account accounts offset)))) (telegram-edit-message-reply-markup (apply #'keyboard/account chat-id entry posting nav-list) :chat-id chat-id :message-id message-id)))) (defun keyboard/account (chat-id entry posting account parent children prev next) (get-inline-keyboard chat-id (append (list (list (when account (inline-button (account) (setf (pta-ledger:posting-account posting) account) (entry-edit chat-id source-message-id entry))) (inline-button ("Ввести") (bot-send-message chat-id "Введите счёт" :reply-markup (telegram-force-reply)) (on-next-message chat-id (let ((account (pta-ledger:parse-account text))) (if account (progn (setf (pta-ledger:posting-account posting) account) (entry-edit chat-id source-message-id entry)) (bot-send-message chat-id "Не разобрал"))))))) (loop for (acc . leaf) in children collect (let ((this-account acc)) (list (if leaf (inline-button (this-account) (setf (pta-ledger:posting-account posting) this-account) (entry-edit chat-id source-message-id entry)) (inline-button ((format nil "~A ..." this-account)) (account-edit chat-id source-message-id entry posting this-account)))))) (list (list (when prev (inline-button ("<<") (account-edit chat-id source-message-id entry posting account prev))) (when (or parent account) (inline-button ((or parent "ACC")) (account-edit chat-id source-message-id entry posting parent account))) (when next (inline-button (">>") (account-edit chat-id source-message-id entry posting account next))))))))