ledger.lisp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  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 ()
  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 (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 "Добавь журнал: uri - /ledger <url>; git - /ledger <remote> <path>"))))
  118. (defun ledger/handle-set-info (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 (format nil "Добавил журнал с ~D записями. Веб-хук для обновления: ~A"
  126. (length journal)
  127. (ledger/get-hook-url *chat-id*))))
  128. (pta-ledger:journal-failed (e)
  129. (bot-send-message (format nil "Не смог спарсить: ~A" e)))
  130. (dex:http-request-failed (e)
  131. (bot-send-message (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 *args*))
  135. (:otherwise (ledger/handle-info))))
  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 "Добавь журнал: uri - /ledger <url>; git - /ledger <remote> <path>"
  144. :chat-id ,chat-id)))))
  145. (defun ledger/handle-balance (query)
  146. (with-chat-journal (*chat-id* journal updated)
  147. (bot-send-message (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 :budget)
  155. (cond
  156. ((null *args*) (ledger/handle-balance (if (eql *cmd* :budget) "budget" "assets")))
  157. (:otherwise (ledger/handle-balance (spaced *args*)))))
  158. (defun ledger/handle-journal (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 (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 "date:thisweek"))
  171. (:otherwise (ledger/handle-journal (spaced *args*)))))
  172. (def-message-cmd-handler hander-add-report (:add_report)
  173. (bot-send-message "Введи название"
  174. :reply-markup (telegram-force-reply))
  175. (on-next-message
  176. (let ((name *text*))
  177. (bot-send-message "Введи запрос"
  178. :reply-markup (telegram-force-reply))
  179. (on-next-message
  180. (let ((query *text*))
  181. (pta-ledger:parse-query query) ;; Validate query
  182. (bot-send-message "Введи расписание, ex: (:day-of-week 0 :hour 10), (:day * :hour 10)"
  183. :reply-markup (telegram-force-reply))
  184. (on-next-message
  185. (let* ((schedule *text*))
  186. (add-chat-cron :ledger-report *chat-id* schedule name query)
  187. (bot-send-message "Добавил"))))))))
  188. (defun run-report (chat-id name query)
  189. (with-chat-journal (chat-id journal updated)
  190. (bot-send-message (text-chunks (split-sequence:split-sequence
  191. #\Newline
  192. (format nil "*~A*~%~%~A" name
  193. (pta-ledger:journal-balance journal query)))
  194. :text-sep "
  195. ")
  196. :parse-mode "markdown"
  197. :chat-id chat-id)))
  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. (format nil "Отчёты~%~%~{~A) ~A _~A_: ~A~^~%~}"
  205. (loop for (schedule name query) in crons
  206. for idx from 1
  207. append (list idx name schedule query)))
  208. :parse-mode "markdown"
  209. :reply-markup
  210. (get-inline-keyboard
  211. (append
  212. (loop for (schedule name query) in crons
  213. for idx from 0
  214. collect
  215. (let ((cron-index idx)
  216. (cron-name name))
  217. (list (inline-button ((format nil "Удалить '~A'" cron-name))
  218. (delete-chat-cron :ledger-report *source-chat-id* cron-index)
  219. (telegram-edit-message-reply-markup
  220. nil :chat-id *source-chat-id* :message-id *source-message-id*)
  221. (bot-send-message (format nil "Удалил *~A*" cron-name)
  222. :chat-id *source-chat-id*
  223. :parse-mode "markdown")))))
  224. (list (list (inline-button ("Отмена")
  225. (telegram-edit-message-reply-markup
  226. nil :chat-id *source-chat-id* :message-id *source-message-id*)))))))
  227. (bot-send-message
  228. "Отчётов пока нет"
  229. :reply-markup (telegram-reply-keyboard-markup (list (list (list :text "/add_report")))
  230. :one-time-keyboard t)))))
  231. (defun match-entry (text journal)
  232. (labels ((two-post (entries)
  233. (remove-if-not #'(lambda (e)
  234. (= 2 (length (pta-ledger:entry-postings e))))
  235. entries)))
  236. (let ((desc (two-post
  237. (pta-ledger:journal-entries journal (format nil "desc:'~A'" text)))))
  238. (if desc (car (last desc))
  239. (let ((comment (two-post
  240. (pta-ledger:journal-entries journal (format nil "comment:'~A'" text)))))
  241. (when comment (car (last comment))))))))
  242. (defvar *expenses-account-root* "expenses" "Expenses accounts root.")
  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-account-root*)
  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. (defun find-posting (entry root)
  263. (when (and entry root)
  264. (find root (pta-ledger:entry-postings entry)
  265. :test #'equal
  266. :key #'(lambda (p)
  267. (car (pta-ledger:account-parents
  268. (pta-ledger:posting-account p) :tree :t))))))
  269. (defvar *budget-account-root* "budget" "Budget accounts root. Extend entry with matching budget if set")
  270. (defvar *budget-search-date-query* "date:last30" "Date part of matching budget search")
  271. (defun extend-entry! (chat-id entry)
  272. (let ((expense (find-posting entry *expenses-account-root*))
  273. (budget (find-posting entry *budget-account-root*)))
  274. (when (and *budget-account-root* expense (or (null budget)
  275. (equal #\! (pta-ledger:posting-status budget))))
  276. (with-chat-journal (chat-id journal updated)
  277. (let* ((last-entries (pta-ledger:journal-entries journal (format nil "~A acct:^~A"
  278. *budget-search-date-query*
  279. (pta-ledger:posting-account expense))))
  280. (last-budget (some #'(lambda (e) (find-posting e *budget-account-root*))
  281. (reverse last-entries)))
  282. (expense-amount (car (pta-ledger:get-amounts expense (pta-ledger:entry-postings entry) :t))))
  283. (when last-budget
  284. (unless budget
  285. (setf budget (pta-ledger:make-posting :status #\! :virtual #\())
  286. (setf (pta-ledger:entry-postings entry)
  287. (append (pta-ledger:entry-postings entry)
  288. (list budget))))
  289. (setf (pta-ledger:posting-amount budget) (pta-ledger:make-amount
  290. :quantity (- (pta-ledger:amount-quantity expense-amount))
  291. :commodity (pta-ledger:amount-commodity expense-amount))
  292. (pta-ledger:posting-account budget) (pta-ledger:posting-account last-budget))))))
  293. entry))
  294. (def-webhook-handler ledger/handle-webhook ("ledger")
  295. (when (= 2 (length *paths*))
  296. (destructuring-bind (chat-id hmac) *paths*
  297. (let ((true-hmac (token-hmac chat-id)))
  298. (when (string= true-hmac hmac)
  299. (with-secret (info (list :ledger chat-id))
  300. (when info
  301. (let ((chat-id (parse-integer chat-id)))
  302. (log:info "Updating ledger for ~A" chat-id)
  303. (setf (gethash chat-id *ledger/chat-journals*) nil)
  304. (get-chat-journal-info chat-id info)
  305. "OK"))))))))
  306. ;; New entries
  307. (defun format-entry (entry)
  308. (let ((pta-ledger:*posting-length* 40))
  309. (format nil "```~%~A```" (pta-ledger:render entry))))
  310. (defun ledger/format-add-entry-message (from)
  311. (format nil "Ledger add from ~A ~A at ~A"
  312. (aget "first_name" from) (aget "last_name" from)
  313. (ledger/format-time (get-universal-time))))
  314. (defun ledger/process-add-entry (chat-id from entry)
  315. (with-secret (info (list :ledger chat-id))
  316. (if info
  317. (cond
  318. ((consp info)
  319. (handler-case (progn
  320. (ledger/add-git
  321. chat-id
  322. (car info) (cadr info)
  323. (pta-ledger:render entry)
  324. (ledger/format-add-entry-message from))
  325. (show-harshly))
  326. (error (e)
  327. (log:error "~A" e)
  328. "Не смог :(")))
  329. (:otherwise "Добавляю только в git журнал :("))
  330. "Добавь git журнал.")))
  331. (defun ledger/new-chat-entry (chat-id entry)
  332. (let ((entry (extend-entry! chat-id entry)))
  333. (bot-send-message
  334. (format-entry entry)
  335. :chat-id chat-id
  336. :parse-mode "markdown"
  337. :reply-markup (keyboard/entry entry))))
  338. (defun entry-edit (chat-id message-id entry)
  339. (let ((entry (extend-entry! chat-id entry)))
  340. (telegram-edit-message-text
  341. (format-entry entry)
  342. :chat-id chat-id :message-id message-id
  343. :parse-mode "markdown"
  344. :reply-markup (keyboard/edit-entry chat-id message-id entry))))
  345. (defun keyboard/entry (entry)
  346. (get-inline-keyboard
  347. (list
  348. (list (inline-button ("➕")
  349. (telegram-answer-callback-query *query-id* :text "Добавляю...")
  350. (telegram-send-message *source-chat-id* (ledger/process-add-entry
  351. *source-chat-id* *from* entry))
  352. (telegram-edit-message-reply-markup
  353. nil :chat-id *source-chat-id* :message-id *source-message-id*))
  354. (inline-button ("💲")
  355. (entry-edit *source-chat-id* *source-message-id* entry))
  356. (inline-button ("✖️")
  357. (telegram-delete-message *source-chat-id* *source-message-id*))))))
  358. (defun def (str default)
  359. (if (or (null str) (string= "" str)) default
  360. str))
  361. (defun keyboard/edit-entry (chat-id message-id entry)
  362. (get-inline-keyboard
  363. (append
  364. (list
  365. (list (inline-button ((format-date (pta-ledger:entry-date entry)))
  366. (bot-send-message "Введите дату" :chat-id chat-id
  367. :reply-markup (telegram-force-reply))
  368. (on-next-message
  369. (let ((date (pta-ledger:parse-date *text* (get-year
  370. (pta-ledger:entry-date entry)))))
  371. (if date
  372. (progn
  373. (setf (pta-ledger:entry-date entry) date)
  374. (entry-edit chat-id message-id entry))
  375. (bot-send-message "Не разобрал" :chat-id chat-id)))))
  376. (inline-button ((def (pta-ledger:entry-description entry) "Описание"))
  377. (bot-send-message "Введите описание" :chat-id chat-id
  378. :reply-markup (telegram-force-reply))
  379. (on-next-message
  380. (setf (pta-ledger:entry-description entry) *text*)
  381. (entry-edit chat-id message-id entry)))
  382. (inline-button ((def (pta-ledger:entry-comment entry) "Коммент"))
  383. (bot-send-message "Введите комментарий" :chat-id chat-id
  384. :reply-markup (telegram-force-reply))
  385. (on-next-message
  386. (setf (pta-ledger:entry-comment entry) *text*)
  387. (entry-edit chat-id message-id entry)))))
  388. (loop for posting in (pta-ledger:entry-postings entry)
  389. collect
  390. (let ((this-posting posting))
  391. (list (inline-button ((pta-ledger:posting-account posting))
  392. (account-edit chat-id *source-message-id* entry this-posting
  393. (pta-ledger:posting-account this-posting)))
  394. (inline-button ((def (pta-ledger:render
  395. (pta-ledger:posting-amount posting))
  396. "Сумма"))
  397. (bot-send-message "Введите сумму" :chat-id chat-id
  398. :reply-markup (telegram-force-reply))
  399. (on-next-message
  400. (let ((amount (pta-ledger:parse-amount *text*)))
  401. (setf (pta-ledger:posting-amount this-posting) amount
  402. (pta-ledger:posting-status this-posting) nil)
  403. (entry-edit chat-id message-id entry))))
  404. (inline-button ("❌")
  405. (setf (pta-ledger:entry-postings entry)
  406. (remove this-posting (pta-ledger:entry-postings entry)
  407. :test #'equalp))
  408. (entry-edit chat-id *source-message-id* entry)))))
  409. (list (list (inline-button ("Готово")
  410. (telegram-edit-message-reply-markup
  411. (keyboard/entry entry)
  412. :chat-id chat-id :message-id *source-message-id*)))))))
  413. (defun accounts/nav (account accounts &optional (offset 0) (count 5))
  414. (let* ((len (1+ (length account)))
  415. (sep-pos (position #\: account :from-end t))
  416. (parent (when sep-pos (subseq account 0 sep-pos)))
  417. (head (when account (concatenate 'string account ":")))
  418. (descendants (remove-if #'(lambda (a)
  419. (when head
  420. (not (equal head
  421. (subseq a 0 (min (length a) len))))))
  422. accounts)))
  423. (if descendants
  424. (let* ((children (sort (remove-duplicates
  425. (mapcar #'(lambda (d)
  426. (subseq d 0 (or (position #\: d :start len)
  427. (length d))))
  428. descendants)
  429. :test #'equal) #'string<))
  430. (total (length children)))
  431. (when (stringp offset)
  432. (let ((off (position offset children :test #'equal)))
  433. (setf offset (if off (max 0 (- off (round count 2))) 0))))
  434. (values account parent
  435. (mapcar
  436. #'(lambda (c)
  437. (let* ((needle (concatenate 'string c ":"))
  438. (n-l (length needle)))
  439. (cons c
  440. (not
  441. (find needle accounts :test #'equal
  442. :key #'(lambda (a)
  443. (subseq a 0 (min n-l (length a)))))))))
  444. (subseq children offset
  445. (min total (+ offset count))))
  446. (unless (zerop offset) (max 0 (- offset count)))
  447. (when (< (+ offset count) total) (+ offset count))))
  448. (when parent (accounts/nav parent accounts account)))))
  449. (defun account-edit (chat-id message-id entry posting account &optional (offset 0))
  450. (with-chat-journal (chat-id journal updated)
  451. (let* ((accounts (pta-ledger:journal-accounts journal))
  452. (nav-list (multiple-value-list
  453. (accounts/nav account accounts offset))))
  454. (telegram-edit-message-reply-markup
  455. (apply #'keyboard/account chat-id message-id entry posting nav-list)
  456. :chat-id chat-id :message-id message-id))))
  457. (defun keyboard/account (chat-id message-id entry posting account parent children prev next)
  458. (get-inline-keyboard
  459. (append
  460. (list (list (when account
  461. (inline-button (account)
  462. (setf (pta-ledger:posting-account posting) account
  463. (pta-ledger:posting-status posting) nil)
  464. (entry-edit chat-id *source-message-id* entry)))
  465. (inline-button ("Ввести")
  466. (bot-send-message "Введите счёт" :chat-id chat-id
  467. :reply-markup (telegram-force-reply))
  468. (on-next-message
  469. (let ((account (pta-ledger:parse-account *text*)))
  470. (if account
  471. (progn
  472. (setf (pta-ledger:posting-account posting) account
  473. (pta-ledger:posting-status posting) nil)
  474. (entry-edit chat-id message-id entry))
  475. (bot-send-message "Не разобрал" :chat-id chat-id)))))))
  476. (loop for (acc . leaf) in children
  477. collect (let ((this-account acc))
  478. (list (if leaf
  479. (inline-button (this-account)
  480. (setf (pta-ledger:posting-account posting) this-account
  481. (pta-ledger:posting-status posting) nil)
  482. (entry-edit chat-id *source-message-id* entry))
  483. (inline-button ((format nil "~A ..." this-account))
  484. (account-edit chat-id *source-message-id* entry posting
  485. this-account))))))
  486. (list (list (when prev
  487. (inline-button ("<<")
  488. (account-edit chat-id *source-message-id* entry posting
  489. account prev)))
  490. (when (or parent account)
  491. (inline-button ((or parent "ACC"))
  492. (account-edit chat-id *source-message-id* entry posting
  493. parent account)))
  494. (when next
  495. (inline-button (">>")
  496. (account-edit chat-id *source-message-id* entry posting
  497. account next))))))))
  498. (def-message-cmd-handler handler-create (:rub :usd :eur :thb :btc :czk)
  499. (cond
  500. ((>= (length *args*) 2)
  501. (ledger/new-chat-entry *chat-id* (create-entry *chat-id*
  502. (spaced (subseq *args* 1))
  503. (parse-float (car *args*))
  504. (symbol-name *cmd*))))
  505. (:otherwise (bot-send-message (format nil "/~A <amount> <description>" *cmd*)))))
  506. (defun get-harshly-state (journal account day next-day)
  507. (labels ((get-account-balance (query)
  508. (car (gethash account
  509. (apply #'pta-ledger:balance
  510. (pta-ledger::entries journal)
  511. (pta-ledger::parse-query query))))))
  512. (let* ((left-days (ceiling (- next-day day) 86400))
  513. (morning-balance (get-account-balance (format nil "~A date:-~A" account (format-date day))))
  514. (balance (get-account-balance (format nil "~A date:-~A" account (format-date (+ day pta-ledger::+day+)))))
  515. (today-amount (get-account-balance (format nil "amt:<0 ~A date:~A" account (format-date day))))
  516. (daily-amount (if (zerop left-days) balance
  517. (pta-ledger:make-amount
  518. :quantity (/ (pta-ledger:amount-quantity morning-balance) left-days)
  519. :commodity (pta-ledger:amount-commodity morning-balance))))
  520. (left-today (pta-ledger:make-amount
  521. :quantity (+ (pta-ledger:amount-quantity daily-amount)
  522. (if today-amount (pta-ledger:amount-quantity today-amount) 0))
  523. :commodity (pta-ledger:amount-commodity morning-balance)))
  524. (overspent-today (< (pta-ledger:amount-quantity left-today) 0))
  525. (overspent-daily (when (and overspent-today (> left-days 0))
  526. (pta-ledger:make-amount
  527. :quantity (/ (pta-ledger:amount-quantity balance) (1- left-days))
  528. :commodity (pta-ledger:amount-commodity balance)))))
  529. (list overspent-today left-days balance daily-amount today-amount left-today overspent-daily))))
  530. (defun format-harshly-state (state)
  531. (destructuring-bind (overspent-today left-days balance daily-amount today-amount left-today overspent-daily)
  532. state
  533. (if overspent-today
  534. (apply #'format nil "До зарплаты ~A дн, осталось ~A. Сегодня покутил на ~a и осталось теперь по ~a в день"
  535. left-days
  536. (mapcar #'pta-ledger:render (list balance today-amount overspent-daily)))
  537. (if today-amount
  538. (apply #'format nil "До зарплаты ~a дн, осталось ~A. Это по ~A в день. Сегодня уже слито ~a и осталось на сегодня ~A."
  539. left-days
  540. (mapcar #'pta-ledger:render (list balance daily-amount today-amount left-today)))
  541. (apply #'format nil "До зарплаты ~a дн, осталось ~A. Это по ~A в день, на сегодня полностью."
  542. left-days
  543. (mapcar #'pta-ledger:render (list balance daily-amount)))))))
  544. (defvar *harshly-account* "assets:Raiffeisen:Debit")
  545. (defvar *harshly-payday-schedule* '(:day-of-month (member 5 20)))
  546. (defun show-harshly ()
  547. (with-chat-journal (*chat-id* journal updated)
  548. (format-harshly-state
  549. (get-harshly-state
  550. journal *harshly-account*
  551. (get-universal-time)
  552. (clon:next-time (apply #'clon:make-typed-cron-schedule
  553. *harshly-payday-schedule*))))))
  554. (def-message-cmd-handler handler-harshly (:harshly :harsh)
  555. (bot-send-message (show-harshly)))