236 Commits
0.4.0 ... 0.6.0

Author SHA1 Message Date
8eabf3d1c8 Merge pull request 'Fix input on mobile' (#44) from mobile-input into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #44
2022-03-15 22:12:31 +01:00
f0084b683e Fix ts issues
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2022-03-15 21:11:24 +00:00
84c95d0c4e Bring submit button to work
Some checks failed
continuous-integration/drone/push Build is failing
continuous-integration/drone/pr Build is failing
2022-03-15 21:05:12 +00:00
6576c994c9 Improve layout 2022-03-15 20:21:34 +00:00
a552983ac4 Merge pull request 'Setup and enable ESLint' (#43) from eslint into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #43
2022-03-15 21:11:01 +01:00
f99efe0e8e Finish Rename
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2022-03-15 20:09:59 +00:00
e1b6056d77 Fix more imports
Some checks failed
continuous-integration/drone/pr Build is failing
continuous-integration/drone/push Build is failing
2022-03-15 20:08:36 +00:00
94329ac331 Fix imports in router
Some checks failed
continuous-integration/drone/push Build is failing
continuous-integration/drone/pr Build is failing
2022-03-15 20:05:42 +00:00
bfa67578cf Fix tsc issues
Some checks failed
continuous-integration/drone/push Build is failing
continuous-integration/drone/pr Build is failing
2022-03-15 20:04:01 +00:00
eae196aa69 Run eslint in CI 2022-03-15 20:00:12 +00:00
d2dd7d5280 Ignore left-over issues
Some checks failed
continuous-integration/drone/pr Build is failing
continuous-integration/drone/push Build is failing
2022-03-15 19:58:16 +00:00
f707197f42 Ignore index.css 2022-03-15 19:58:03 +00:00
66322ebd86 Fix some linter issues 2022-03-15 19:50:49 +00:00
3ea90a5ebe Run eslint with autofix 2022-03-15 12:55:22 +00:00
d717ef1b4d Use spaces 2022-03-15 12:52:23 +00:00
61a534610f Run prettier
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2022-03-15 12:50:20 +00:00
d8d713f841 Change prettier configuration 2022-03-15 12:50:20 +00:00
7ac06012ec Initialize eslint 2022-03-15 12:50:20 +00:00
9af412a8bd Merge pull request 'Hide hidden categories from autocomplete results' (#42) from hide-hidden-categories into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #42
2022-03-15 13:50:10 +01:00
3b61028576 Hide hidden categories from searchresults 2022-03-15 13:50:10 +01:00
87b78e7b67 Make search queries case insensitive 2022-03-15 13:50:10 +01:00
6a71d9643c Merge pull request 'Persist last_reconciled instead of using last transactions date' (#41) from reconciled-as-field into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #41
2022-03-14 21:01:08 +01:00
450324d29e Extract AccountWithReconciled
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2022-03-14 19:48:45 +00:00
6f4e286b7a Initialize last_reconciled from transactions 2022-03-14 19:46:21 +00:00
324e13f5c5 Show age in days 2022-03-14 19:34:17 +00:00
0201b368d4 Add column and use instead of last transactions date
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2022-03-14 19:26:54 +00:00
984a2aa296 Merge pull request 'Show sums for category groups' (#40) from category-group-summary into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #40
2022-03-14 20:15:20 +01:00
d1a0296a58 Add margin before group
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2022-03-14 19:12:46 +00:00
d9efa9f4a1 Improve layout of groups 2022-03-14 19:10:09 +00:00
b176ce26ba Implement summing per category group
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2022-03-05 22:23:41 +00:00
97de326527 Use new UpdateAssignmentWithDifference for ynab-import to prevent errors on duplicates 2022-03-05 22:23:13 +00:00
a62ab543b0 Merge pull request 'Implement basic budgeting input' (#39) from budgeting into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #39
2022-03-05 22:12:14 +01:00
244333adbc Fix null reference in GetIncomeAvailable
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2022-03-05 20:48:36 +00:00
67ef4745a0 Handle login redirect 2022-03-05 20:48:27 +00:00
3856e8a8a5 Update assignment on modification
All checks were successful
continuous-integration/drone/push Build is passing
2022-03-04 22:24:50 +00:00
db96fddde2 Implement update Assignment on backend 2022-03-04 22:24:38 +00:00
ecb801b2f2 Move getDate to util file 2022-03-04 21:56:24 +00:00
fd6b77f154 Replace id column with natural PK 2022-03-04 21:56:12 +00:00
442e87234c Show available income in Budgeting header
All checks were successful
continuous-integration/drone/push Build is passing
2022-03-04 21:31:13 +00:00
caf39fe5ea Set Available balance of income category 2022-03-04 21:18:44 +00:00
0dde94f855 Remove logging 2022-03-04 21:15:24 +00:00
34bbdf48b7 Also return income category 2022-03-04 21:13:59 +00:00
1e495a5e47 Remove unneeded loop 2022-03-04 21:13:50 +00:00
fc29b1409d Use in-place additions more 2022-03-04 21:13:38 +00:00
8ecfd6b87a Use in-place calculations 2022-03-04 20:55:38 +00:00
d89e702669 Move sidebar layout to BudgetSidebar 2022-03-04 20:55:14 +00:00
3795150508 Implement numeric operations in-place 2022-03-04 20:54:23 +00:00
67c013799d Calculate available balance locally 2022-03-03 10:44:50 +00:00
0038db90ac Merge pull request 'Fix docker build' (#38) from docker-build into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #38
2022-03-02 23:55:29 +01:00
9759a7cc1e Fix docker build
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2022-03-02 22:55:21 +00:00
81c31a3d5f Merge pull request 'Cleanup' (#37) from cleanup into master
Some checks failed
continuous-integration/drone/push Build is failing
Reviewed-on: #37
2022-03-02 23:53:15 +01:00
38e21786a7 Fix app bar for small screens
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2022-03-02 22:52:12 +00:00
971c3d3be5 Improve sidebar and show next to appbar instead of below 2022-03-02 22:52:12 +00:00
946f14c1cc Fix const 2022-03-02 22:51:20 +00:00
9ce0da0182 Move CSS to _index.css 2022-03-02 22:51:20 +00:00
4c93e4635d Extract const for default expiration 2022-03-02 22:51:20 +00:00
f3a50c790b Hide .task, build and dist folders 2022-03-02 22:51:20 +00:00
0c5f68ed80 Hide files generated by sqlc 2022-03-02 22:51:20 +00:00
7fdd8bd935 Split jwt into two files 2022-03-02 22:51:20 +00:00
d4287f8aac Remove example config 2022-03-02 22:51:20 +00:00
6712af10d9 Move production Dockerfile to docker directory 2022-03-02 22:51:20 +00:00
70edb382e1 Move compose files to docker directory 2022-03-02 22:51:20 +00:00
390a042441 Rename development Dockerfile and build script 2022-03-02 22:51:20 +00:00
e8028dae34 Remove woodpecker config 2022-03-02 22:51:20 +00:00
fc249adc9e Remove Earthfile 2022-03-02 22:51:20 +00:00
c186a14644 go mod tidy 2022-03-02 22:51:20 +00:00
8a27303670 Remove earthignore 2022-03-02 22:51:20 +00:00
44e9bb6ec0 Merge pull request 'Implement closing of accounts' (#36) from closed-accounts into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #36
2022-03-02 22:54:02 +01:00
42d431ba8b Fix modal layout for dark theme
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2022-03-02 21:52:35 +00:00
3727061065 Prevent closing of accounts with balance 2022-03-02 21:52:16 +00:00
c7a8adb3ab Remove closed account from sidebar
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2022-03-02 21:22:15 +00:00
29f534bf10 Hide closed accounts menuentry 2022-03-02 21:22:06 +00:00
15381c84f6 Navigate to budgeting from closed account 2022-03-02 21:21:56 +00:00
a0cabbf4f7 Pass is_open to API from EditAccount 2022-03-02 21:16:06 +00:00
f26ee8f472 Add ability to change is_open from API 2022-03-02 21:15:56 +00:00
4fb3c2a335 Show is_open in EditAccount 2022-03-02 21:14:12 +00:00
8899ff5772 Return and filter by is_open 2022-03-02 21:14:00 +00:00
347a0c9e50 Add column is_open to accounts 2022-03-02 21:13:42 +00:00
66b8e1f69f Fix edit-accounts' font being off 2022-03-02 21:07:53 +00:00
5d1b49c896 Merge pull request 'Implement custom checkbox' (#35) from checkbox into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #35
2022-03-02 21:34:27 +01:00
42dc51fe9a Improve layout of Reconcilation
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2022-03-02 20:33:01 +00:00
1ca95f8768 Remove old logging calls
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2022-03-02 20:06:33 +00:00
a73f7c2934 Bind to value instead of using v-model 2022-03-02 20:06:16 +00:00
489aa88c4b Add custom checkbox component 2022-03-02 20:06:06 +00:00
7b5b16c1b2 Merge pull request 'Design fixes for dark mode' (#34) from design-fixes into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #34
2022-03-02 20:54:26 +01:00
29cfeb6fa6 Use Input component for all inputs except file-input 2022-03-02 20:54:26 +01:00
42baafd273 Invert if 2022-03-02 20:54:26 +01:00
1e79f193be Extract Input component and add some dark color tags 2022-03-02 20:54:26 +01:00
f0ec7fb30d Merge pull request 'Show symbol for accounts that haven't been recently reconciled' (#33) from recently-reconciled into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #33
2022-03-02 20:53:41 +01:00
034f4f2a90 Show * in sidebar for unreconciled accounts
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2022-03-02 19:25:07 +00:00
51ece59866 Calculate last reconciled date on backend 2022-03-02 19:24:30 +00:00
bbfda6f402 Improve layout of balances header
All checks were successful
continuous-integration/drone/push Build is passing
2022-03-01 20:59:06 +00:00
2b3afbf448 Merge pull request 'Implement simple dark mode' (#32) from dark-mode into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #32
2022-03-01 21:48:05 +01:00
a53c3d23a4 Implement simple dark mode
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2022-03-01 20:47:55 +00:00
c899c21256 Merge pull request 'Fix budget data being one month off' (#31) from hotfix-budgeting-off-by-one into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #31
2022-03-01 21:38:23 +01:00
cccc948048 Fix budget data being one month off
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2022-03-01 20:38:12 +00:00
e8a0670a83 Merge pull request 'Improve mobile usability' (#30) from mobile-usability into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #30
2022-03-01 21:33:07 +01:00
9638676b8f Add new transaction button on small screens
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2022-03-01 20:32:05 +00:00
08bda8d14f Make buttonText optional 2022-03-01 20:31:22 +00:00
d0ade0f2f1 Remove height from Card 2022-03-01 20:31:13 +00:00
466239ce11 Remove defaults from Button 2022-03-01 20:31:01 +00:00
d52e5c63d4 Hide Input on small screens and match columns 2022-03-01 20:12:27 +00:00
3dcb362372 Prevent wrap in balance-labels 2022-03-01 20:12:11 +00:00
67c9b53e91 Extract date to own row on small screens 2022-03-01 20:11:59 +00:00
7c08ddacb7 Remove widths from TransactionInputRow and use Button 2022-03-01 20:11:41 +00:00
ecbb85aeaa Decrease displayed information 2022-03-01 18:52:04 +00:00
3696bbde43 Check empty secret in other spots
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2022-03-01 18:37:07 +00:00
09a227d08d Wrap error for more details 2022-03-01 18:34:22 +00:00
dae6185857 Prevent startup on empty secret
Some checks failed
continuous-integration/drone/push Build is failing
2022-03-01 18:33:46 +00:00
6dd8a3791f Use grid instead of table 2022-03-01 08:36:03 +00:00
18149eef8b Hide Leftover on small screens 2022-03-01 08:33:01 +00:00
f0f97a2e77 Merge pull request 'Fix budgeting not being openable' (#29) from hotfix-budget into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #29
2022-03-01 09:11:33 +01:00
71b2f8a9a3 Fix budgeting not being openable
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2022-02-28 20:14:27 +00:00
8f666a0f26 Merge pull request 'Improve Transactions handling' (#28) from transactions into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #28
2022-02-28 14:28:38 +01:00
2b9c76960e Run vue-tsc on CI build
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2022-02-28 13:27:02 +00:00
7fd057f9f6 Remove vuetify plugin 2022-02-28 13:25:14 +00:00
a9be9367a9 Use transactionid for TransactionRow 2022-02-28 13:23:30 +00:00
bc75757ac7 Complete migration two transactions store 2022-02-28 13:13:21 +00:00
a3e12df2e2 Extract transactions store 2022-02-28 13:09:15 +00:00
024c5e0a1c Refactor transactions store 2022-02-28 13:03:53 +00:00
27372199f7 Improve logger 2022-02-28 09:34:57 +00:00
b3b878854e Extract GetAccount 2022-02-28 09:28:53 +00:00
bbb12a788d Improve layout of Account header 2022-02-28 07:58:51 +00:00
7dfbef60a4 Fix date input getting stuck on invalid input 2022-02-27 22:10:47 +00:00
d8a96535dc Merge pull request 'Fix GroupID not being set for original transaction' (#27) from hotfix-transfers into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #27
2022-02-27 22:53:19 +01:00
ce26e76e8f Fix GroupID not being set for original transaction
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2022-02-27 21:44:15 +00:00
6b3ac199fc Merge pull request 'Implement reconciliation' (#26) from reconcilation into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #26
2022-02-27 22:16:01 +01:00
4c6d21c2b4 Improve editing and creating of transactions
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2022-02-27 21:15:46 +00:00
faef975f1a Pass amount as string and add transaction correctly
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2022-02-27 21:06:34 +00:00
bd686e0c00 Remove duplicate order by 2022-02-27 21:06:11 +00:00
4844889e0b Disable nilnil linter for CreateReconcilationTransaction 2022-02-27 20:53:57 +00:00
2775578713 Extract method CreateReconcilationTransaction 2022-02-27 20:50:26 +00:00
27dd6e923c Actually handle passed reconciliation amount 2022-02-27 20:45:18 +00:00
2cf6b815bf Use view everywhere 2022-02-27 20:45:02 +00:00
81aacf339e Extract view for transactions 2022-02-27 20:35:10 +00:00
16bcf516f6 Add ReconcilationTransactionAmount 2022-02-27 20:34:10 +00:00
52503a4c92 Improve frontend 2022-02-27 20:02:57 +00:00
b4321395d9 Implement backend for reconcilation 2022-02-27 20:02:23 +00:00
d7058a49b0 Add SQL Query for update status 2022-02-27 20:01:35 +00:00
eb9fc722aa Show reconcile button and current reconciling-balance 2022-02-27 19:20:13 +00:00
511081298e Merge pull request 'Split account balances in working, cleared and reconciled' (#25) from account-balances into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #25
2022-02-27 19:33:44 +01:00
422a74704b Show all balances in Account view
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2022-02-27 18:32:00 +00:00
c4995bcbaf Show cleared balance by default 2022-02-27 15:22:54 +00:00
79fd95e152 Calculate working, cleared and reconciled balance 2022-02-27 15:22:18 +00:00
af8fda178d Merge pull request 'Improve CI image' (#24) from ci-improvements into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #24
2022-02-26 00:01:31 +01:00
71f4d2384b Fetch image only if not in PR
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2022-02-25 23:00:15 +00:00
eb52bd5def Fix pull definition
Some checks reported errors
continuous-integration/drone/pr Build encountered an error
continuous-integration/drone/push Build is passing
2022-02-25 22:57:19 +00:00
adcb64f4ad Remove unused method
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2022-02-25 22:55:48 +00:00
a73c5ce04b Build images only on master push or tag
Some checks failed
continuous-integration/drone/pr Build is failing
continuous-integration/drone/push Build is failing
2022-02-25 22:54:51 +00:00
52bb343402 Reorganize routes and remove legacy ones
Some checks failed
continuous-integration/drone/pr Build is failing
continuous-integration/drone/push Build is failing
2022-02-25 22:52:08 +00:00
27ce8d250f Move WORKDIR call
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2022-02-25 22:44:09 +00:00
408207df92 Fix yarn call not doing anything
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2022-02-25 22:39:49 +00:00
98890f10eb Merge pull request 'Implement editing of transactions' (#23) from edit-transaction into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #23
2022-02-25 23:35:10 +01:00
5621d63436 Actually call backend for edit
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2022-02-25 22:34:09 +00:00
05099e469f Delete transaction when amount is zero 2022-02-25 22:33:58 +00:00
ae9e9d34c9 Use type instead of isAccount flag
All checks were successful
continuous-integration/drone/push Build is passing
2022-02-25 22:28:22 +00:00
32439e3e87 rename type to model 2022-02-25 22:16:41 +00:00
4ed15b740b Remove unneeded imports and methods 2022-02-25 22:14:56 +00:00
5f161b2163 Rename Transaction to TX to match input row 2022-02-25 22:14:13 +00:00
10ea73663f Extract UpdateTransaction 2022-02-25 22:09:59 +00:00
07804e4241 Update existing transaction if transactionid was passed 2022-02-25 22:05:15 +00:00
2f4f8a7568 Extract method CreateTransferForOtherAccount 2022-02-25 22:02:57 +00:00
13d0194632 Pass date using ISO without time
All checks were successful
continuous-integration/drone/push Build is passing
2022-02-25 21:52:56 +00:00
c864666eb6 Use local date format
All checks were successful
continuous-integration/drone/push Build is passing
2022-02-25 21:50:15 +00:00
464931babe Pass amount as string 2022-02-25 21:46:20 +00:00
480a95e096 Implement custom date input 2022-02-25 21:45:58 +00:00
2d37ec147c Pass only category Id as categories are not to be created on the fly 2022-02-25 21:21:55 +00:00
75b48be20d Also pass Suggestion-Object from EditRow 2022-02-25 21:20:41 +00:00
306edbf817 Update TransactionInputRow to new models 2022-02-25 21:19:34 +00:00
be3829baf8 Replace modelValue by models for id and name 2022-02-25 21:10:21 +00:00
a452482381 Normalize transaction store 2022-02-25 20:47:58 +00:00
0f6990407d Remove widths from rows as header decides 2022-02-25 20:37:49 +00:00
97be5abc8c Add abilty to switch to edit mode 2022-02-25 20:37:31 +00:00
1e80ba6ca8 Also return PayeeID and CategoryID from backend 2022-02-25 20:36:24 +00:00
1331304639 Extract EditAccount Dialog 2022-02-25 20:17:54 +00:00
7435ac3667 Merge pull request 'Implement YNAB Export from UI' (#22) from export-from-ui into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #22
2022-02-25 21:07:40 +01:00
55dffbbe89 Implmeent expand/collapse of category-groups
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2022-02-25 20:06:26 +00:00
212c81ab81 Implement download from UI 2022-02-25 20:06:10 +00:00
5b5b8215c3 Merge pull request 'Make ynab export equivalent to original export' (#21) from ynab-export-fixes into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #21
2022-02-25 16:35:18 +01:00
79c0fceafe Fix formatting for negative numbers
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2022-02-25 15:32:39 +00:00
1ea3590fd6 Add tests with negative numbers 2022-02-25 15:32:32 +00:00
5bb2c9c8b8 Use empty string as fallback for TransferAccount
All checks were successful
continuous-integration/drone/push Build is passing
2022-02-25 15:27:06 +00:00
f9e512c593 Fix floating points < 1 2022-02-25 15:26:51 +00:00
4f72351ee9 Add more unittests for numeric 2022-02-25 15:26:39 +00:00
9ed4df7053 Fix leading space before category separator
All checks were successful
continuous-integration/drone/push Build is passing
2022-02-25 15:04:30 +00:00
78389e4beb Also export transfers 2022-02-25 15:04:09 +00:00
8ac3c22826 Merge pull request 'Implement editing of Accounts' (#20) from account-edit into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #20
2022-02-24 23:15:54 +01:00
ab07d3472d Handle EditAccount in Store
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2022-02-24 22:12:35 +00:00
466df523ab Implement EditAccount in Frontend 2022-02-24 22:12:26 +00:00
f51807e459 Implement EditAccount in Backend 2022-02-24 22:12:10 +00:00
03d1d1e520 Use grid instead of width for buttons 2022-02-24 21:38:57 +00:00
d09f5be69b Extract modal component 2022-02-24 21:37:26 +00:00
b5a03b40db Merge pull request 'Implement transfer creation' (#19) from enable-transfers into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #19
2022-02-24 00:13:20 +01:00
966c0ce0eb Redesign Budget Settings and introduce Button component
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2022-02-23 23:12:39 +00:00
635f4de402 Fix initialize of Budgets after login
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2022-02-23 23:03:31 +00:00
ddf51b5922 Use store instead of props in BudgetSidebar 2022-02-23 23:03:18 +00:00
bbbeff92e8 Reset amount to positive after saving transfer transaction
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2022-02-23 22:55:15 +00:00
5ccec61465 Implement transfer creation
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2022-02-23 22:53:04 +00:00
696fbee7cc Merge pull request 'Extract package for Numeric datatype and add unittests' (#18) from numeric-package into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #18
2022-02-23 23:13:18 +01:00
7c694fb32c Skip account_test when no db available
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2022-02-23 22:12:09 +00:00
5f746f5889 Also run tests in CI
Some checks failed
continuous-integration/drone/push Build is failing
continuous-integration/drone/pr Build is failing
2022-02-23 22:10:16 +00:00
24e5b18ded Implement linter fixes
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2022-02-23 22:08:47 +00:00
253ecd1720 Add negative testcases
Some checks failed
continuous-integration/drone/push Build is failing
continuous-integration/drone/pr Build is failing
2022-02-23 22:04:19 +00:00
f445f19233 Write all tests equally
Some checks failed
continuous-integration/drone/pr Build is failing
continuous-integration/drone/push Build is failing
2022-02-23 22:02:29 +00:00
ea6d198bff Add some unit-tests for numeric
Some checks failed
continuous-integration/drone/push Build is failing
continuous-integration/drone/pr Build is failing
2022-02-23 21:59:14 +00:00
28c20aacd3 Extract package 2022-02-23 21:59:14 +00:00
d89a8f4e2e Switch between payees and accounts depending on prefix 2022-02-23 21:59:14 +00:00
dae9abeeea Merge pull request 'Handle more of categories locally and update Modal' (#17) from categories-improvements into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #17
2022-02-23 22:58:33 +01:00
510c91205d Rewrite categories to be nested below groups
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2022-02-23 21:56:20 +00:00
f93888cbbc Move logic for hidden categories to client 2022-02-23 21:56:20 +00:00
674bef667b Hide checkmark icon 2022-02-23 21:56:20 +00:00
fffc91269e Extract NewCategoryWithBalance 2022-02-23 21:56:20 +00:00
c3175b9be6 Update NewBudget to use modal again 2022-02-23 21:56:20 +00:00
1d81aa2fb3 Do not try to set categories, if none are available 2022-02-23 21:56:20 +00:00
e5cf439231 Update BudgetSettings to tailwindcss 2022-02-23 21:56:20 +00:00
cfd2388de0 Disable cache for apk calls and add yarn.lock 2022-02-23 21:56:20 +00:00
0dfa698ada Merge pull request 'Fix inverted condition for Authorization and update expected JSON body' (#16) from minor-fixes into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #16
2022-02-23 22:56:04 +01:00
b4aec52d4f Fix changed json contract
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2022-02-23 21:55:29 +00:00
b5e3e7bea0 Fix inverted condition 2022-02-23 21:55:21 +00:00
e98e0d4779 Merge pull request 'Implement Export in YNAB-Format' (#15) from ynab-export into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #15
2022-02-23 22:18:01 +01:00
6686904539 Use zero Numeric for export instead of hardcoding 0,00
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2022-02-23 21:17:43 +00:00
0478d82c1f Fix order of fields
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2022-02-23 21:09:33 +00:00
34b6e450de Handle nil in Numeric 2022-02-23 21:09:25 +00:00
bc65249c03 Split transactions and assignments export into two endpoints
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2022-02-23 20:52:29 +00:00
e0dc7800af Remove limit for GetAllTransactionsForBudget 2022-02-23 20:52:29 +00:00
a7cd3512bb Handle errors of Write and add dots to comments 2022-02-23 20:52:29 +00:00
ece610419f Disable linter lll because no exceptions in comments are possible 2022-02-23 20:52:29 +00:00
27188e2e27 Implement ynab-export 2022-02-23 20:52:29 +00:00
4c7c61e820 Add string method to numeric 2022-02-23 20:52:29 +00:00
2adb70fa01 Fix comment and add csv example 2022-02-23 20:52:29 +00:00
eeb2d425e5 Merge pull request 'Fix registration not displaying' (#14) from registration into master
All checks were successful
continuous-integration/drone/push Build is passing
ci/woodpecker/push/woodpecker Pipeline was successful
Reviewed-on: #14
2022-02-22 14:44:29 +01:00
484b1062e1 Fix returning number as string for numbers
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/pr/woodpecker Pipeline was successful
2022-02-22 13:42:44 +00:00
a4ca21bb37 Add missing spaces
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/pr/woodpecker Pipeline was successful
2022-02-21 21:42:16 +00:00
ffabf1bca9 Also fix in register
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/pr/woodpecker Pipeline was successful
2022-02-21 21:41:24 +00:00
e9d4ed1b3e Fix router initialization in eventhandler
All checks were successful
continuous-integration/drone/push Build is passing
ci/woodpecker/push/woodpecker Pipeline was successful
useRouter has to be called in setup or returns undefined otherwise.
See https://github.com/vuejs/vue-router/issues/3379
2022-02-21 21:40:38 +00:00
4085868cd7 Update register to tailwindcss
All checks were successful
continuous-integration/drone/push Build is passing
ci/woodpecker/push/woodpecker Pipeline was successful
2022-02-21 21:26:12 +00:00
98 changed files with 4571 additions and 1542 deletions

View File

@ -4,11 +4,23 @@ type: docker
name: budgeteer
steps:
- name: Taskfile.dev
- name: Taskfile.dev PR
image: hub.javil.eu/budgeteer:dev
pull: true
commands:
- task ci
when:
event:
- pull_request
- name: Taskfile.dev
image: hub.javil.eu/budgeteer:dev
pull: always
commands:
- task ci
when:
event:
exclude:
- pull_request
- name: docker
image: plugins/docker
@ -20,14 +32,30 @@ steps:
from_secret: docker_password
repo: hub.javil.eu/budgeteer
context: build
dockerfile: build/Dockerfile
dockerfile: docker/Dockerfile
tags:
- latest
when:
branch:
- master
event:
exclude:
- pull_request
- push
- name: docker tag
image: plugins/docker
settings:
registry: hub.javil.eu
username:
from_secret: docker_user
password:
from_secret: docker_password
repo: hub.javil.eu/budgeteer
context: build
dockerfile: docker/Dockerfile
auto_tag: true
when:
event:
- tag
image_pull_secrets:
- hub.javil.eu

View File

@ -1,10 +0,0 @@
build/
.git/
docker-compose.yml
README.md
Earthfile
config.example.json
.gitignore
.vscode/
budgeteer
budgeteer.exe

View File

@ -13,6 +13,7 @@ linters:
- exhaustivestruct
- gci # not working, shows errors on freshly formatted file
- varnamelen
- lll
linters-settings:
errcheck:
exclude-functions:

View File

@ -1,7 +1,11 @@
{
"files.exclude": {
"**/node_modules": true,
"**/vendor": true
"**/vendor": true,
"**/*.sql.go": true,
".task/": true,
"build/": true,
"web/dist/": true
},
"gopls": {
"formatting.gofumpt": true,

View File

@ -1,23 +0,0 @@
pipeline:
build:
name: Taskfile.dev
image: hub.javil.eu/budgeteer:dev
pull: true
commands:
- task ci
docker:
image: plugins/docker
secrets: [ docker_username, docker_password ]
settings:
registry: hub.javil.eu
repo: hub.javil.eu/budgeteer
context: build
dockerfile: build/Dockerfile
tags:
- latest
when:
event: [push, tag, deployment]
image_pull_secrets:
- hub.javil.eu

View File

@ -1,21 +0,0 @@
FROM golang:1.17
WORKDIR /src
build:
COPY go.mod go.sum .
RUN go mod download
COPY . .
RUN --mount=type=cache,target=/root/.cache/go-build go build -o build/budgeteer ./cmd/budgeteer
SAVE ARTIFACT build/budgeteer /budgeteer AS LOCAL build/budgeteer
docker:
WORKDIR /app
COPY +build/budgeteer .
ENTRYPOINT ["/app/budgeteer"]
SAVE IMAGE hub.javil.eu/budgeteer:latest
run:
LOCALLY
WITH DOCKER --load=+docker
RUN docker-compose up -d
END

View File

@ -65,6 +65,7 @@ tasks:
desc: Run CI build
cmds:
- task: build-prod
- go test ./...
frontend:
desc: Build vue frontend
@ -76,6 +77,8 @@ tasks:
cmds:
- yarn
- yarn build
- yarn run vue-tsc --noEmit
- yarn run eslint "./src/**"
docker:
desc: Build budgeeter:latest
@ -94,7 +97,7 @@ tasks:
- ./docker/build.sh
- ./web/package.json
cmds:
- docker build -t {{.IMAGE_NAME}}:dev . -f docker/Dockerfile
- docker build -t {{.IMAGE_NAME}}:dev . -f docker/Dockerfile.dev
- docker push {{.IMAGE_NAME}}:dev
run:

View File

@ -1,3 +0,0 @@
FROM scratch
COPY ./budgeteer /app/budgeteer
ENTRYPOINT ["/app/budgeteer"]

View File

@ -1,6 +1,7 @@
package main
import (
"fmt"
"io/fs"
"log"
"net/http"
@ -29,11 +30,14 @@ func main() {
panic("couldn't open static files")
}
tokenVerifier, err := jwt.NewTokenVerifier(cfg.SessionSecret)
if err != nil {
panic(fmt.Errorf("couldn't create token verifier: %w", err))
}
handler := &server.Handler{
Service: queries,
TokenVerifier: &jwt.TokenVerifier{
Secret: cfg.SessionSecret,
},
TokenVerifier: tokenVerifier,
CredentialsVerifier: &bcrypt.Verifier{},
StaticFS: http.FS(static),
}

View File

@ -1,6 +0,0 @@
{
"DatabaseHost": "localhost",
"DatabaseUser": "user",
"DatabasePassword": "thisismypassword",
"DatabaseName": "budgeteer"
}

View File

@ -1,17 +1,3 @@
FROM alpine as godeps
RUN apk add go
RUN go install github.com/kyleconroy/sqlc/cmd/sqlc@latest
RUN go install github.com/go-task/task/v3/cmd/task@latest
RUN go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest
FROM alpine
RUN apk add go
RUN apk add nodejs yarn bash curl git git-perl tmux
ADD docker/build.sh /
RUN yarn global add @vue/cli
ENV PATH="/root/.yarn/bin/:${PATH}"
WORKDIR /src
ADD web/package.json /src/web/
RUN yarn
COPY --from=godeps /root/go/bin/task /root/go/bin/sqlc /root/go/bin/golangci-lint /usr/local/bin/
CMD /build.sh
FROM scratch
COPY ./budgeteer /app/budgeteer
ENTRYPOINT ["/app/budgeteer"]

17
docker/Dockerfile.dev Normal file
View File

@ -0,0 +1,17 @@
FROM alpine as godeps
RUN apk --no-cache add go
RUN go install github.com/kyleconroy/sqlc/cmd/sqlc@latest
RUN go install github.com/go-task/task/v3/cmd/task@latest
RUN go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest
FROM alpine
RUN apk --no-cache add go nodejs yarn bash curl git git-perl tmux
ADD docker/dev.sh /
RUN yarn global add @vue/cli
ENV PATH="/root/.yarn/bin/:${PATH}"
WORKDIR /src/web
ADD web/package.json web/yarn.lock /src/web/
RUN yarn
WORKDIR /src
COPY --from=godeps /root/go/bin/task /root/go/bin/sqlc /root/go/bin/golangci-lint /usr/local/bin/
CMD /dev.sh

2
go.mod
View File

@ -11,7 +11,7 @@ require (
golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa
)
require github.com/DATA-DOG/go-txdb v0.1.5 // indirect
require github.com/DATA-DOG/go-txdb v0.1.5
require (
github.com/gin-contrib/sse v0.1.0 // indirect

1
go.sum
View File

@ -74,6 +74,7 @@ github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+
github.com/go-playground/validator/v10 v10.4.1 h1:pH2c5ADXtd66mxoE0Zm9SUhxE20r7aM3F26W0hOn+GE=
github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4=
github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=
github.com/go-sql-driver/mysql v1.6.0 h1:BCTh4TKNUYmOmMUcQ3IipzF5prigylS7XXjEkfCHuOE=
github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=

View File

@ -12,32 +12,45 @@ import (
// TokenVerifier verifies Tokens.
type TokenVerifier struct {
Secret string
Expiration time.Duration
secret string
}
// Token contains everything to authenticate a user.
type Token struct {
username string
name string
expiry float64
id uuid.UUID
const DefaultExpiration = time.Hour * time.Duration(72)
func NewTokenVerifier(secret string) (*TokenVerifier, error) {
if secret == "" {
return nil, ErrEmptySecret
}
return &TokenVerifier{
Expiration: DefaultExpiration,
secret: secret,
}, nil
}
const (
expiration = 72
var (
ErrUnexpectedSigningMethod = fmt.Errorf("unexpected signing method")
ErrInvalidToken = fmt.Errorf("token is invalid")
ErrTokenExpired = fmt.Errorf("token has expired")
ErrEmptySecret = fmt.Errorf("secret is required")
)
// CreateToken creates a new token from username and name.
func (tv *TokenVerifier) CreateToken(user *postgres.User) (string, error) {
if tv.secret == "" {
return "", ErrEmptySecret
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"usr": user.Email,
"name": user.Name,
"exp": time.Now().Add(time.Hour * expiration).Unix(),
"exp": time.Now().Add(tv.Expiration).Unix(),
"id": user.ID,
})
// Generate encoded token and send it as response.
t, err := token.SignedString([]byte(tv.Secret))
t, err := token.SignedString([]byte(tv.secret))
if err != nil {
return "", fmt.Errorf("create token: %w", err)
}
@ -45,19 +58,17 @@ func (tv *TokenVerifier) CreateToken(user *postgres.User) (string, error) {
return t, nil
}
var (
ErrUnexpectedSigningMethod = fmt.Errorf("unexpected signing method")
ErrInvalidToken = fmt.Errorf("token is invalid")
ErrTokenExpired = fmt.Errorf("token has expired")
)
// VerifyToken verifys a given string-token.
// VerifyToken verifies a given string-token.
func (tv *TokenVerifier) VerifyToken(tokenString string) (budgeteer.Token, error) { //nolint:ireturn
if tv.secret == "" {
return nil, ErrEmptySecret
}
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("method '%v': %w", token.Header["alg"], ErrUnexpectedSigningMethod)
}
return []byte(tv.Secret), nil
return []byte(tv.secret), nil
})
if err != nil {
return nil, fmt.Errorf("parse jwt: %w", err)
@ -76,36 +87,3 @@ func (tv *TokenVerifier) VerifyToken(tokenString string) (budgeteer.Token, error
}
return tkn, nil
}
func verifyToken(token *jwt.Token) (jwt.MapClaims, error) {
if !token.Valid {
return nil, ErrInvalidToken
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
return nil, ErrInvalidToken
}
if !claims.VerifyExpiresAt(time.Now().Unix(), true) {
return nil, ErrTokenExpired
}
return claims, nil
}
func (t *Token) GetName() string {
return t.name
}
func (t *Token) GetUsername() string {
return t.username
}
func (t *Token) GetExpiry() float64 {
return t.expiry
}
func (t *Token) GetID() uuid.UUID {
return t.id
}

49
jwt/token.go Normal file
View File

@ -0,0 +1,49 @@
package jwt
import (
"time"
"github.com/dgrijalva/jwt-go"
"github.com/google/uuid"
)
// Token contains everything to authenticate a user.
type Token struct {
username string
name string
expiry float64
id uuid.UUID
}
func verifyToken(token *jwt.Token) (jwt.MapClaims, error) {
if !token.Valid {
return nil, ErrInvalidToken
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
return nil, ErrInvalidToken
}
if !claims.VerifyExpiresAt(time.Now().Unix(), true) {
return nil, ErrTokenExpired
}
return claims, nil
}
func (t *Token) GetName() string {
return t.name
}
func (t *Token) GetUsername() string {
return t.username
}
func (t *Token) GetExpiry() float64 {
return t.expiry
}
func (t *Token) GetID() uuid.UUID {
return t.id
}

View File

@ -5,7 +5,9 @@ package postgres
import (
"context"
"database/sql"
"git.javil.eu/jacob1123/budgeteer/postgres/numeric"
"github.com/google/uuid"
)
@ -13,7 +15,7 @@ const createAccount = `-- name: CreateAccount :one
INSERT INTO accounts
(name, budget_id)
VALUES ($1, $2)
RETURNING id, budget_id, name, on_budget
RETURNING id, budget_id, name, on_budget, is_open, last_reconciled
`
type CreateAccountParams struct {
@ -29,12 +31,14 @@ func (q *Queries) CreateAccount(ctx context.Context, arg CreateAccountParams) (A
&i.BudgetID,
&i.Name,
&i.OnBudget,
&i.IsOpen,
&i.LastReconciled,
)
return i, err
}
const getAccount = `-- name: GetAccount :one
SELECT accounts.id, accounts.budget_id, accounts.name, accounts.on_budget FROM accounts
SELECT accounts.id, accounts.budget_id, accounts.name, accounts.on_budget, accounts.is_open, accounts.last_reconciled FROM accounts
WHERE accounts.id = $1
`
@ -46,13 +50,16 @@ func (q *Queries) GetAccount(ctx context.Context, id uuid.UUID) (Account, error)
&i.BudgetID,
&i.Name,
&i.OnBudget,
&i.IsOpen,
&i.LastReconciled,
)
return i, err
}
const getAccounts = `-- name: GetAccounts :many
SELECT accounts.id, accounts.budget_id, accounts.name, accounts.on_budget FROM accounts
SELECT accounts.id, accounts.budget_id, accounts.name, accounts.on_budget, accounts.is_open, accounts.last_reconciled FROM accounts
WHERE accounts.budget_id = $1
AND accounts.is_open = TRUE
ORDER BY accounts.name
`
@ -70,6 +77,8 @@ func (q *Queries) GetAccounts(ctx context.Context, budgetID uuid.UUID) ([]Accoun
&i.BudgetID,
&i.Name,
&i.OnBudget,
&i.IsOpen,
&i.LastReconciled,
); err != nil {
return nil, err
}
@ -85,11 +94,13 @@ func (q *Queries) GetAccounts(ctx context.Context, budgetID uuid.UUID) ([]Accoun
}
const getAccountsWithBalance = `-- name: GetAccountsWithBalance :many
SELECT accounts.id, accounts.name, accounts.on_budget, SUM(transactions.amount)::decimal(12,2) as balance
SELECT accounts.id, accounts.name, accounts.on_budget, accounts.is_open, accounts.last_reconciled,
(SELECT SUM(transactions.amount) FROM transactions WHERE transactions.account_id = accounts.id AND transactions.date < NOW())::decimal(12,2) as working_balance,
(SELECT SUM(transactions.amount) FROM transactions WHERE transactions.account_id = accounts.id AND transactions.date < NOW() AND transactions.status IN ('Cleared', 'Reconciled'))::decimal(12,2) as cleared_balance,
(SELECT SUM(transactions.amount) FROM transactions WHERE transactions.account_id = accounts.id AND transactions.date < NOW() AND transactions.status = 'Reconciled')::decimal(12,2) as reconciled_balance
FROM accounts
LEFT JOIN transactions ON transactions.account_id = accounts.id AND transactions.date < NOW()
WHERE accounts.budget_id = $1
GROUP BY accounts.id, accounts.name
AND accounts.is_open = TRUE
ORDER BY accounts.name
`
@ -97,7 +108,11 @@ type GetAccountsWithBalanceRow struct {
ID uuid.UUID
Name string
OnBudget bool
Balance Numeric
IsOpen bool
LastReconciled sql.NullTime
WorkingBalance numeric.Numeric
ClearedBalance numeric.Numeric
ReconciledBalance numeric.Numeric
}
func (q *Queries) GetAccountsWithBalance(ctx context.Context, budgetID uuid.UUID) ([]GetAccountsWithBalanceRow, error) {
@ -113,7 +128,11 @@ func (q *Queries) GetAccountsWithBalance(ctx context.Context, budgetID uuid.UUID
&i.ID,
&i.Name,
&i.OnBudget,
&i.Balance,
&i.IsOpen,
&i.LastReconciled,
&i.WorkingBalance,
&i.ClearedBalance,
&i.ReconciledBalance,
); err != nil {
return nil, err
}
@ -127,3 +146,97 @@ func (q *Queries) GetAccountsWithBalance(ctx context.Context, budgetID uuid.UUID
}
return items, nil
}
const searchAccounts = `-- name: SearchAccounts :many
SELECT accounts.id, accounts.budget_id, accounts.name, 'account' as type FROM accounts
WHERE accounts.budget_id = $1
AND accounts.is_open = TRUE
AND accounts.name ILIKE $2
ORDER BY accounts.name
`
type SearchAccountsParams struct {
BudgetID uuid.UUID
Search string
}
type SearchAccountsRow struct {
ID uuid.UUID
BudgetID uuid.UUID
Name string
Type interface{}
}
func (q *Queries) SearchAccounts(ctx context.Context, arg SearchAccountsParams) ([]SearchAccountsRow, error) {
rows, err := q.db.QueryContext(ctx, searchAccounts, arg.BudgetID, arg.Search)
if err != nil {
return nil, err
}
defer rows.Close()
var items []SearchAccountsRow
for rows.Next() {
var i SearchAccountsRow
if err := rows.Scan(
&i.ID,
&i.BudgetID,
&i.Name,
&i.Type,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Close(); err != nil {
return nil, err
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const setLastReconciled = `-- name: SetLastReconciled :exec
UPDATE accounts
SET last_reconciled = NOW()
WHERE accounts.id = $1
`
func (q *Queries) SetLastReconciled(ctx context.Context, id uuid.UUID) error {
_, err := q.db.ExecContext(ctx, setLastReconciled, id)
return err
}
const updateAccount = `-- name: UpdateAccount :one
UPDATE accounts
SET name = $1,
on_budget = $2,
is_open = $3
WHERE accounts.id = $4
RETURNING id, budget_id, name, on_budget, is_open, last_reconciled
`
type UpdateAccountParams struct {
Name string
OnBudget bool
IsOpen bool
ID uuid.UUID
}
func (q *Queries) UpdateAccount(ctx context.Context, arg UpdateAccountParams) (Account, error) {
row := q.db.QueryRowContext(ctx, updateAccount,
arg.Name,
arg.OnBudget,
arg.IsOpen,
arg.ID,
)
var i Account
err := row.Scan(
&i.ID,
&i.BudgetID,
&i.Name,
&i.OnBudget,
&i.IsOpen,
&i.LastReconciled,
)
return i, err
}

View File

@ -7,6 +7,7 @@ import (
"context"
"time"
"git.javil.eu/jacob1123/budgeteer/postgres/numeric"
"github.com/google/uuid"
)
@ -16,12 +17,12 @@ INSERT INTO assignments (
) VALUES (
$1, $2, $3
)
RETURNING id, category_id, date, memo, amount
RETURNING category_id, date, memo, amount
`
type CreateAssignmentParams struct {
Date time.Time
Amount Numeric
Amount numeric.Numeric
CategoryID uuid.UUID
}
@ -29,7 +30,6 @@ func (q *Queries) CreateAssignment(ctx context.Context, arg CreateAssignmentPara
row := q.db.QueryRowContext(ctx, createAssignment, arg.Date, arg.Amount, arg.CategoryID)
var i Assignment
err := row.Scan(
&i.ID,
&i.CategoryID,
&i.Date,
&i.Memo,
@ -53,6 +53,49 @@ func (q *Queries) DeleteAllAssignments(ctx context.Context, budgetID uuid.UUID)
return result.RowsAffected()
}
const getAllAssignments = `-- name: GetAllAssignments :many
SELECT assignments.date, categories.name as category, category_groups.name as group, assignments.amount
FROM assignments
INNER JOIN categories ON categories.id = assignments.category_id
INNER JOIN category_groups ON categories.category_group_id = category_groups.id
WHERE category_groups.budget_id = $1
`
type GetAllAssignmentsRow struct {
Date time.Time
Category string
Group string
Amount numeric.Numeric
}
func (q *Queries) GetAllAssignments(ctx context.Context, budgetID uuid.UUID) ([]GetAllAssignmentsRow, error) {
rows, err := q.db.QueryContext(ctx, getAllAssignments, budgetID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []GetAllAssignmentsRow
for rows.Next() {
var i GetAllAssignmentsRow
if err := rows.Scan(
&i.Date,
&i.Category,
&i.Group,
&i.Amount,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Close(); err != nil {
return nil, err
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const getAssignmentsByMonthAndCategory = `-- name: GetAssignmentsByMonthAndCategory :many
SELECT date, category_id, budget_id, amount
FROM assignments_by_month
@ -86,3 +129,41 @@ func (q *Queries) GetAssignmentsByMonthAndCategory(ctx context.Context, budgetID
}
return items, nil
}
const updateAssignment = `-- name: UpdateAssignment :exec
INSERT INTO assignments (category_id, date, amount)
VALUES($1, $2, $3)
ON CONFLICT (category_id, date)
DO
UPDATE SET amount = $3
`
type UpdateAssignmentParams struct {
CategoryID uuid.UUID
Date time.Time
Amount numeric.Numeric
}
func (q *Queries) UpdateAssignment(ctx context.Context, arg UpdateAssignmentParams) error {
_, err := q.db.ExecContext(ctx, updateAssignment, arg.CategoryID, arg.Date, arg.Amount)
return err
}
const updateAssignmentWithDifference = `-- name: UpdateAssignmentWithDifference :exec
INSERT INTO assignments (category_id, date, amount)
VALUES($1, $2, $3)
ON CONFLICT (category_id, date)
DO
UPDATE SET amount = assignments.amount + $3
`
type UpdateAssignmentWithDifferenceParams struct {
CategoryID uuid.UUID
Date time.Time
Amount numeric.Numeric
}
func (q *Queries) UpdateAssignmentWithDifference(ctx context.Context, arg UpdateAssignmentWithDifferenceParams) error {
_, err := q.db.ExecContext(ctx, updateAssignmentWithDifference, arg.CategoryID, arg.Date, arg.Amount)
return err
}

View File

@ -118,10 +118,12 @@ func (q *Queries) GetCategoryGroups(ctx context.Context, budgetID uuid.UUID) ([]
}
const searchCategories = `-- name: SearchCategories :many
SELECT CONCAT(category_groups.name, ' : ', categories.name) as name, categories.id FROM categories
SELECT CONCAT(category_groups.name, ' : ', categories.name) as name, categories.id, 'category' as type
FROM categories
INNER JOIN category_groups ON categories.category_group_id = category_groups.id
WHERE category_groups.budget_id = $1
AND categories.name LIKE $2
AND categories.name ILIKE $2
AND category_groups.name != 'Hidden Categories'
ORDER BY category_groups.name, categories.name
`
@ -133,6 +135,7 @@ type SearchCategoriesParams struct {
type SearchCategoriesRow struct {
Name interface{}
ID uuid.UUID
Type interface{}
}
func (q *Queries) SearchCategories(ctx context.Context, arg SearchCategoriesParams) ([]SearchCategoriesRow, error) {
@ -144,7 +147,7 @@ func (q *Queries) SearchCategories(ctx context.Context, arg SearchCategoriesPara
var items []SearchCategoriesRow
for rows.Next() {
var i SearchCategoriesRow
if err := rows.Scan(&i.Name, &i.ID); err != nil {
if err := rows.Scan(&i.Name, &i.ID, &i.Type); err != nil {
return nil, err
}
items = append(items, i)

View File

@ -7,6 +7,7 @@ import (
"context"
"time"
"git.javil.eu/jacob1123/budgeteer/postgres/numeric"
"github.com/google/uuid"
)
@ -23,10 +24,10 @@ ORDER BY COALESCE(ass.date, tra.date), COALESCE(ass.category_id, tra.category_id
type GetCumultativeBalancesRow struct {
Date time.Time
CategoryID uuid.UUID
Assignments Numeric
AssignmentsCum Numeric
Transactions Numeric
TransactionsCum Numeric
Assignments numeric.Numeric
AssignmentsCum numeric.Numeric
Transactions numeric.Numeric
TransactionsCum numeric.Numeric
}
func (q *Queries) GetCumultativeBalances(ctx context.Context, budgetID uuid.UUID) ([]GetCumultativeBalancesRow, error) {

View File

@ -7,6 +7,7 @@ import (
"fmt"
"time"
"git.javil.eu/jacob1123/budgeteer/postgres/numeric"
"github.com/google/uuid"
)
@ -35,14 +36,15 @@ type Account struct {
BudgetID uuid.UUID
Name string
OnBudget bool
IsOpen bool
LastReconciled sql.NullTime
}
type Assignment struct {
ID uuid.UUID
CategoryID uuid.UUID
Date time.Time
Memo sql.NullString
Amount Numeric
Amount numeric.Numeric
}
type AssignmentsByMonth struct {
@ -71,6 +73,24 @@ type CategoryGroup struct {
Name string
}
type DisplayTransaction struct {
ID uuid.UUID
Date time.Time
Memo string
Amount numeric.Numeric
GroupID uuid.NullUUID
Status TransactionStatus
Account string
PayeeID uuid.NullUUID
CategoryID uuid.NullUUID
Payee string
CategoryGroup string
Category string
TransferAccount string
BudgetID uuid.UUID
AccountID uuid.UUID
}
type Payee struct {
ID uuid.UUID
BudgetID uuid.UUID
@ -81,7 +101,7 @@ type Transaction struct {
ID uuid.UUID
Date time.Time
Memo string
Amount Numeric
Amount numeric.Numeric
AccountID uuid.UUID
CategoryID uuid.NullUUID
PayeeID uuid.NullUUID

View File

@ -1,130 +0,0 @@
package postgres
import (
"fmt"
"math/big"
"github.com/jackc/pgtype"
)
type Numeric struct {
pgtype.Numeric
}
func NewZeroNumeric() Numeric {
return Numeric{pgtype.Numeric{Exp: 0, Int: big.NewInt(0), Status: pgtype.Present, NaN: false}}
}
func (n Numeric) GetFloat64() float64 {
if n.Status != pgtype.Present {
return 0
}
var balance float64
err := n.AssignTo(&balance)
if err != nil {
panic(err)
}
return balance
}
func (n Numeric) IsPositive() bool {
if n.Status != pgtype.Present {
return true
}
float := n.GetFloat64()
return float >= 0
}
func (n Numeric) IsZero() bool {
if n.Status != pgtype.Present {
return true
}
float := n.GetFloat64()
return float == 0
}
func (n Numeric) MatchExp(exp int32) Numeric {
diffExp := n.Exp - exp
factor := big.NewInt(0).Exp(big.NewInt(10), big.NewInt(int64(diffExp)), nil) //nolint:gomnd
return Numeric{pgtype.Numeric{
Exp: exp,
Int: big.NewInt(0).Mul(n.Int, factor),
Status: n.Status,
NaN: n.NaN,
}}
}
func (n Numeric) Sub(other Numeric) Numeric {
left := n
right := other
if n.Exp < other.Exp {
right = other.MatchExp(n.Exp)
} else if n.Exp > other.Exp {
left = n.MatchExp(other.Exp)
}
if left.Exp == right.Exp {
return Numeric{pgtype.Numeric{
Exp: left.Exp,
Int: big.NewInt(0).Sub(left.Int, right.Int),
}}
}
panic("Cannot subtract with different exponents")
}
func (n Numeric) Add(other Numeric) Numeric {
left := n
right := other
if n.Exp < other.Exp {
right = other.MatchExp(n.Exp)
} else if n.Exp > other.Exp {
left = n.MatchExp(other.Exp)
}
if left.Exp == right.Exp {
return Numeric{pgtype.Numeric{
Exp: left.Exp,
Int: big.NewInt(0).Add(left.Int, right.Int),
}}
}
panic("Cannot add with different exponents")
}
func (n Numeric) MarshalJSON() ([]byte, error) {
if n.Int.Int64() == 0 {
return []byte("\"0\""), nil
}
s := fmt.Sprintf("%d", n.Int)
bytes := []byte(s)
exp := n.Exp
for exp > 0 {
bytes = append(bytes, byte('0'))
exp--
}
if exp == 0 {
return bytes, nil
}
length := int32(len(bytes))
var bytesWithSeparator []byte
exp = -exp
for length <= exp {
bytes = append(bytes, byte('0'))
length++
}
split := length - exp
bytesWithSeparator = append(bytesWithSeparator, bytes[:split]...)
if split == 1 && n.Int.Int64() < 0 {
bytesWithSeparator = append(bytesWithSeparator, byte('0'))
}
bytesWithSeparator = append(bytesWithSeparator, byte('.'))
bytesWithSeparator = append(bytesWithSeparator, bytes[split:]...)
return bytesWithSeparator, nil
}

265
postgres/numeric/numeric.go Normal file
View File

@ -0,0 +1,265 @@
package numeric
import (
"fmt"
"math/big"
"strings"
"unicode/utf8"
"github.com/jackc/pgtype"
)
type Numeric struct {
pgtype.Numeric
}
func Zero() Numeric {
return Numeric{pgtype.Numeric{Exp: 0, Int: big.NewInt(0), Status: pgtype.Present, NaN: false}}
}
func FromInt64(value int64) Numeric {
return Numeric{Numeric: pgtype.Numeric{Int: big.NewInt(value), Status: pgtype.Present}}
}
func FromInt64WithExp(value int64, exp int32) Numeric {
return Numeric{Numeric: pgtype.Numeric{Int: big.NewInt(value), Exp: exp, Status: pgtype.Present}}
}
func (n Numeric) GetFloat64() float64 {
if n.Status != pgtype.Present {
return 0
}
var balance float64
err := n.AssignTo(&balance)
if err != nil {
panic(err)
}
return balance
}
func (n Numeric) IsPositive() bool {
if n.Status != pgtype.Present {
return true
}
float := n.GetFloat64()
return float >= 0
}
func (n Numeric) IsZero() bool {
if n.Status != pgtype.Present {
return true
}
float := n.GetFloat64()
return float == 0
}
func (n *Numeric) MatchExpI(exp int32) {
diffExp := n.Exp - exp
factor := big.NewInt(0).Exp(big.NewInt(10), big.NewInt(int64(diffExp)), nil) //nolint:gomnd
n.Exp = exp
n.Int = big.NewInt(0).Mul(n.Int, factor)
}
func (n Numeric) MatchExp(exp int32) Numeric {
diffExp := n.Exp - exp
factor := big.NewInt(0).Exp(big.NewInt(10), big.NewInt(int64(diffExp)), nil) //nolint:gomnd
return Numeric{pgtype.Numeric{
Exp: exp,
Int: big.NewInt(0).Mul(n.Int, factor),
Status: n.Status,
NaN: n.NaN,
}}
}
func (n *Numeric) SubI(other Numeric) *Numeric {
right := other
if n.Exp < other.Exp {
right = other.MatchExp(n.Exp)
} else if n.Exp > other.Exp {
n.MatchExpI(other.Exp)
}
if n.Exp == right.Exp {
n.Int = big.NewInt(0).Sub(n.Int, right.Int)
return n
}
panic("Cannot subtract with different exponents")
}
func (n Numeric) Sub(other Numeric) Numeric {
left := n
right := other
if n.Exp < other.Exp {
right = other.MatchExp(n.Exp)
} else if n.Exp > other.Exp {
left = n.MatchExp(other.Exp)
}
if left.Exp == right.Exp {
return Numeric{pgtype.Numeric{
Exp: left.Exp,
Int: big.NewInt(0).Sub(left.Int, right.Int),
}}
}
panic("Cannot subtract with different exponents")
}
func (n Numeric) Neg() Numeric {
return Numeric{pgtype.Numeric{Exp: n.Exp, Int: big.NewInt(-1 * n.Int.Int64()), Status: n.Status}}
}
func (n Numeric) Add(other Numeric) Numeric {
left := n
right := other
if n.Exp < other.Exp {
right = other.MatchExp(n.Exp)
} else if n.Exp > other.Exp {
left = n.MatchExp(other.Exp)
}
if left.Exp == right.Exp {
return Numeric{pgtype.Numeric{
Exp: left.Exp,
Int: big.NewInt(0).Add(left.Int, right.Int),
}}
}
panic("Cannot add with different exponents")
}
func (n *Numeric) AddI(other Numeric) *Numeric {
right := other
if n.Exp < other.Exp {
right = other.MatchExp(n.Exp)
} else if n.Exp > other.Exp {
n.MatchExpI(other.Exp)
}
if n.Exp == right.Exp {
n.Int = big.NewInt(0).Add(n.Int, right.Int)
return n
}
panic("Cannot add with different exponents")
}
func (n Numeric) String() string {
if n.Int == nil || n.Int.Int64() == 0 {
return "0"
}
s := fmt.Sprintf("%d", n.Int)
bytes := []byte(s)
exp := n.Exp
for exp > 0 {
bytes = append(bytes, byte('0'))
exp--
}
if exp == 0 {
return string(bytes)
}
length := int32(len(bytes))
var bytesWithSeparator []byte
exp = -exp
for length <= exp {
if n.Int.Int64() < 0 {
bytes = append([]byte{bytes[0], byte('0')}, bytes[1:]...)
} else {
bytes = append([]byte{byte('0')}, bytes...)
}
length++
}
split := length - exp
bytesWithSeparator = append(bytesWithSeparator, bytes[:split]...)
if split == 1 && n.Int.Int64() < 0 {
bytesWithSeparator = append(bytesWithSeparator, byte('0'))
}
bytesWithSeparator = append(bytesWithSeparator, byte('.'))
bytesWithSeparator = append(bytesWithSeparator, bytes[split:]...)
return string(bytesWithSeparator)
}
func (n Numeric) MarshalJSON() ([]byte, error) {
if n.Int == nil || n.Int.Int64() == 0 {
return []byte("0"), nil
}
s := fmt.Sprintf("%d", n.Int)
bytes := []byte(s)
exp := n.Exp
for exp > 0 {
bytes = append(bytes, byte('0'))
exp--
}
if exp == 0 {
return bytes, nil
}
length := int32(len(bytes))
var bytesWithSeparator []byte
exp = -exp
for length <= exp {
if n.Int.Int64() < 0 {
bytes = append([]byte{bytes[0], byte('0')}, bytes[1:]...)
} else {
bytes = append([]byte{byte('0')}, bytes...)
}
length++
}
split := length - exp
bytesWithSeparator = append(bytesWithSeparator, bytes[:split]...)
if split == 1 && n.Int.Int64() < 0 {
bytesWithSeparator = append(bytesWithSeparator, byte('0'))
}
bytesWithSeparator = append(bytesWithSeparator, byte('.'))
bytesWithSeparator = append(bytesWithSeparator, bytes[split:]...)
return bytesWithSeparator, nil
}
func MustParse(text string) Numeric {
num, err := Parse(text)
if err != nil {
panic(err)
}
return num
}
func Parse(text string) (Numeric, error) {
// Unify decimal separator
text = strings.Replace(text, ",", ".", 1)
num := Numeric{}
err := num.Set(text)
if err != nil {
return num, fmt.Errorf("parse numeric %s: %w", text, err)
}
return num, nil
}
func ParseCurrency(text string) (Numeric, error) {
// Remove trailing currency
text = trimLastChar(text)
return Parse(text)
}
func trimLastChar(s string) string {
r, size := utf8.DecodeLastRuneInString(s)
if r == utf8.RuneError && (size == 0 || size == 1) {
size = 0
}
return s[:len(s)-size]
}

View File

@ -0,0 +1,118 @@
package numeric_test
import (
"testing"
"git.javil.eu/jacob1123/budgeteer/postgres/numeric"
)
type TestCaseMarshalJSON struct {
Value numeric.Numeric
Result string
}
func TestMarshalJSON(t *testing.T) {
t.Parallel()
tests := []TestCaseMarshalJSON{
{numeric.Zero(), `0`},
{numeric.MustParse("1.23"), "1.23"},
{numeric.MustParse("1,24"), "1.24"},
{numeric.MustParse("1"), "1"},
{numeric.MustParse("10"), "10"},
{numeric.MustParse("100"), "100"},
{numeric.MustParse("1000"), "1000"},
{numeric.MustParse("0.1"), "0.1"},
{numeric.MustParse("0.01"), "0.01"},
{numeric.MustParse("0.001"), "0.001"},
{numeric.MustParse("0.0001"), "0.0001"},
{numeric.MustParse("-1"), "-1"},
{numeric.MustParse("-10"), "-10"},
{numeric.MustParse("-100"), "-100"},
{numeric.MustParse("-1000"), "-1000"},
{numeric.MustParse("-0.1"), "-0.1"},
{numeric.MustParse("-0.01"), "-0.01"},
{numeric.MustParse("-0.001"), "-0.001"},
{numeric.MustParse("-0.0001"), "-0.0001"},
{numeric.MustParse("123456789.12345"), "123456789.12345"},
{numeric.MustParse("123456789.12345"), "123456789.12345"},
{numeric.MustParse("-1.23"), "-1.23"},
{numeric.MustParse("-1,24"), "-1.24"},
{numeric.MustParse("-123456789.12345"), "-123456789.12345"},
}
for i := range tests {
test := tests[i]
t.Run(test.Result, func(t *testing.T) {
t.Parallel()
z := test.Value
result, err := z.MarshalJSON()
if err != nil {
t.Error(err)
return
}
if string(result) != test.Result {
t.Errorf("Expected %s, got %s", test.Result, string(result))
return
}
})
}
}
type TestCaseParse struct {
Result numeric.Numeric
Value string
}
func TestParse(t *testing.T) {
t.Parallel()
tests := []TestCaseParse{
{numeric.FromInt64WithExp(0, 0), `0`},
{numeric.FromInt64WithExp(1, 0), `1`},
{numeric.FromInt64WithExp(1, 1), `10`},
{numeric.FromInt64WithExp(1, 2), `100`},
{numeric.FromInt64WithExp(1, 3), `1000`},
{numeric.FromInt64WithExp(1, -1), `0.1`},
{numeric.FromInt64WithExp(1, -2), `0.01`},
{numeric.FromInt64WithExp(1, -3), `0.001`},
{numeric.FromInt64WithExp(1, -4), `0.0001`},
{numeric.FromInt64WithExp(-1, 0), `-1`},
{numeric.FromInt64WithExp(-1, 1), `-10`},
{numeric.FromInt64WithExp(-1, 2), `-100`},
{numeric.FromInt64WithExp(-1, 3), `-1000`},
{numeric.FromInt64WithExp(-1, -1), `-0.1`},
{numeric.FromInt64WithExp(-1, -2), `-0.01`},
{numeric.FromInt64WithExp(-1, -3), `-0.001`},
{numeric.FromInt64WithExp(-1, -4), `-0.0001`},
{numeric.FromInt64WithExp(123, -2), "1.23"},
{numeric.FromInt64WithExp(124, -2), "1,24"},
{numeric.FromInt64WithExp(12345678912345, -5), "123456789.12345"},
{numeric.FromInt64WithExp(0, 0), `-0`},
{numeric.FromInt64WithExp(-1, 0), `-1`},
{numeric.FromInt64WithExp(-1, 1), `-10`},
{numeric.FromInt64WithExp(-1, 2), `-100`},
{numeric.FromInt64WithExp(-123, -2), "-1.23"},
{numeric.FromInt64WithExp(-124, -2), "-1,24"},
{numeric.FromInt64WithExp(-12345678912345, -5), "-123456789.12345"},
}
for i := range tests {
test := tests[i]
t.Run(test.Value, func(t *testing.T) {
t.Parallel()
result, err := numeric.Parse(test.Value)
if err != nil {
t.Error(err)
return
}
if test.Result.Int.Int64() != result.Int.Int64() {
t.Errorf("Expected int %d, got %d", test.Result.Int, result.Int)
return
}
if test.Result.Exp != result.Exp {
t.Errorf("Expected exp %d, got %d", test.Result.Exp, result.Exp)
return
}
})
}
}

View File

@ -58,9 +58,9 @@ func (q *Queries) GetPayees(ctx context.Context, budgetID uuid.UUID) ([]Payee, e
}
const searchPayees = `-- name: SearchPayees :many
SELECT payees.id, payees.budget_id, payees.name FROM payees
SELECT payees.id, payees.budget_id, payees.name, 'payee' as type FROM payees
WHERE payees.budget_id = $1
AND payees.name LIKE $2
AND payees.name ILIKE $2
ORDER BY payees.name
`
@ -69,16 +69,28 @@ type SearchPayeesParams struct {
Search string
}
func (q *Queries) SearchPayees(ctx context.Context, arg SearchPayeesParams) ([]Payee, error) {
type SearchPayeesRow struct {
ID uuid.UUID
BudgetID uuid.UUID
Name string
Type interface{}
}
func (q *Queries) SearchPayees(ctx context.Context, arg SearchPayeesParams) ([]SearchPayeesRow, error) {
rows, err := q.db.QueryContext(ctx, searchPayees, arg.BudgetID, arg.Search)
if err != nil {
return nil, err
}
defer rows.Close()
var items []Payee
var items []SearchPayeesRow
for rows.Next() {
var i Payee
if err := rows.Scan(&i.ID, &i.BudgetID, &i.Name); err != nil {
var i SearchPayeesRow
if err := rows.Scan(
&i.ID,
&i.BudgetID,
&i.Name,
&i.Type,
); err != nil {
return nil, err
}
items = append(items, i)

View File

@ -11,12 +11,35 @@ WHERE accounts.id = $1;
-- name: GetAccounts :many
SELECT accounts.* FROM accounts
WHERE accounts.budget_id = $1
AND accounts.is_open = TRUE
ORDER BY accounts.name;
-- name: GetAccountsWithBalance :many
SELECT accounts.id, accounts.name, accounts.on_budget, SUM(transactions.amount)::decimal(12,2) as balance
SELECT accounts.id, accounts.name, accounts.on_budget, accounts.is_open, accounts.last_reconciled,
(SELECT SUM(transactions.amount) FROM transactions WHERE transactions.account_id = accounts.id AND transactions.date < NOW())::decimal(12,2) as working_balance,
(SELECT SUM(transactions.amount) FROM transactions WHERE transactions.account_id = accounts.id AND transactions.date < NOW() AND transactions.status IN ('Cleared', 'Reconciled'))::decimal(12,2) as cleared_balance,
(SELECT SUM(transactions.amount) FROM transactions WHERE transactions.account_id = accounts.id AND transactions.date < NOW() AND transactions.status = 'Reconciled')::decimal(12,2) as reconciled_balance
FROM accounts
LEFT JOIN transactions ON transactions.account_id = accounts.id AND transactions.date < NOW()
WHERE accounts.budget_id = $1
GROUP BY accounts.id, accounts.name
AND accounts.is_open = TRUE
ORDER BY accounts.name;
-- name: SearchAccounts :many
SELECT accounts.id, accounts.budget_id, accounts.name, 'account' as type FROM accounts
WHERE accounts.budget_id = @budget_id
AND accounts.is_open = TRUE
AND accounts.name ILIKE @search
ORDER BY accounts.name;
-- name: UpdateAccount :one
UPDATE accounts
SET name = $1,
on_budget = $2,
is_open = $3
WHERE accounts.id = $4
RETURNING *;
-- name: SetLastReconciled :exec
UPDATE accounts
SET last_reconciled = NOW()
WHERE accounts.id = $1;

View File

@ -16,3 +16,24 @@ WHERE categories.id = assignments.category_id AND category_groups.budget_id = @b
SELECT *
FROM assignments_by_month
WHERE assignments_by_month.budget_id = @budget_id;
-- name: GetAllAssignments :many
SELECT assignments.date, categories.name as category, category_groups.name as group, assignments.amount
FROM assignments
INNER JOIN categories ON categories.id = assignments.category_id
INNER JOIN category_groups ON categories.category_group_id = category_groups.id
WHERE category_groups.budget_id = @budget_id;
-- name: UpdateAssignment :exec
INSERT INTO assignments (category_id, date, amount)
VALUES($1, $2, $3)
ON CONFLICT (category_id, date)
DO
UPDATE SET amount = $3;
-- name: UpdateAssignmentWithDifference :exec
INSERT INTO assignments (category_id, date, amount)
VALUES($1, $2, $3)
ON CONFLICT (category_id, date)
DO
UPDATE SET amount = assignments.amount + $3;

View File

@ -21,9 +21,11 @@ WHERE category_groups.budget_id = $1
ORDER BY category_groups.name, categories.name;
-- name: SearchCategories :many
SELECT CONCAT(category_groups.name, ' : ', categories.name) as name, categories.id FROM categories
SELECT CONCAT(category_groups.name, ' : ', categories.name) as name, categories.id, 'category' as type
FROM categories
INNER JOIN category_groups ON categories.category_group_id = category_groups.id
WHERE category_groups.budget_id = @budget_id
AND categories.name LIKE @search
AND categories.name ILIKE @search
AND category_groups.name != 'Hidden Categories'
ORDER BY category_groups.name, categories.name;
--ORDER BY levenshtein(payees.name, $2);

View File

@ -10,8 +10,8 @@ WHERE payees.budget_id = $1
ORDER BY name;
-- name: SearchPayees :many
SELECT payees.* FROM payees
SELECT payees.*, 'payee' as type FROM payees
WHERE payees.budget_id = @budget_id
AND payees.name LIKE @search
AND payees.name ILIKE @search
ORDER BY payees.name;
--ORDER BY levenshtein(payees.name, $2);

View File

@ -1,60 +1,40 @@
-- name: GetTransaction :one
SELECT * FROM transactions
SELECT * FROM display_transactions
WHERE id = $1;
-- name: CreateTransaction :one
INSERT INTO transactions
(date, memo, amount, account_id, payee_id, category_id, group_id, status)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
RETURNING *;
RETURNING id;
-- name: UpdateTransaction :exec
UPDATE transactions
SET date = $1,
memo = $2,
amount = $3,
account_id = $4,
payee_id = $5,
category_id = $6
WHERE id = $7;
payee_id = $4,
category_id = $5
WHERE id = $6;
-- name: SetTransactionReconciled :exec
UPDATE transactions
SET status = 'Reconciled'
WHERE id = $1;
-- name: DeleteTransaction :exec
DELETE FROM transactions
WHERE id = $1;
-- name: GetTransactionsForBudget :many
SELECT transactions.id, transactions.date, transactions.memo, transactions.amount, transactions.group_id, transactions.status,
accounts.name as account, COALESCE(payees.name, '') as payee, COALESCE(category_groups.name, '') as category_group, COALESCE(categories.name, '') as category
FROM transactions
INNER JOIN accounts ON accounts.id = transactions.account_id
LEFT JOIN payees ON payees.id = transactions.payee_id
LEFT JOIN categories ON categories.id = transactions.category_id
LEFT JOIN category_groups ON category_groups.id = categories.category_group_id
WHERE accounts.budget_id = $1
ORDER BY transactions.date DESC
LIMIT 200;
-- name: GetAllTransactionsForBudget :many
SELECT t.*
FROM display_transactions AS t
WHERE t.budget_id = $1;
-- name: GetTransactionsForAccount :many
SELECT transactions.id, transactions.date, transactions.memo,
transactions.amount, transactions.group_id, transactions.status,
accounts.name as account,
COALESCE(payees.name, '') as payee,
COALESCE(category_groups.name, '') as category_group,
COALESCE(categories.name, '') as category,
(
SELECT CONCAT(otherAccounts.name)
FROM transactions otherTransactions
LEFT JOIN accounts otherAccounts ON otherAccounts.id = otherTransactions.account_id
WHERE otherTransactions.group_id = transactions.group_id
AND otherTransactions.id != transactions.id
) as transfer_account
FROM transactions
INNER JOIN accounts ON accounts.id = transactions.account_id
LEFT JOIN payees ON payees.id = transactions.payee_id
LEFT JOIN categories ON categories.id = transactions.category_id
LEFT JOIN category_groups ON category_groups.id = categories.category_group_id
WHERE transactions.account_id = $1
ORDER BY transactions.date DESC
SELECT t.*
FROM display_transactions AS t
WHERE t.account_id = $1
LIMIT 200;
-- name: DeleteAllTransactions :execrows

View File

@ -0,0 +1,25 @@
-- +goose Up
CREATE VIEW display_transactions AS
SELECT transactions.id, transactions.date, transactions.memo,
transactions.amount, transactions.group_id, transactions.status,
accounts.name as account, transactions.payee_id, transactions.category_id,
COALESCE(payees.name, '') as payee,
COALESCE(category_groups.name, '') as category_group,
COALESCE(categories.name, '') as category,
COALESCE((
SELECT CONCAT(otherAccounts.name)
FROM transactions otherTransactions
LEFT JOIN accounts otherAccounts ON otherAccounts.id = otherTransactions.account_id
WHERE otherTransactions.group_id = transactions.group_id
AND otherTransactions.id != transactions.id
), '')::text as transfer_account,
accounts.budget_id, transactions.account_id
FROM transactions
INNER JOIN accounts ON accounts.id = transactions.account_id
LEFT JOIN payees ON payees.id = transactions.payee_id
LEFT JOIN categories ON categories.id = transactions.category_id
LEFT JOIN category_groups ON category_groups.id = categories.category_group_id
ORDER BY transactions.date DESC;
-- +goose Down
DROP VIEW display_transactions;

View File

@ -0,0 +1,5 @@
-- +goose Up
ALTER TABLE accounts ADD COLUMN is_open BOOLEAN NOT NULL DEFAULT TRUE;
-- +goose Down
ALTER TABLE accounts DROP COLUMN is_open;

View File

@ -0,0 +1,6 @@
-- +goose Up
ALTER TABLE assignments DROP id;
ALTER TABLE assignments ADD PRIMARY KEY (category_id, date);
-- +goose Down
ALTER TABLE assignments ADD COLUMN id uuid DEFAULT uuid_generate_v4() PRIMARY KEY;

View File

@ -0,0 +1,12 @@
-- +goose Up
ALTER TABLE accounts ADD COLUMN last_reconciled date NULL;
UPDATE accounts
SET last_reconciled = (
SELECT MAX(transactions.date)
FROM transactions
WHERE transactions.account_id = accounts.id
AND transactions.status = 'Reconciled'
);
-- +goose Down
ALTER TABLE accounts DROP COLUMN last_reconciled;

View File

@ -7,6 +7,7 @@ import (
"context"
"time"
"git.javil.eu/jacob1123/budgeteer/postgres/numeric"
"github.com/google/uuid"
)
@ -14,13 +15,13 @@ const createTransaction = `-- name: CreateTransaction :one
INSERT INTO transactions
(date, memo, amount, account_id, payee_id, category_id, group_id, status)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
RETURNING id, date, memo, amount, account_id, category_id, payee_id, group_id, status
RETURNING id
`
type CreateTransactionParams struct {
Date time.Time
Memo string
Amount Numeric
Amount numeric.Numeric
AccountID uuid.UUID
PayeeID uuid.NullUUID
CategoryID uuid.NullUUID
@ -28,7 +29,7 @@ type CreateTransactionParams struct {
Status TransactionStatus
}
func (q *Queries) CreateTransaction(ctx context.Context, arg CreateTransactionParams) (Transaction, error) {
func (q *Queries) CreateTransaction(ctx context.Context, arg CreateTransactionParams) (uuid.UUID, error) {
row := q.db.QueryRowContext(ctx, createTransaction,
arg.Date,
arg.Memo,
@ -39,19 +40,9 @@ func (q *Queries) CreateTransaction(ctx context.Context, arg CreateTransactionPa
arg.GroupID,
arg.Status,
)
var i Transaction
err := row.Scan(
&i.ID,
&i.Date,
&i.Memo,
&i.Amount,
&i.AccountID,
&i.CategoryID,
&i.PayeeID,
&i.GroupID,
&i.Status,
)
return i, err
var id uuid.UUID
err := row.Scan(&id)
return id, err
}
const deleteAllTransactions = `-- name: DeleteAllTransactions :execrows
@ -79,24 +70,75 @@ func (q *Queries) DeleteTransaction(ctx context.Context, id uuid.UUID) error {
return err
}
const getAllTransactionsForBudget = `-- name: GetAllTransactionsForBudget :many
SELECT t.id, t.date, t.memo, t.amount, t.group_id, t.status, t.account, t.payee_id, t.category_id, t.payee, t.category_group, t.category, t.transfer_account, t.budget_id, t.account_id
FROM display_transactions AS t
WHERE t.budget_id = $1
`
func (q *Queries) GetAllTransactionsForBudget(ctx context.Context, budgetID uuid.UUID) ([]DisplayTransaction, error) {
rows, err := q.db.QueryContext(ctx, getAllTransactionsForBudget, budgetID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []DisplayTransaction
for rows.Next() {
var i DisplayTransaction
if err := rows.Scan(
&i.ID,
&i.Date,
&i.Memo,
&i.Amount,
&i.GroupID,
&i.Status,
&i.Account,
&i.PayeeID,
&i.CategoryID,
&i.Payee,
&i.CategoryGroup,
&i.Category,
&i.TransferAccount,
&i.BudgetID,
&i.AccountID,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Close(); err != nil {
return nil, err
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const getTransaction = `-- name: GetTransaction :one
SELECT id, date, memo, amount, account_id, category_id, payee_id, group_id, status FROM transactions
SELECT id, date, memo, amount, group_id, status, account, payee_id, category_id, payee, category_group, category, transfer_account, budget_id, account_id FROM display_transactions
WHERE id = $1
`
func (q *Queries) GetTransaction(ctx context.Context, id uuid.UUID) (Transaction, error) {
func (q *Queries) GetTransaction(ctx context.Context, id uuid.UUID) (DisplayTransaction, error) {
row := q.db.QueryRowContext(ctx, getTransaction, id)
var i Transaction
var i DisplayTransaction
err := row.Scan(
&i.ID,
&i.Date,
&i.Memo,
&i.Amount,
&i.AccountID,
&i.CategoryID,
&i.PayeeID,
&i.GroupID,
&i.Status,
&i.Account,
&i.PayeeID,
&i.CategoryID,
&i.Payee,
&i.CategoryGroup,
&i.Category,
&i.TransferAccount,
&i.BudgetID,
&i.AccountID,
)
return i, err
}
@ -136,52 +178,21 @@ func (q *Queries) GetTransactionsByMonthAndCategory(ctx context.Context, budgetI
}
const getTransactionsForAccount = `-- name: GetTransactionsForAccount :many
SELECT transactions.id, transactions.date, transactions.memo,
transactions.amount, transactions.group_id, transactions.status,
accounts.name as account,
COALESCE(payees.name, '') as payee,
COALESCE(category_groups.name, '') as category_group,
COALESCE(categories.name, '') as category,
(
SELECT CONCAT(otherAccounts.name)
FROM transactions otherTransactions
LEFT JOIN accounts otherAccounts ON otherAccounts.id = otherTransactions.account_id
WHERE otherTransactions.group_id = transactions.group_id
AND otherTransactions.id != transactions.id
) as transfer_account
FROM transactions
INNER JOIN accounts ON accounts.id = transactions.account_id
LEFT JOIN payees ON payees.id = transactions.payee_id
LEFT JOIN categories ON categories.id = transactions.category_id
LEFT JOIN category_groups ON category_groups.id = categories.category_group_id
WHERE transactions.account_id = $1
ORDER BY transactions.date DESC
SELECT t.id, t.date, t.memo, t.amount, t.group_id, t.status, t.account, t.payee_id, t.category_id, t.payee, t.category_group, t.category, t.transfer_account, t.budget_id, t.account_id
FROM display_transactions AS t
WHERE t.account_id = $1
LIMIT 200
`
type GetTransactionsForAccountRow struct {
ID uuid.UUID
Date time.Time
Memo string
Amount Numeric
GroupID uuid.NullUUID
Status TransactionStatus
Account string
Payee string
CategoryGroup string
Category string
TransferAccount interface{}
}
func (q *Queries) GetTransactionsForAccount(ctx context.Context, accountID uuid.UUID) ([]GetTransactionsForAccountRow, error) {
func (q *Queries) GetTransactionsForAccount(ctx context.Context, accountID uuid.UUID) ([]DisplayTransaction, error) {
rows, err := q.db.QueryContext(ctx, getTransactionsForAccount, accountID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []GetTransactionsForAccountRow
var items []DisplayTransaction
for rows.Next() {
var i GetTransactionsForAccountRow
var i DisplayTransaction
if err := rows.Scan(
&i.ID,
&i.Date,
@ -190,10 +201,14 @@ func (q *Queries) GetTransactionsForAccount(ctx context.Context, accountID uuid.
&i.GroupID,
&i.Status,
&i.Account,
&i.PayeeID,
&i.CategoryID,
&i.Payee,
&i.CategoryGroup,
&i.Category,
&i.TransferAccount,
&i.BudgetID,
&i.AccountID,
); err != nil {
return nil, err
}
@ -208,64 +223,15 @@ func (q *Queries) GetTransactionsForAccount(ctx context.Context, accountID uuid.
return items, nil
}
const getTransactionsForBudget = `-- name: GetTransactionsForBudget :many
SELECT transactions.id, transactions.date, transactions.memo, transactions.amount, transactions.group_id, transactions.status,
accounts.name as account, COALESCE(payees.name, '') as payee, COALESCE(category_groups.name, '') as category_group, COALESCE(categories.name, '') as category
FROM transactions
INNER JOIN accounts ON accounts.id = transactions.account_id
LEFT JOIN payees ON payees.id = transactions.payee_id
LEFT JOIN categories ON categories.id = transactions.category_id
LEFT JOIN category_groups ON category_groups.id = categories.category_group_id
WHERE accounts.budget_id = $1
ORDER BY transactions.date DESC
LIMIT 200
const setTransactionReconciled = `-- name: SetTransactionReconciled :exec
UPDATE transactions
SET status = 'Reconciled'
WHERE id = $1
`
type GetTransactionsForBudgetRow struct {
ID uuid.UUID
Date time.Time
Memo string
Amount Numeric
GroupID uuid.NullUUID
Status TransactionStatus
Account string
Payee string
CategoryGroup string
Category string
}
func (q *Queries) GetTransactionsForBudget(ctx context.Context, budgetID uuid.UUID) ([]GetTransactionsForBudgetRow, error) {
rows, err := q.db.QueryContext(ctx, getTransactionsForBudget, budgetID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []GetTransactionsForBudgetRow
for rows.Next() {
var i GetTransactionsForBudgetRow
if err := rows.Scan(
&i.ID,
&i.Date,
&i.Memo,
&i.Amount,
&i.GroupID,
&i.Status,
&i.Account,
&i.Payee,
&i.CategoryGroup,
&i.Category,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Close(); err != nil {
return nil, err
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
func (q *Queries) SetTransactionReconciled(ctx context.Context, id uuid.UUID) error {
_, err := q.db.ExecContext(ctx, setTransactionReconciled, id)
return err
}
const updateTransaction = `-- name: UpdateTransaction :exec
@ -273,17 +239,15 @@ UPDATE transactions
SET date = $1,
memo = $2,
amount = $3,
account_id = $4,
payee_id = $5,
category_id = $6
WHERE id = $7
payee_id = $4,
category_id = $5
WHERE id = $6
`
type UpdateTransactionParams struct {
Date time.Time
Memo string
Amount Numeric
AccountID uuid.UUID
Amount numeric.Numeric
PayeeID uuid.NullUUID
CategoryID uuid.NullUUID
ID uuid.UUID
@ -294,7 +258,6 @@ func (q *Queries) UpdateTransaction(ctx context.Context, arg UpdateTransactionPa
arg.Date,
arg.Memo,
arg.Amount,
arg.AccountID,
arg.PayeeID,
arg.CategoryID,
arg.ID,

144
postgres/ynab-export.go Normal file
View File

@ -0,0 +1,144 @@
package postgres
import (
"context"
"encoding/csv"
"fmt"
"io"
"git.javil.eu/jacob1123/budgeteer/postgres/numeric"
"github.com/google/uuid"
)
type YNABExport struct {
queries *Queries
budgetID uuid.UUID
}
func NewYNABExport(context context.Context, queries *Queries, budgetID uuid.UUID) (*YNABExport, error) {
return &YNABExport{
queries: queries,
budgetID: budgetID,
}, nil
}
// ImportAssignments expects a TSV-file as exported by YNAB in the following format:
// "Month" "Category Group/Category" "Category Group" "Category" "Budgeted" "Activity" "Available"
// "Apr 2019" "Income: Next Month" "Income" "Next Month" 0,00€ 0,00€ 0,00€
//
// Activity and Available are not imported, since they are determined by the transactions and historic assignments.
func (ynab *YNABExport) ExportAssignments(context context.Context, w io.Writer) error {
csv := csv.NewWriter(w)
csv.Comma = '\t'
assignments, err := ynab.queries.GetAllAssignments(context, ynab.budgetID)
if err != nil {
return fmt.Errorf("load assignments: %w", err)
}
count := 0
for _, assignment := range assignments {
row := []string{
assignment.Date.Format("Jan 2006"),
assignment.Group + ": " + assignment.Category,
assignment.Group,
assignment.Category,
assignment.Amount.String() + "€",
numeric.Zero().String() + "€",
numeric.Zero().String() + "€",
}
err := csv.Write(row)
if err != nil {
return fmt.Errorf("write assignment: %w", err)
}
count++
}
csv.Flush()
fmt.Printf("Exported %d assignments\n", count)
return nil
}
// ImportTransactions expects a TSV-file as exported by YNAB in the following format:
// "Account" "Flag" "Date" "Payee" "Category Group/Category" "Category Group" "Category" "Memo" "Outflow" "Inflow" "Cleared"
// "Cash" "" "11.12.2021" "Transfer : Checking" "" "" "" "Brought to bank" 500,00€ 0,00€ "Cleared".
func (ynab *YNABExport) ExportTransactions(context context.Context, w io.Writer) error {
csv := csv.NewWriter(w)
csv.Comma = '\t'
transactions, err := ynab.queries.GetAllTransactionsForBudget(context, ynab.budgetID)
if err != nil {
return fmt.Errorf("load transactions: %w", err)
}
header := []string{
"Account",
"Flag",
"Date",
"Payee",
"Category Group/Category",
"Category Group",
"Category",
"Memo",
"Outflow",
"Inflow",
"Cleared",
}
err = csv.Write(header)
if err != nil {
return fmt.Errorf("write transaction: %w", err)
}
count := 0
for _, transaction := range transactions {
row := GetTransactionRow(transaction)
err := csv.Write(row)
if err != nil {
return fmt.Errorf("write transaction: %w", err)
}
count++
}
csv.Flush()
fmt.Printf("Exported %d transactions\n", count)
return nil
}
func GetTransactionRow(transaction DisplayTransaction) []string {
row := []string{
transaction.Account,
"", // Flag
transaction.Date.Format("02.01.2006"),
}
if transaction.TransferAccount != "" {
row = append(row, "Transfer : "+transaction.TransferAccount)
} else {
row = append(row, transaction.Payee)
}
if transaction.CategoryGroup != "" && transaction.Category != "" {
row = append(row,
transaction.CategoryGroup+": "+transaction.Category,
transaction.CategoryGroup,
transaction.Category)
} else {
row = append(row, "", "", "")
}
row = append(row, transaction.Memo)
if transaction.Amount.IsPositive() {
row = append(row, numeric.Zero().String()+"€", transaction.Amount.String()+"€")
} else {
row = append(row, transaction.Amount.String()[1:]+"€", numeric.Zero().String()+"€")
}
return append(row, string(transaction.Status))
}

View File

@ -7,8 +7,8 @@ import (
"io"
"strings"
"time"
"unicode/utf8"
"git.javil.eu/jacob1123/budgeteer/postgres/numeric"
"github.com/google/uuid"
)
@ -91,12 +91,12 @@ func (ynab *YNABImport) ImportAssignments(context context.Context, r io.Reader)
continue
}
assignment := CreateAssignmentParams{
assignment := UpdateAssignmentWithDifferenceParams{
Date: date,
CategoryID: category.UUID,
Amount: amount,
}
_, err = ynab.queries.CreateAssignment(context, assignment)
err = ynab.queries.UpdateAssignmentWithDifference(context, assignment)
if err != nil {
return fmt.Errorf("save assignment %v: %w", assignment, err)
}
@ -116,7 +116,9 @@ type Transfer struct {
ToAccount string
}
// ImportTransactions expects a TSV-file as exported by YNAB.
// ImportTransactions expects a TSV-file as exported by YNAB in the following format:
// "Account" "Flag" "Date" "Payee" "Category Group/Category" "Category Group" "Category" "Memo" "Outflow" "Inflow" "Cleared"
// "Cash" "" "11.12.2021" "Transfer : Checking" "" "" "" "Brought to bank" 500,00€ 0,00€ "Cleared".
func (ynab *YNABImport) ImportTransactions(context context.Context, r io.Reader) error {
csv := csv.NewReader(r)
csv.Comma = '\t'
@ -224,7 +226,8 @@ func (ynab *YNABImport) GetTransaction(context context.Context, record []string)
}
func (ynab *YNABImport) ImportRegularTransaction(context context.Context, payeeName string,
transaction CreateTransactionParams) error {
transaction CreateTransactionParams,
) error {
payeeID, err := ynab.GetPayee(context, payeeName)
if err != nil {
return fmt.Errorf("get payee %s: %w", payeeName, err)
@ -240,7 +243,8 @@ func (ynab *YNABImport) ImportRegularTransaction(context context.Context, payeeN
func (ynab *YNABImport) ImportTransferTransaction(context context.Context, payeeName string,
transaction CreateTransactionParams, openTransfers *[]Transfer,
account *Account, amount Numeric) error {
account *Account, amount numeric.Numeric,
) error {
transferToAccountName := payeeName[11:]
transferToAccount, err := ynab.GetAccount(context, transferToAccountName)
if err != nil {
@ -293,35 +297,22 @@ func (ynab *YNABImport) ImportTransferTransaction(context context.Context, payee
return nil
}
func trimLastChar(s string) string {
r, size := utf8.DecodeLastRuneInString(s)
if r == utf8.RuneError && (size == 0 || size == 1) {
size = 0
}
return s[:len(s)-size]
}
func GetAmount(inflow string, outflow string) (Numeric, error) {
// Remove trailing currency
inflow = strings.Replace(trimLastChar(inflow), ",", ".", 1)
outflow = strings.Replace(trimLastChar(outflow), ",", ".", 1)
num := Numeric{}
err := num.Set(inflow)
func GetAmount(inflow string, outflow string) (numeric.Numeric, error) {
in, err := numeric.ParseCurrency(inflow)
if err != nil {
return num, fmt.Errorf("parse inflow %s: %w", inflow, err)
return in, fmt.Errorf("parse inflow: %w", err)
}
if !in.IsZero() {
return in, nil
}
// if inflow is zero, use outflow
if num.Int.Int64() != 0 {
return num, nil
}
err = num.Set("-" + outflow)
out, err := numeric.ParseCurrency("-" + outflow)
if err != nil {
return num, fmt.Errorf("parse outflow %s: %w", inflow, err)
return out, fmt.Errorf("parse outflow: %w", err)
}
return num, nil
return out, nil
}
func (ynab *YNABImport) GetAccount(context context.Context, name string) (*Account, error) {

View File

@ -33,5 +33,41 @@ func (h *Handler) transactionsForAccount(c *gin.Context) {
type TransactionsResponse struct {
Account postgres.Account
Transactions []postgres.GetTransactionsForAccountRow
Transactions []postgres.DisplayTransaction
}
type EditAccountRequest struct {
Name string `json:"name"`
OnBudget bool `json:"onBudget"`
IsOpen bool `json:"isOpen"`
}
func (h *Handler) editAccount(c *gin.Context) {
accountID := c.Param("accountid")
accountUUID, err := uuid.Parse(accountID)
if err != nil {
c.AbortWithError(http.StatusBadRequest, err)
return
}
var request EditAccountRequest
err = c.BindJSON(&request)
if err != nil {
c.AbortWithError(http.StatusBadRequest, err)
return
}
updateParams := postgres.UpdateAccountParams{
Name: request.Name,
OnBudget: request.OnBudget,
IsOpen: request.IsOpen,
ID: accountUUID,
}
account, err := h.Service.UpdateAccount(c.Request.Context(), updateParams)
if err != nil {
c.AbortWithError(http.StatusNotFound, err)
return
}
h.returnBudgetingData(c, account.BudgetID)
}

View File

@ -2,6 +2,7 @@ package server
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
@ -22,15 +23,15 @@ func TestRegisterUser(t *testing.T) { //nolint:funlen
t.Parallel()
database, err := postgres.Connect("pgtx", "example")
if err != nil {
t.Errorf("could not connect to db: %s", err)
fmt.Printf("could not connect to db: %s\n", err)
t.Skip()
return
}
tokenVerifier, _ := jwt.NewTokenVerifier("this_is_my_demo_secret_for_unit_tests")
h := Handler{
Service: database,
TokenVerifier: &jwt.TokenVerifier{
Secret: "this_is_my_demo_secret_for_unit_tests",
},
TokenVerifier: tokenVerifier,
CredentialsVerifier: &bcrypt.Verifier{},
}

View File

@ -2,6 +2,7 @@ package server
import (
"net/http"
"strings"
"git.javil.eu/jacob1123/budgeteer/postgres"
"github.com/gin-gonic/gin"
@ -39,10 +40,27 @@ func (h *Handler) autocompletePayee(c *gin.Context) {
}
query := c.Request.URL.Query().Get("s")
transferPrefix := "Transfer"
if strings.HasPrefix(query, transferPrefix) {
searchParams := postgres.SearchAccountsParams{
BudgetID: budgetUUID,
Search: "%" + strings.Trim(query[len(transferPrefix):], " \t\n:") + "%",
}
accounts, err := h.Service.SearchAccounts(c.Request.Context(), searchParams)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
c.JSON(http.StatusOK, accounts)
} else {
searchParams := postgres.SearchPayeesParams{
BudgetID: budgetUUID,
Search: query + "%",
}
payees, err := h.Service.SearchPayees(c.Request.Context(), searchParams)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
@ -50,4 +68,5 @@ func (h *Handler) autocompletePayee(c *gin.Context) {
}
c.JSON(http.StatusOK, payees)
}
}

View File

@ -3,10 +3,10 @@ package server
import (
"fmt"
"net/http"
"strconv"
"time"
"git.javil.eu/jacob1123/budgeteer/postgres"
"git.javil.eu/jacob1123/budgeteer/postgres/numeric"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
@ -24,31 +24,20 @@ func getFirstOfMonthTime(date time.Time) time.Time {
type CategoryWithBalance struct {
*postgres.GetCategoriesRow
Available postgres.Numeric
AvailableLastMonth postgres.Numeric
Activity postgres.Numeric
Assigned postgres.Numeric
Available numeric.Numeric
AvailableLastMonth numeric.Numeric
Activity numeric.Numeric
Assigned numeric.Numeric
}
func getDate(c *gin.Context) (time.Time, error) {
var year, month int
yearString := c.Param("year")
monthString := c.Param("month")
if yearString == "" && monthString == "" {
return getFirstOfMonthTime(time.Now()), nil
func NewCategoryWithBalance(category *postgres.GetCategoriesRow) CategoryWithBalance {
return CategoryWithBalance{
GetCategoriesRow: category,
Available: numeric.Zero(),
AvailableLastMonth: numeric.Zero(),
Activity: numeric.Zero(),
Assigned: numeric.Zero(),
}
year, err := strconv.Atoi(yearString)
if err != nil {
return time.Time{}, fmt.Errorf("parse year: %w", err)
}
month, err = strconv.Atoi(monthString)
if err != nil {
return time.Time{}, fmt.Errorf("parse month: %w", err)
}
return getFirstOfMonth(year, month, time.Now().Location()), nil
}
func (h *Handler) budgetingForMonth(c *gin.Context) {
@ -86,28 +75,31 @@ func (h *Handler) budgetingForMonth(c *gin.Context) {
categoriesWithBalance, moneyUsed := h.calculateBalances(
budget, firstOfNextMonth, firstOfMonth, categories, cumultativeBalances)
availableBalance := h.getAvailableBalance(budget, moneyUsed, cumultativeBalances, firstOfNextMonth)
for i := range categoriesWithBalance {
cat := &categoriesWithBalance[i]
if cat.ID != budget.IncomeCategoryID {
continue
}
availableBalance := h.getAvailableBalance(categories, budget, moneyUsed, cumultativeBalances, firstOfNextMonth)
cat.Available = availableBalance
cat.AvailableLastMonth = availableBalance
}
data := struct {
Categories []CategoryWithBalance
AvailableBalance postgres.Numeric
AvailableBalance numeric.Numeric
}{categoriesWithBalance, availableBalance}
c.JSON(http.StatusOK, data)
}
func (*Handler) getAvailableBalance(categories []postgres.GetCategoriesRow, budget postgres.Budget,
moneyUsed postgres.Numeric, cumultativeBalances []postgres.GetCumultativeBalancesRow,
firstOfNextMonth time.Time) postgres.Numeric {
availableBalance := postgres.NewZeroNumeric()
for _, cat := range categories {
if cat.ID != budget.IncomeCategoryID {
continue
}
availableBalance = moneyUsed
func (*Handler) getAvailableBalance(budget postgres.Budget,
moneyUsed numeric.Numeric, cumultativeBalances []postgres.GetCumultativeBalancesRow,
firstOfNextMonth time.Time) numeric.Numeric {
availableBalance := moneyUsed
for _, bal := range cumultativeBalances {
if bal.CategoryID != cat.ID {
if bal.CategoryID != budget.IncomeCategoryID {
continue
}
@ -115,12 +107,17 @@ func (*Handler) getAvailableBalance(categories []postgres.GetCategoriesRow, budg
continue
}
availableBalance = availableBalance.Add(bal.Transactions)
}
availableBalance.AddI(bal.Transactions)
availableBalance.AddI(bal.Assignments)
}
return availableBalance
}
type BudgetingResponse struct {
Accounts []postgres.GetAccountsWithBalanceRow
Budget postgres.Budget
}
func (h *Handler) budgeting(c *gin.Context) {
budgetID := c.Param("budgetid")
budgetUUID, err := uuid.Parse(budgetID)
@ -129,6 +126,10 @@ func (h *Handler) budgeting(c *gin.Context) {
return
}
h.returnBudgetingData(c, budgetUUID)
}
func (h *Handler) returnBudgetingData(c *gin.Context, budgetUUID uuid.UUID) {
budget, err := h.Service.GetBudget(c.Request.Context(), budgetUUID)
if err != nil {
c.AbortWithError(http.StatusNotFound, err)
@ -141,66 +142,34 @@ func (h *Handler) budgeting(c *gin.Context) {
return
}
data := struct {
Accounts []postgres.GetAccountsWithBalanceRow
Budget postgres.Budget
}{accounts, budget}
data := BudgetingResponse{accounts, budget}
c.JSON(http.StatusOK, data)
}
func (h *Handler) calculateBalances(budget postgres.Budget,
firstOfNextMonth time.Time, firstOfMonth time.Time, categories []postgres.GetCategoriesRow,
cumultativeBalances []postgres.GetCumultativeBalancesRow) ([]CategoryWithBalance, postgres.Numeric) {
cumultativeBalances []postgres.GetCumultativeBalancesRow) ([]CategoryWithBalance, numeric.Numeric) {
categoriesWithBalance := []CategoryWithBalance{}
hiddenCategory := CategoryWithBalance{
GetCategoriesRow: &postgres.GetCategoriesRow{
Name: "",
Group: "Hidden Categories",
},
Available: postgres.NewZeroNumeric(),
AvailableLastMonth: postgres.NewZeroNumeric(),
Activity: postgres.NewZeroNumeric(),
Assigned: postgres.NewZeroNumeric(),
}
moneyUsed := postgres.NewZeroNumeric()
moneyUsed2 := numeric.Zero()
moneyUsed := &moneyUsed2
for i := range categories {
cat := &categories[i]
// do not show hidden categories
categoryWithBalance := h.CalculateCategoryBalances(cat, cumultativeBalances,
firstOfNextMonth, &moneyUsed, firstOfMonth, hiddenCategory, budget)
if cat.Group == "Hidden Categories" {
hiddenCategory.Available = hiddenCategory.Available.Add(categoryWithBalance.Available)
hiddenCategory.AvailableLastMonth = hiddenCategory.AvailableLastMonth.Add(categoryWithBalance.AvailableLastMonth)
hiddenCategory.Activity = hiddenCategory.Activity.Add(categoryWithBalance.Activity)
hiddenCategory.Assigned = hiddenCategory.Assigned.Add(categoryWithBalance.Assigned)
continue
}
if cat.ID == budget.IncomeCategoryID {
continue
}
firstOfNextMonth, moneyUsed, firstOfMonth, budget)
categoriesWithBalance = append(categoriesWithBalance, categoryWithBalance)
}
categoriesWithBalance = append(categoriesWithBalance, hiddenCategory)
return categoriesWithBalance, moneyUsed
return categoriesWithBalance, *moneyUsed
}
func (*Handler) CalculateCategoryBalances(cat *postgres.GetCategoriesRow,
cumultativeBalances []postgres.GetCumultativeBalancesRow, firstOfNextMonth time.Time,
moneyUsed *postgres.Numeric, firstOfMonth time.Time, hiddenCategory CategoryWithBalance,
budget postgres.Budget) CategoryWithBalance {
categoryWithBalance := CategoryWithBalance{
GetCategoriesRow: cat,
Available: postgres.NewZeroNumeric(),
AvailableLastMonth: postgres.NewZeroNumeric(),
Activity: postgres.NewZeroNumeric(),
Assigned: postgres.NewZeroNumeric(),
}
moneyUsed *numeric.Numeric, firstOfMonth time.Time, budget postgres.Budget) CategoryWithBalance {
categoryWithBalance := NewCategoryWithBalance(cat)
for _, bal := range cumultativeBalances {
if bal.CategoryID != cat.ID {
continue
@ -211,12 +180,12 @@ func (*Handler) CalculateCategoryBalances(cat *postgres.GetCategoriesRow,
continue
}
*moneyUsed = moneyUsed.Sub(bal.Assignments)
categoryWithBalance.Available = categoryWithBalance.Available.Add(bal.Assignments)
categoryWithBalance.Available = categoryWithBalance.Available.Add(bal.Transactions)
moneyUsed.SubI(bal.Assignments)
categoryWithBalance.Available.AddI(bal.Assignments)
categoryWithBalance.Available.AddI(bal.Transactions)
if !categoryWithBalance.Available.IsPositive() && bal.Date.Before(firstOfMonth) {
*moneyUsed = moneyUsed.Add(categoryWithBalance.Available)
categoryWithBalance.Available = postgres.NewZeroNumeric()
moneyUsed.AddI(categoryWithBalance.Available)
categoryWithBalance.Available = numeric.Zero()
}
if bal.Date.Before(firstOfMonth) {

55
server/category.go Normal file
View File

@ -0,0 +1,55 @@
package server
import (
"fmt"
"net/http"
"git.javil.eu/jacob1123/budgeteer/postgres"
"git.javil.eu/jacob1123/budgeteer/postgres/numeric"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
type SetCategoryAssignmentRequest struct {
Assigned string
}
func (h *Handler) setCategoryAssignment(c *gin.Context) {
categoryID := c.Param("categoryid")
categoryUUID, err := uuid.Parse(categoryID)
if err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, ErrorResponse{"categoryid missing from URL"})
return
}
var request SetCategoryAssignmentRequest
err = c.BindJSON(&request)
if err != nil {
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("invalid payload: %w", err))
return
}
date, err := getDate(c)
if err != nil {
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("date invalid: %w", err))
return
}
var amount numeric.Numeric
err = amount.Set(request.Assigned)
if err != nil {
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("parse amount: %w", err))
return
}
updateArgs := postgres.UpdateAssignmentParams{
CategoryID: categoryUUID,
Date: date,
Amount: amount,
}
err = h.Service.UpdateAssignment(c.Request.Context(), updateArgs)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("update assignment: %w", err))
return
}
}

View File

@ -36,41 +36,43 @@ type ErrorResponse struct {
Message string
}
type SuccessResponse struct {
Message string
}
// LoadRoutes initializes all the routes.
func (h *Handler) LoadRoutes(router *gin.Engine) {
router.Use(enableCachingForStaticFiles())
router.NoRoute(h.ServeStatic)
withLogin := router.Group("")
withLogin.Use(h.verifyLoginWithRedirect)
withBudget := router.Group("")
withBudget.Use(h.verifyLoginWithForbidden)
withBudget.GET("/budget/:budgetid/:year/:month", h.budgeting)
withBudget.GET("/budget/:budgetid/settings/clean-negative", h.cleanNegativeBudget)
api := router.Group("/api/v1")
unauthenticated := api.Group("/user")
unauthenticated.GET("/login", func(c *gin.Context) { c.Redirect(http.StatusPermanentRedirect, "/login") })
unauthenticated.POST("/login", h.loginPost)
unauthenticated.POST("/register", h.registerPost)
anonymous := api.Group("/user")
anonymous.GET("/login", func(c *gin.Context) { c.Redirect(http.StatusPermanentRedirect, "/login") })
anonymous.POST("/login", h.loginPost)
anonymous.POST("/register", h.registerPost)
authenticated := api.Group("")
authenticated.Use(h.verifyLoginWithForbidden)
authenticated.GET("/dashboard", h.dashboard)
authenticated.GET("/account/:accountid/transactions", h.transactionsForAccount)
authenticated.POST("/account/:accountid/reconcile", h.reconcileTransactions)
authenticated.POST("/account/:accountid", h.editAccount)
authenticated.GET("/admin/clear-database", h.clearDatabase)
authenticated.GET("/budget/:budgetid", h.budgeting)
authenticated.GET("/budget/:budgetid/:year/:month", h.budgetingForMonth)
authenticated.GET("/budget/:budgetid/autocomplete/payees", h.autocompletePayee)
authenticated.GET("/budget/:budgetid/autocomplete/categories", h.autocompleteCategories)
authenticated.DELETE("/budget/:budgetid", h.deleteBudget)
authenticated.POST("/budget/:budgetid/import/ynab", h.importYNAB)
authenticated.POST("/budget/:budgetid/settings/clear", h.clearBudget)
budget := authenticated.Group("/budget")
budget.POST("/new", h.newBudget)
budget.GET("/:budgetid", h.budgeting)
budget.GET("/:budgetid/:year/:month", h.budgetingForMonth)
budget.POST("/:budgetid/category/:categoryid/:year/:month", h.setCategoryAssignment)
budget.GET("/:budgetid/autocomplete/payees", h.autocompletePayee)
budget.GET("/:budgetid/autocomplete/categories", h.autocompleteCategories)
budget.DELETE("/:budgetid", h.deleteBudget)
budget.POST("/:budgetid/import/ynab", h.importYNAB)
budget.POST("/:budgetid/export/ynab/transactions", h.exportYNABTransactions)
budget.POST("/:budgetid/export/ynab/assignments", h.exportYNABAssignments)
budget.POST("/:budgetid/settings/clear", h.clearBudget)
budget.POST("/:budgetid/settings/clean-negative", h.cleanNegativeBudget)
transaction := authenticated.Group("/transaction")
transaction.POST("/new", h.newTransaction)

109
server/reconcile.go Normal file
View File

@ -0,0 +1,109 @@
package server
import (
"database/sql"
"fmt"
"net/http"
"time"
"git.javil.eu/jacob1123/budgeteer/postgres"
"git.javil.eu/jacob1123/budgeteer/postgres/numeric"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
type ReconcileTransactionsRequest struct {
TransactionIDs []uuid.UUID `json:"transactionIds"`
ReconcilationTransactionAmount string `json:"reconciliationTransactionAmount"`
}
type ReconcileTransactionsResponse struct {
Message string
ReconciliationTransaction *postgres.DisplayTransaction
}
func (h *Handler) reconcileTransactions(c *gin.Context) {
accountID := c.Param("accountid")
accountUUID, err := uuid.Parse(accountID)
if err != nil {
c.AbortWithError(http.StatusBadRequest, err)
return
}
var request ReconcileTransactionsRequest
err = c.BindJSON(&request)
if err != nil {
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("parse request: %w", err))
return
}
var amount numeric.Numeric
err = amount.Set(request.ReconcilationTransactionAmount)
if err != nil {
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("parse request: %w", err))
return
}
tx, err := h.Service.BeginTx(c.Request.Context(), &sql.TxOptions{})
if err != nil {
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("begin tx: %w", err))
return
}
db := h.Service.WithTx(tx)
for _, transactionID := range request.TransactionIDs {
err := db.SetTransactionReconciled(c.Request.Context(), transactionID)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("update transaction: %w", err))
return
}
}
reconciliationTransaction, err := h.CreateReconcilationTransaction(amount, accountUUID, db, c)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("insert new transaction: %w", err))
return
}
err = h.Service.SetLastReconciled(c.Request.Context(), accountUUID)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("set last reconciled: %w", err))
return
}
err = tx.Commit()
if err != nil {
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("commit: %w", err))
return
}
c.JSON(http.StatusOK, ReconcileTransactionsResponse{
Message: fmt.Sprintf("Set status for %d transactions", len(request.TransactionIDs)),
ReconciliationTransaction: reconciliationTransaction,
})
}
func (*Handler) CreateReconcilationTransaction(amount numeric.Numeric, accountUUID uuid.UUID, db *postgres.Queries, c *gin.Context) (*postgres.DisplayTransaction, error) {
if amount.IsZero() {
return nil, nil //nolint: nilnil
}
createTransaction := postgres.CreateTransactionParams{
Date: time.Now(),
Memo: "Reconciliation Transaction",
Amount: amount,
AccountID: accountUUID,
Status: "Reconciled",
}
transactionUUID, err := db.CreateTransaction(c.Request.Context(), createTransaction)
if err != nil {
return nil, fmt.Errorf("insert new transaction: %w", err)
}
transaction, err := db.GetTransaction(c.Request.Context(), transactionUUID)
if err != nil {
return nil, fmt.Errorf("get created transaction: %w", err)
}
return &transaction, nil
}

View File

@ -19,7 +19,7 @@ const (
func MustGetToken(c *gin.Context) budgeteer.Token { //nolint:ireturn
token := c.MustGet(ParamName)
if token, ok := token.(budgeteer.Token); !ok {
if token, ok := token.(budgeteer.Token); ok {
return token
}
@ -53,18 +53,6 @@ func (h *Handler) verifyLoginWithForbidden(c *gin.Context) {
c.Next()
}
func (h *Handler) verifyLoginWithRedirect(c *gin.Context) {
token, err := h.verifyLogin(c)
if err != nil {
c.Redirect(http.StatusTemporaryRedirect, "/login")
c.Abort()
return
}
c.Set(ParamName, token)
c.Next()
}
type loginInformation struct {
Password string `json:"password"`
User string `json:"user"`

View File

@ -1,11 +1,13 @@
package server
import (
"context"
"fmt"
"net/http"
"time"
"git.javil.eu/jacob1123/budgeteer/postgres"
"git.javil.eu/jacob1123/budgeteer/postgres/numeric"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
@ -15,11 +17,9 @@ type NewTransactionPayload struct {
Payee struct {
ID uuid.NullUUID
Name string
Type string
} `json:"payee"`
Category struct {
ID uuid.NullUUID
Name string
} `json:"category"`
CategoryID uuid.NullUUID `json:"categoryId"`
Memo string `json:"memo"`
Amount string `json:"amount"`
BudgetID uuid.UUID `json:"budgetId"`
@ -35,44 +35,125 @@ func (h *Handler) newTransaction(c *gin.Context) {
return
}
amount := postgres.Numeric{}
err = amount.Set(payload.Amount)
amount, err := numeric.Parse(payload.Amount)
if err != nil {
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("amount: %w", err))
return
}
payeeID := payload.Payee.ID
if !payeeID.Valid && payload.Payee.Name != "" {
newPayee := postgres.CreatePayeeParams{
Name: payload.Payee.Name,
BudgetID: payload.BudgetID,
}
payee, err := h.Service.CreatePayee(c.Request.Context(), newPayee)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("create payee: %w", err))
}
payeeID = uuid.NullUUID{
UUID: payee.ID,
Valid: true,
}
transactionID := c.Param("transactionid")
if transactionID != "" {
h.UpdateTransaction(payload, amount, transactionID, c)
return
}
newTransaction := postgres.CreateTransactionParams{
Memo: payload.Memo,
Date: time.Time(payload.Date),
Amount: amount,
AccountID: payload.AccountID,
PayeeID: payeeID,
CategoryID: payload.Category.ID,
Status: postgres.TransactionStatus(payload.State),
CategoryID: payload.CategoryID,
AccountID: payload.AccountID,
}
transaction, err := h.Service.CreateTransaction(c.Request.Context(), newTransaction)
if payload.Payee.Type == "account" {
groupID, err := h.CreateTransferForOtherAccount(newTransaction, amount, payload, c)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
newTransaction.GroupID = groupID
} else {
payeeID, err := GetPayeeID(c.Request.Context(), payload, h)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("create payee: %w", err))
}
newTransaction.PayeeID = payeeID
}
transactionUUID, err := h.Service.CreateTransaction(c.Request.Context(), newTransaction)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("create transaction: %w", err))
return
}
transaction, err := h.Service.GetTransaction(c.Request.Context(), transactionUUID)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("get transaction: %w", err))
return
}
c.JSON(http.StatusOK, transaction)
}
func (h *Handler) UpdateTransaction(payload NewTransactionPayload, amount numeric.Numeric, transactionID string, c *gin.Context) {
transactionUUID := uuid.MustParse(transactionID)
if amount.IsZero() {
err := h.Service.DeleteTransaction(c.Request.Context(), transactionUUID)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("delete transaction: %w", err))
}
return
}
editTransaction := postgres.UpdateTransactionParams{
Memo: payload.Memo,
Date: time.Time(payload.Date),
Amount: amount,
PayeeID: payload.Payee.ID,
CategoryID: payload.CategoryID,
ID: transactionUUID,
}
err := h.Service.UpdateTransaction(c.Request.Context(), editTransaction)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("edit transaction: %w", err))
return
}
transaction, err := h.Service.GetTransaction(c.Request.Context(), transactionUUID)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("get transaction: %w", err))
return
}
c.JSON(http.StatusOK, transaction)
}
func (h *Handler) CreateTransferForOtherAccount(newTransaction postgres.CreateTransactionParams, amount numeric.Numeric, payload NewTransactionPayload, c *gin.Context) (uuid.NullUUID, error) {
newTransaction.GroupID = uuid.NullUUID{UUID: uuid.New(), Valid: true}
newTransaction.Amount = amount.Neg()
newTransaction.AccountID = payload.Payee.ID.UUID
// transfer does not need category. Either it's account is off-budget or no category was supplied.
newTransaction.CategoryID = uuid.NullUUID{}
_, err := h.Service.CreateTransaction(c.Request.Context(), newTransaction)
if err != nil {
return uuid.NullUUID{}, fmt.Errorf("create transfer transaction: %w", err)
}
return newTransaction.GroupID, nil
}
func GetPayeeID(context context.Context, payload NewTransactionPayload, h *Handler) (uuid.NullUUID, error) {
payeeID := payload.Payee.ID
if payeeID.Valid {
return payeeID, nil
}
if payload.Payee.Name == "" {
return uuid.NullUUID{}, nil
}
newPayee := postgres.CreatePayeeParams{
Name: payload.Payee.Name,
BudgetID: payload.BudgetID,
}
payee, err := h.Service.CreatePayee(context, newPayee)
if err != nil {
return uuid.NullUUID{}, fmt.Errorf("create payee: %w", err)
}
return uuid.NullUUID{UUID: payee.ID, Valid: true}, nil
}

30
server/util.go Normal file
View File

@ -0,0 +1,30 @@
package server
import (
"fmt"
"strconv"
"time"
"github.com/gin-gonic/gin"
)
func getDate(c *gin.Context) (time.Time, error) {
var year, month int
yearString := c.Param("year")
monthString := c.Param("month")
if yearString == "" && monthString == "" {
return getFirstOfMonthTime(time.Now()), nil
}
year, err := strconv.Atoi(yearString)
if err != nil {
return time.Time{}, fmt.Errorf("parse year: %w", err)
}
month, err = strconv.Atoi(monthString)
if err != nil {
return time.Time{}, fmt.Errorf("parse month: %w", err)
}
return getFirstOfMonth(year, month, time.Now().Location()), nil
}

View File

@ -63,3 +63,55 @@ func (h *Handler) importYNAB(c *gin.Context) {
return
}
}
func (h *Handler) exportYNABTransactions(c *gin.Context) {
budgetID, succ := c.Params.Get("budgetid")
if !succ {
c.AbortWithStatusJSON(http.StatusBadRequest, ErrorResponse{"no budget_id specified"})
return
}
budgetUUID, err := uuid.Parse(budgetID)
if !succ {
c.AbortWithError(http.StatusBadRequest, err)
return
}
ynab, err := postgres.NewYNABExport(c.Request.Context(), h.Service.Queries, budgetUUID)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
err = ynab.ExportTransactions(c.Request.Context(), c.Writer)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
}
func (h *Handler) exportYNABAssignments(c *gin.Context) {
budgetID, succ := c.Params.Get("budgetid")
if !succ {
c.AbortWithStatusJSON(http.StatusBadRequest, ErrorResponse{"no budget_id specified"})
return
}
budgetUUID, err := uuid.Parse(budgetID)
if !succ {
c.AbortWithError(http.StatusBadRequest, err)
return
}
ynab, err := postgres.NewYNABExport(c.Request.Context(), h.Service.Queries, budgetUUID)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
err = ynab.ExportAssignments(c.Request.Context(), c.Writer)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
}

View File

@ -7,9 +7,11 @@ packages:
queries: "postgres/queries/"
overrides:
- go_type:
type: "Numeric"
import: "git.javil.eu/jacob1123/budgeteer/postgres/numeric"
type: Numeric
db_type: "pg_catalog.numeric"
- go_type:
type: "Numeric"
import: "git.javil.eu/jacob1123/budgeteer/postgres/numeric"
type: Numeric
db_type: "pg_catalog.numeric"
nullable: true

17
web/.eslintrc.js Normal file
View File

@ -0,0 +1,17 @@
module.exports = {
extends: [
// add more generic rulesets here, such as:
// 'eslint:recommended',
"plugin:vue/vue3-recommended",
// 'plugin:vue/recommended' // Use this if you are using Vue.js 2.x.
],
rules: {
// override/add rules settings here, such as:
// 'vue/no-unused-vars': 'error'
},
parser: "vue-eslint-parser",
parserOptions: {
parser: "@typescript-eslint/parser",
sourceType: "module",
},
};

View File

@ -6,7 +6,8 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite App</title>
</head>
<body>
<body
class="bg-slate-200 text-slate-800 dark:bg-slate-800 dark:text-slate-200 box-border w-full">
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>

View File

@ -11,6 +11,7 @@
"@mdi/font": "5.9.55",
"@vueuse/core": "^7.6.1",
"autoprefixer": "^10.4.2",
"file-saver": "^2.0.5",
"pinia": "^2.0.11",
"postcss": "^8.4.6",
"tailwindcss": "^3.0.18",
@ -18,13 +19,26 @@
"vue-router": "^4.0.12"
},
"devDependencies": {
"@types/file-saver": "^2.0.5",
"@typescript-eslint/parser": "^5.13.0",
"@vitejs/plugin-vue": "^2.0.0",
"@vue/cli-plugin-babel": "5.0.0-beta.7",
"@vue/cli-plugin-typescript": "~4.5.0",
"@vue/cli-service": "5.0.0-beta.7",
"eslint": "^8.10.0",
"eslint-plugin-vue": "^8.5.0",
"prettier": "2.5.1",
"sass": "^1.38.0",
"sass-loader": "^10.0.0",
"typescript": "^4.5.5",
"vite": "^2.7.2",
"vue-cli-plugin-vuetify": "~2.4.5"
}
"vue-tsc": "^0.32.0"
},
"prettier": {
"bracketSameLine": true,
"embeddedLanguageFormatting": "off",
"tabWidth": 4,
"useTabs": false
},
"eslintIgnore": ["index.css"]
}

View File

@ -3,4 +3,4 @@ module.exports = {
tailwindcss: {},
autoprefixer: {},
},
}
};

View File

@ -8,7 +8,6 @@ import { useSettingsStore } from "./stores/settings";
export default defineComponent({
computed: {
...mapState(useBudgetsStore, ["CurrentBudgetName"]),
...mapState(useSettingsStore, ["Menu"]),
...mapState(useSessionStore, ["LoggedIn"]),
},
methods: {
@ -27,39 +26,50 @@ export default defineComponent({
</script>
<template>
<div class="box-border w-full">
<div class="flex bg-gray-400 p-4 m-2 rounded-lg">
<span class="flex-1 font-bold text-5xl -my-3 hidden md:inline" @click="toggleMenuSize"></span>
<span class="flex-1 font-bold text-5xl -my-3 md:hidden" @click="toggleMenu"></span>
<div class="flex flex-col md:flex-row flex-1 h-screen">
<router-view name="sidebar" />
<div class="flex-1 overflow-auto">
<div
class="flex bg-gray-400 dark:bg-gray-600 p-4 fixed md:static top-0 left-0 w-full h-14"
>
<span
class="flex-1 font-bold text-5xl -my-3 hidden md:inline"
@click="toggleMenuSize"
></span>
<span
class="flex-1 font-bold text-5xl -my-3 md:hidden"
@click="toggleMenu"
></span>
<span class="flex-1">{{ CurrentBudgetName }}</span>
<div class="flex flex-1 flex-row justify-end -mx-4">
<router-link class="mx-4" v-if="LoggedIn" to="/dashboard">Dashboard</router-link>
<router-link class="mx-4" v-if="!LoggedIn" to="/login">Login</router-link>
<a class="mx-4" v-if="LoggedIn" @click="logout">Logout</a>
</div>
</div>
<div class="flex flex-col md:flex-row flex-1">
<div
:class="[Menu.Expand ? 'md:w-72' : 'md:w-36', Menu.Show ? '' : 'hidden']"
class="md:block flex-shrink-0 w-full"
<router-link
v-if="LoggedIn"
class="mx-4"
to="/dashboard"
>
<router-view name="sidebar"></router-view>
Dashboard
</router-link>
<router-link
v-if="!LoggedIn"
class="mx-4"
to="/login"
>
Login
</router-link>
<a
v-if="LoggedIn"
class="mx-4"
@click="logout"
>Logout</a>
</div>
</div>
<div class="flex-1 p-6">
<router-view></router-view>
<div class="p-3 pl-6">
<router-view />
</div>
</div>
</div>
</template>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
</style>

View File

@ -1,13 +1,13 @@
import { useSessionStore } from "./stores/session";
export const BASE_URL = "/api/v1"
export const BASE_URL = "/api/v1";
export function GET(path: string) {
const sessionStore = useSessionStore();
return fetch(BASE_URL + path, {
headers: sessionStore.AuthHeaders,
})
};
});
}
export function POST(path: string, body: FormData | string | null) {
const sessionStore = useSessionStore();
@ -15,12 +15,12 @@ export function POST(path: string, body: FormData | string | null) {
method: "POST",
headers: sessionStore.AuthHeaders,
body: body,
})
});
}
export function DELETE(path: string) {
const sessionStore = useSessionStore();
return fetch(BASE_URL + path, {
method: "DELETE",
headers: sessionStore.AuthHeaders,
})
});
}

View File

@ -0,0 +1,35 @@
<script lang="ts" setup>
import { computed } from 'vue';
import { useBudgetsStore } from '../stores/budget';
import { Account } from '../stores/budget-account';
const props = defineProps<{
account: Account
}>();
const budgetStore = useBudgetsStore();
const CurrentBudgetID = computed(() => budgetStore.CurrentBudgetID);
const days = 24 * 60 * 60 * 1000;
function daysSinceLastReconciled() {
const now = new Date().getTime();
const diff = new Date(now).getTime() - props.account.LastReconciled.Time.getTime();
return Math.floor(diff / days);
}
</script>
<template>
<span>
<router-link
:to="'/budget/' + CurrentBudgetID + '/account/' + account.ID"
>
{{ account.Name }}
</router-link>
<span
v-if="props.account.LastReconciled.Valid && daysSinceLastReconciled() > 7"
class="font-bold bg-gray-500 rounded-md text-sm px-2 mx-2 py-1 no-underline"
>
{{ daysSinceLastReconciled() }}
</span>
</span>
</template>

View File

@ -1,43 +1,39 @@
<script lang="ts" setup>
import { defineComponent, PropType, ref, watch } from "vue"
import { ref, watch } from "vue"
import { GET } from "../api";
import { useBudgetsStore } from "../stores/budget";
import Input from "./Input.vue";
export interface Suggestion {
ID: string
Name: string
}
interface Data {
Selected: Suggestion | undefined
SearchQuery: String
Suggestions: Suggestion[]
Type: string
}
const props = defineProps<{
modelValue: Suggestion | undefined,
type: String
text: string,
id: string | undefined,
model: string,
type?: string | undefined,
}>();
const Selected = ref<Suggestion | undefined>(props.modelValue || undefined);
const SearchQuery = ref(props.modelValue?.Name || "");
const SearchQuery = ref(props.text || "");
const Suggestions = ref<Array<Suggestion>>([]);
const emit = defineEmits(["update:modelValue"]);
const emit = defineEmits(["update:id", "update:text", "update:type"]);
watch(SearchQuery, () => {
load(SearchQuery.value);
});
function saveTransaction(e: MouseEvent) {
e.preventDefault();
};
function load(text: String) {
emit('update:modelValue', { ID: null, Name: text });
emit('update:id', null);
emit('update:text', text);
emit('update:type', undefined);
if (text == "") {
Suggestions.value = [];
return;
}
const budgetStore = useBudgetsStore();
GET("/budget/" + budgetStore.CurrentBudgetID + "/autocomplete/" + props.type + "?s=" + text)
GET("/budget/" + budgetStore.CurrentBudgetID + "/autocomplete/" + props.model + "?s=" + text)
.then(x => x.json())
.then(x => {
let suggestions = x || [];
@ -48,8 +44,9 @@ function load(text: String) {
});
};
function keypress(e: KeyboardEvent) {
console.log(e.key);
if (e.key == "Enter") {
if (e.key != "Enter")
return;
const selected = Suggestions.value[0];
selectElement(selected);
const el = (<HTMLInputElement>e.target);
@ -57,14 +54,15 @@ function keypress(e: KeyboardEvent) {
const currentIndex = inputElements.indexOf(el);
const nextElement = inputElements[currentIndex < inputElements.length - 1 ? currentIndex + 1 : 0];
(<HTMLInputElement>nextElement).focus();
};
}
};
function selectElement(element: Suggestion) {
Selected.value = element;
emit('update:id', element.ID);
emit('update:text', element.Name);
emit('update:type', element.Type);
Suggestions.value = [];
emit('update:modelValue', element);
};
function select(e: MouseEvent) {
const target = (<HTMLInputElement>e.target);
const valueAttribute = target.attributes.getNamedItem("value");
@ -74,27 +72,38 @@ function select(e: MouseEvent) {
const selected = Suggestions.value.filter(x => x.ID == selectedID)[0];
selectElement(selected);
};
function clear() {
Selected.value = undefined;
emit('update:modelValue', { ID: null, Name: SearchQuery.value });
emit('update:id', null);
emit('update:text', SearchQuery.value);
emit('update:type', undefined);
};
</script>
<template>
<div>
<input
<Input
v-if="id == undefined"
v-model="SearchQuery"
type="text"
class="border-b-2 border-black"
@keypress="keypress"
v-if="Selected == undefined"
v-model="SearchQuery"
/>
<span @click="clear" v-if="Selected != undefined" class="bg-gray-300">{{ Selected.Name }}</span>
<div v-if="Suggestions.length > 0" class="absolute bg-gray-400 w-64 p-2">
<span
v-if="id != undefined"
class="bg-gray-300 dark:bg-gray-700"
@click="clear"
>{{ text }}</span>
<div
v-if="Suggestions.length > 0"
class="absolute bg-gray-400 dark:bg-gray-600 w-64 p-2"
>
<span
v-for="suggestion in Suggestions"
:key="suggestion.ID"
class="block"
@click="select"
:value="suggestion.ID"
@click="select"
>{{ suggestion.Name }}</span>
</div>
</div>

View File

@ -1,8 +0,0 @@
<script lang="ts" setup>
</script>
<template>
<div class="flex flex-row items-center bg-gray-300 h-32 rounded-lg">
<slot></slot>
</div>
</template>

View File

@ -0,0 +1,15 @@
<script lang="ts" setup>
const props = defineProps<{modelValue?: boolean}>();
const emits = defineEmits<{
(e: "update:modelValue", value: boolean): void
}>();
</script>
<template>
<input
type="checkbox"
:checked="modelValue"
class="dark:bg-slate-900"
@change="emits('update:modelValue', ($event.target as HTMLInputElement)?.checked)"
>
</template>

View File

@ -1,7 +1,11 @@
<script lang="ts" setup>
import { computed } from 'vue';
const props = defineProps<{ value: number | undefined }>();
const props = defineProps<{
value: number | undefined
negativeClass?: string
positiveClass?: string
}>();
const internalValue = computed(() => Number(props.value ?? 0));
@ -11,5 +15,8 @@ const formattedValue = computed(() => internalValue.value.toLocaleString(undefin
</script>
<template>
<span class="text-right" :class="internalValue < 0 ? 'negative' : ''">{{ formattedValue }} </span>
<span
class="text-right"
:class="internalValue < 0 ? (negativeClass ?? 'negative') : positiveClass"
>{{ formattedValue }} </span>
</template>

View File

@ -0,0 +1,38 @@
<script lang="ts" setup>
import Input from './Input.vue';
const props = defineProps<{
modelValue?: Date
}>();
const emit = defineEmits(['update:modelValue']);
function dateToYYYYMMDD(d: Date | undefined) : string {
if(d == null)
return "";
// alternative implementations in https://stackoverflow.com/q/23593052/1850609
//return new Date(d.getTime() - (d.getTimezoneOffset() * 60 * 1000)).toISOString().split('T')[0];
return d.toISOString().split('T')[0];
}
function updateValue(event: Event) {
const target = event.target as HTMLInputElement;
emit('update:modelValue', target.valueAsDate);
}
function selectAll(event: FocusEvent) {
// Workaround for Safari bug
// http://stackoverflow.com/questions/1269722/selecting-text-on-focus-using-jquery-not-working-in-safari-and-chrome
setTimeout(function () {
const target = event.target as HTMLInputElement;
target.select()
}, 0)
}
</script>
<template>
<Input
ref="input"
type="date"
:value="dateToYYYYMMDD(modelValue)"
@input="updateValue"
@focus="selectAll"
/>
</template>

View File

@ -0,0 +1,17 @@
<script lang="ts" setup>
const props = defineProps<{
modelValue?: number | string
}>();
const emits = defineEmits<{
(e: "update:modelValue", value: number | string): void
}>();
</script>
<template>
<input
:value="modelValue"
class="dark:bg-slate-900"
@input="emits('update:modelValue', ($event.target as HTMLInputElement)?.value)"
>
</template>

View File

@ -0,0 +1,77 @@
<script lang="ts" setup>
import RowCard from './RowCard.vue';
import { ref } from "vue";
const props = defineProps<{
buttonText?: string,
}>();
const emit = defineEmits<{
(e: 'submit', event : {cancel:boolean}): boolean,
(e: 'open'): void,
}>();
const visible = ref(false);
function closeDialog() {
visible.value = false;
};
function openDialog() {
emit("open");
visible.value = true;
};
function submitDialog() {
const e = {cancel: false};
emit("submit", e);
if(e.cancel)
return;
visible.value = false;
}
</script>
<template>
<button @click="openDialog">
<slot name="placeholder">
<RowCard>
<p class="w-24 text-center text-6xl">
+
</p>
<span
class="text-lg"
dark
>{{ buttonText }}</span>
</RowCard>
</slot>
</button>
<div
v-if="visible"
class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full"
>
<div
class="relative top-20 mx-auto p-5 w-96 shadow-lg rounded-md bg-white dark:bg-black"
>
<div class="mt-3 text-center">
<h3
class="mt-3 text-lg leading-6 font-medium text-gray-900 dark:text-gray-100"
>
{{ buttonText }}
</h3>
<slot />
<div class="grid grid-cols-2 gap-6">
<button
class="px-4 py-2 bg-red-500 text-white text-base font-medium rounded-md shadow-sm hover:bg-green-600 focus:outline-none focus:ring-2 focus:ring-green-300"
@click="closeDialog"
>
Close
</button>
<button
class="px-4 py-2 bg-green-500 text-white text-base font-medium rounded-md shadow-sm hover:bg-green-600 focus:outline-none focus:ring-2 focus:ring-green-300"
@click="submitDialog"
>
Save
</button>
</div>
</div>
</div>
</div>
</template>

View File

@ -0,0 +1,9 @@
<script lang="ts" setup></script>
<template>
<div
class="flex flex-row items-center bg-gray-300 dark:bg-gray-700 rounded-lg"
>
<slot />
</div>
</template>

View File

@ -0,0 +1,7 @@
<script lang="ts" setup></script>
<template>
<button class="px-4 rounded-md shadow-sm focus:outline-none focus:ring-2">
<slot />
</button>
</template>

View File

@ -0,0 +1,87 @@
<script lang="ts" setup>
import { computed, ref } from "vue";
import Autocomplete from './Autocomplete.vue'
import { useAccountStore } from '../stores/budget-account'
import DateInput from "./DateInput.vue";
import { useTransactionsStore } from "../stores/transactions";
import Input from "./Input.vue";
import Button from "./SimpleButton.vue";
const props = defineProps<{
transactionid: string
}>()
const emit = defineEmits(["save"]);
const transactionsStore = useTransactionsStore();
const TX = transactionsStore.Transactions.get(props.transactionid)!;
const payeeType = ref<string|undefined>(undefined);
const payload = computed(() => JSON.stringify({
date: TX.Date.toISOString().split("T")[0],
payee: {
Name: TX.Payee,
ID: TX.PayeeID,
Type: payeeType.value,
},
categoryId: TX.CategoryID,
memo: TX.Memo,
amount: TX.Amount.toString(),
state: "Uncleared"
}));
function saveTransaction(e: MouseEvent) {
e.preventDefault();
transactionsStore.editTransaction(TX.ID, payload.value);
emit('save');
}
</script>
<template>
<tr>
<td class="text-sm">
<DateInput
v-model="TX.Date"
class="border-b-2 border-black"
/>
</td>
<td>
<Autocomplete
v-model:text="TX.Payee"
v-model:id="TX.PayeeID"
v-model:type="payeeType"
model="payees"
/>
</td>
<td>
<Autocomplete
v-model:text="TX.Category"
v-model:id="TX.CategoryID"
model="categories"
/>
</td>
<td>
<Input
v-model="TX.Memo"
class="block w-full border-b-2 border-black"
type="text"
/>
</td>
<td class="text-right">
<Input
v-model="TX.Amount"
class="text-right block w-full border-b-2 border-black"
type="currency"
/>
</td>
<td>
<Button
class="bg-blue-500"
@click="saveTransaction"
>
Save
</Button>
</td>
<td />
</tr>
</template>

View File

@ -1,61 +1,110 @@
<script lang="ts" setup>
import { computed, ref } from "vue";
import Autocomplete, { Suggestion } from '../components/Autocomplete.vue'
import { useAccountStore } from '../stores/budget-account'
import Autocomplete from '../components/Autocomplete.vue'
import { Transaction, useTransactionsStore } from "../stores/transactions";
import DateInput from "./DateInput.vue";
import Button from "./SimpleButton.vue";
import Input from "./Input.vue";
const props = defineProps<{
budgetid: string
accountid: string
}>()
const TransactionDate = ref(new Date().toISOString().substring(0, 10));
const Payee = ref<Suggestion | undefined>(undefined);
const Category = ref<Suggestion | undefined>(undefined);
const Memo = ref("");
const Amount = ref("0");
const TX = ref<Transaction>({
Date: new Date(),
Memo: "",
Amount: 0,
Payee: "",
PayeeID: undefined,
Category: "",
CategoryID: undefined,
CategoryGroup: "",
GroupID: "",
ID: "",
Status: "Uncleared",
TransferAccount: "",
Reconciled: false
});
const payeeType = ref<string|undefined>(undefined);
const payload = computed(() => JSON.stringify({
budget_id: props.budgetid,
account_id: props.accountid,
date: TransactionDate.value,
payee: Payee.value,
category: Category.value,
memo: Memo.value,
amount: Amount.value,
budgetId: props.budgetid,
accountId: props.accountid,
date: TX.value.Date.toISOString().split("T")[0],
payee: {
Name: TX.value.Payee,
ID: TX.value.PayeeID,
Type: payeeType.value,
},
categoryId: TX.value.CategoryID,
memo: TX.value.Memo,
amount: TX.value.Amount.toString(),
state: "Uncleared"
}));
const accountStore = useAccountStore();
const transactionsStore = useTransactionsStore();
function saveTransaction(e: MouseEvent) {
e.preventDefault();
accountStore.saveTransaction(payload.value);
Save();
}
function Save() {
transactionsStore.saveTransaction(payload.value);
}
defineExpose({Save});
</script>
<template>
<tr>
<td style="width: 90px;" class="text-sm">
<input class="border-b-2 border-black" type="date" v-model="TransactionDate" />
</td>
<td style="max-width: 150px;">
<Autocomplete v-model="Payee" type="payees" />
</td>
<td style="max-width: 200px;">
<Autocomplete v-model="Category" type="categories" />
</td>
<td>
<input class="block w-full border-b-2 border-black" type="text" v-model="Memo" />
</td>
<td style="width: 80px;" class="text-right">
<input
class="text-right block w-full border-b-2 border-black"
type="currency"
v-model="Amount"
<label class="md:hidden">Date</label>
<td class="text-sm">
<DateInput
v-model="TX.Date"
class="border-b-2 border-black"
/>
</td>
<td style="width: 20px;">
<input type="submit" @click="saveTransaction" value="Save" />
<label class="md:hidden">Payee</label>
<td>
<Autocomplete
v-model:text="TX.Payee"
v-model:id="TX.PayeeID"
v-model:type="payeeType"
model="payees"
/>
</td>
<label class="md:hidden">Category</label>
<td>
<Autocomplete
v-model:text="TX.Category"
v-model:id="TX.CategoryID"
model="categories"
/>
</td>
<td class="col-span-2">
<Input
v-model="TX.Memo"
class="block w-full border-b-2 border-black"
type="text"
/>
</td>
<label class="md:hidden">Amount</label>
<td class="text-right">
<Input
v-model="TX.Amount"
class="text-right block w-full border-b-2 border-black"
type="currency"
/>
</td>
<td class="hidden md:table-cell">
<Button
class="bg-blue-500"
@click="saveTransaction"
>
Save
</Button>
</td>
<td style="width: 20px;"></td>
</tr>
</template>

View File

@ -1,39 +1,100 @@
<script lang="ts" setup>
import { computed } from "vue";
import { computed, ref } from "vue";
import { useBudgetsStore } from "../stores/budget";
import { Transaction } from "../stores/budget-account";
import { useTransactionsStore } from "../stores/transactions";
import Currency from "./Currency.vue";
import TransactionEditRow from "./TransactionEditRow.vue";
import { formatDate } from "../date";
import { useAccountStore } from "../stores/budget-account";
import Input from "./Input.vue";
import Checkbox from "./Checkbox.vue";
const props = defineProps<{
transaction: Transaction,
transactionid: string,
index: number,
}>();
const CurrentBudgetID = computed(()=> useBudgetsStore().CurrentBudgetID);
const edit = ref(false);
const CurrentBudgetID = computed(() => useBudgetsStore().CurrentBudgetID);
const Reconciling = computed(() => useTransactionsStore().Reconciling);
const transactionsStore = useTransactionsStore();
const TX = transactionsStore.Transactions.get(props.transactionid)!;
function dateChanged() {
const currentAccount = useAccountStore().CurrentAccount;
if (currentAccount == null)
return true;
const transactionIndex = currentAccount.Transactions.indexOf(props.transactionid);
if(transactionIndex<=0)
return true;
const previousTransactionId = currentAccount.Transactions[transactionIndex-1];
const previousTransaction = transactionsStore.Transactions.get(previousTransactionId);
return TX.Date.getTime() != previousTransaction?.Date.getTime();
}
function getStatusSymbol() {
if(TX.Status == "Reconciled")
return "✔";
if(TX.Status == "Uncleared")
return "*";
return "✘";
}
</script>
<template>
<tr class="{{transaction.Date.After now ? 'future' : ''}}"
:class="[index % 6 < 3 ? 'bg-gray-300' : 'bg-gray-100']">
<!--:class="[index % 6 < 3 ? index % 6 === 1 ? 'bg-gray-400' : 'bg-gray-300' : index % 6 !== 4 ? 'bg-gray-100' : '']">-->
<td style="width: 90px;">{{ transaction.Date.substring(0, 10) }}</td>
<td style="max-width: 150px;">{{ transaction.TransferAccount ? "Transfer : " + transaction.TransferAccount : transaction.Payee }}</td>
<td style="max-width: 200px;">
{{ transaction.CategoryGroup ? transaction.CategoryGroup + " : " + transaction.Category : "" }}
<tr v-if="dateChanged()" class="table-row md:hidden">
<td class="py-2" colspan="5">
<span class="bg-gray-400 dark:bg-slate-600 rounded-lg p-1 px-2 w-full block">
{{ formatDate(TX.Date) }}
</span>
</td>
<td>
<a :href="'/budget/' + CurrentBudgetID + '/transaction/' + transaction.ID">
{{ transaction.Memo }}
</a>
</td>
<td>
<Currency class="block" :value="transaction.Amount" />
</td>
<td style="width: 20px;">
{{ transaction.Status == "Reconciled" ? "✔" : (transaction.Status == "Uncleared" ? "" : "*") }}
</td>
<td style="width: 20px;">{{ transaction.GroupID ? "☀" : "" }}</td>
</tr>
<tr
v-if="!edit"
class="{{new Date(TX.Date) > new Date() ? 'future' : ''}}"
:class="[index % 6 < 3 ? 'md:bg-gray-300 dark:md:bg-gray-700' : 'md:bg-gray-100 dark:md:bg-gray-900']"
>
<!--:class="[index % 6 < 3 ? index % 6 === 1 ? 'bg-gray-400' : 'bg-gray-300' : index % 6 !== 4 ? 'bg-gray-100' : '']">-->
<td class="hidden md:block">
{{ formatDate(TX.Date) }}
</td>
<td class="pl-2 md:pl-0">
{{ TX.TransferAccount ? "Transfer : " + TX.TransferAccount : TX.Payee }}
</td>
<td>
{{ TX.CategoryGroup ? TX.CategoryGroup + " : " + TX.Category : "" }}
</td>
<td>
<a
:href="'/budget/' + CurrentBudgetID + '/transaction/' + TX.ID"
>{{ TX.Memo }}</a>
</td>
<td>
<Currency
class="block"
:value="TX.Amount"
/>
</td>
<td class="text-right">
{{ TX.GroupID ? "☀" : "" }}
{{ getStatusSymbol() }}
<a @click="edit = true;"></a>
<Checkbox
v-if="Reconciling && TX.Status != 'Reconciled'"
v-model="TX.Reconciled"
/>
</td>
</tr>
<TransactionEditRow
v-if="edit"
:transactionid="TX.ID"
@save="edit = false"
/>
</template>
<style>

8
web/src/date.ts Normal file
View File

@ -0,0 +1,8 @@
export function formatDate(date: Date): string {
return date.toLocaleDateString(undefined, {
// you can use undefined as first argument
year: "numeric",
month: "2-digit",
day: "2-digit",
});
}

View File

@ -0,0 +1,85 @@
<script lang="ts" setup>
import { computed, ref } from 'vue';
import Modal from '../components/Modal.vue';
import { useAccountStore } from '../stores/budget-account';
import Input from '../components/Input.vue';
import Checkbox from '../components/Checkbox.vue';
import { useRouter } from 'vue-router';
import { useBudgetsStore } from '../stores/budget';
const router = useRouter();
const accountStore = useAccountStore();
const CurrentAccount = computed(() => accountStore.CurrentAccount);
const accountName = ref("");
const accountOnBudget = ref(true);
const accountOpen = ref(true);
const error = ref("");
function editAccount(e : {cancel:boolean}) : boolean {
if(CurrentAccount.value?.ClearedBalance != 0 && !accountOpen.value){
e.cancel = true;
error.value = "Cannot close account with balance";
return false;
}
error.value = "";
accountStore.EditAccount(CurrentAccount.value?.ID ?? "", accountName.value, accountOnBudget.value, accountOpen.value);
// account closed, move to Budget
if(!accountOpen.value){
const currentBudgetID = useBudgetsStore().CurrentBudgetID;
router.replace('/budget/'+currentBudgetID+'/budgeting');
}
return true;
}
function openEditAccount(e : any) {
accountName.value = CurrentAccount.value?.Name ?? "";
accountOnBudget.value = CurrentAccount.value?.OnBudget ?? true;
accountOpen.value = CurrentAccount.value?.IsOpen ?? true;
}
</script>
<template>
<Modal
button-text="Edit Account"
@open="openEditAccount"
@submit="editAccount"
>
<template #placeholder>
<span class="ml-2"></span>
</template>
<div class="mt-2 px-7 py-3">
<Input
v-model="accountName"
class="border-2 dark:border-gray-700"
type="text"
placeholder="Account name"
required
/>
</div>
<div class="mt-2 px-7 py-3">
<Checkbox
v-model="accountOnBudget"
class="border-2"
required
/>
<label>On Budget</label>
</div>
<div class="mt-2 px-7 py-3">
<Checkbox
v-model="accountOpen"
class="border-2"
required
/>
<label>Open</label>
</div>
<div
v-if="error != ''"
class="dark:text-red-300 text-red-700"
>
{{ error }}
</div>
</Modal>
</template>

View File

@ -1,36 +1,28 @@
<script lang="ts" setup>
import Card from '../components/Card.vue';
import Modal from '../components/Modal.vue';
import { ref } from "vue";
import { useBudgetsStore } from '../stores/budget';
import Input from '../components/Input.vue';
const dialog = ref(false);
const budgetName = ref("");
function saveBudget() {
useBudgetsStore().NewBudget(budgetName.value);
dialog.value = false;
};
function newBudget() {
dialog.value = true;
};
</script>
<template>
<Card>
<p class="w-24 text-center text-6xl">+</p>
<button class="text-lg" dark @click="newBudget">New Budget</button>
</Card>
<div v-if="dialog" justify="center">
<div>
<div>
<span class="text-h5">New Budget</span>
</div>
<div>
<input type="text" v-model="budgetName" label="Budget name" required />
</div>
<div>
<button @click="dialog = false">Close</button>
<button @click="saveBudget">Save</button>
</div>
</div>
<Modal
button-text="New Budget"
@submit="saveBudget"
>
<div class="mt-2 px-7 py-3">
<Input
v-model="budgetName"
class="border-2"
type="text"
placeholder="Budget name"
required
/>
</div>
</Modal>
</template>

View File

@ -9,3 +9,9 @@ h1 {
a {
text-decoration: underline;
}
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}

View File

@ -1,25 +1,79 @@
import { createApp } from 'vue'
import App from './App.vue'
import './index.css'
import router from './router'
import { createPinia } from 'pinia'
import { useBudgetsStore } from './stores/budget';
import { useAccountStore } from './stores/budget-account'
import PiniaLogger from './pinia-logger'
import { createApp } from "vue";
import App from "./App.vue";
import "./index.css";
import router from "./router";
import { createPinia } from "pinia";
import { useBudgetsStore } from "./stores/budget";
import { useAccountStore } from "./stores/budget-account";
import PiniaLogger from "./pinia-logger";
import { useSessionStore } from "./stores/session";
const app = createApp(App)
app.use(router)
const app = createApp(App);
app.use(router);
const pinia = createPinia()
pinia.use(PiniaLogger())
app.use(pinia)
app.mount('#app')
const pinia = createPinia();
pinia.use(
PiniaLogger({
expanded: false,
showDuration: true,
})
);
app.use(pinia);
app.mount("#app");
router.beforeEach(async (to, from, next) => {
const budgetStore = useBudgetsStore();
await budgetStore.SetCurrentBudget((<string>to.params.budgetid));
await budgetStore.SetCurrentBudget(<string>to.params.budgetid);
const accountStore = useAccountStore();
await accountStore.SetCurrentAccount((<string>to.params.budgetid), (<string>to.params.accountid));
await accountStore.SetCurrentAccount(
<string>to.params.budgetid,
<string>to.params.accountid
);
next();
})
});
router.beforeEach((to, from, next) => {
const sessionStore = useSessionStore();
const token = sessionStore.Session?.Token;
let loggedIn = false;
if (token != null) {
const jwt = parseJwt(token);
if (jwt.exp > Date.now() / 1000) loggedIn = true;
}
if (to.matched.some((record) => record.meta.requiresAuth)) {
if (!loggedIn) {
next({ path: "/login" });
} else {
next();
}
} else if (to.matched.some((record) => record.meta.hideForAuth)) {
if (loggedIn) {
next({ path: "/dashboard" });
} else {
next();
}
} else {
next();
}
});
function parseJwt(token: string) {
var base64Url = token.split(".")[1];
var base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
var jsonPayload = decodeURIComponent(
atob(base64)
.split("")
.map(function (c) {
return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
})
.join("")
);
return JSON.parse(jsonPayload);
}
1646426130;
1646512855755;

View File

@ -4,40 +4,170 @@ import Currency from "../components/Currency.vue";
import TransactionRow from "../components/TransactionRow.vue";
import TransactionInputRow from "../components/TransactionInputRow.vue";
import { useAccountStore } from "../stores/budget-account";
import EditAccount from "../dialogs/EditAccount.vue";
import Button from "../components/SimpleButton.vue";
import { useTransactionsStore } from "../stores/transactions";
import Modal from "../components/Modal.vue";
import Input from "../components/Input.vue";
import Checkbox from "../components/Checkbox.vue";
const props = defineProps<{
defineProps<{
budgetid: string
accountid: string
}>()
const accountStore = useAccountStore();
const CurrentAccount = computed(() => accountStore.CurrentAccount);
const TransactionsList = computed(() => accountStore.TransactionsList);
const modalInputRow = ref<typeof TransactionInputRow | null>(null);
function submitModal() {
modalInputRow.value!.Save();
}
const accounts = useAccountStore();
const transactions = useTransactionsStore();
const TargetReconcilingBalance = ref(0);
function setReconciled(event: Event) {
const target = event.target as HTMLInputElement;
transactions.SetReconciledForAllTransactions(target.checked);
}
function cancelReconcilation() {
transactions.SetReconciledForAllTransactions(false);
transactions.Reconciling = false;
}
function submitReconcilation() {
transactions.SubmitReconcilation(0);
transactions.Reconciling = false;
}
function createReconcilationTransaction() {
const diff = TargetReconcilingBalance.value - transactions.ReconcilingBalance;
transactions.SubmitReconcilation(diff);
transactions.Reconciling = false;
}
</script>
<template>
<h1>{{ CurrentAccount?.Name }}</h1>
<p>
Current Balance:
<Currency :value="CurrentAccount?.Balance" />
</p>
<div class="grid grid-cols-[1fr_auto]">
<div>
<h1 class="inline">
{{ accounts.CurrentAccount?.Name }}
</h1>
<EditAccount />
</div>
<div
class="text-right flex flex-wrap flex-col md:flex-row justify-end gap-2 max-w-sm"
>
<span class="rounded-lg p-1 whitespace-nowrap flex-1">
Working:
<Currency :value="accounts.CurrentAccount?.WorkingBalance" />
</span>
<span class="rounded-lg p-1 whitespace-nowrap flex-1">
Cleared:
<Currency :value="accounts.CurrentAccount?.ClearedBalance" />
</span>
<span
v-if="!transactions.Reconciling"
class="rounded-lg bg-blue-500 p-1 whitespace-nowrap flex-1"
@click="transactions.Reconciling = true"
>
Reconciled:
<Currency :value="accounts.CurrentAccount?.ReconciledBalance" />
</span>
<span
v-if="transactions.Reconciling"
class="contents"
>
<Button
class="bg-blue-500 p-1 whitespace-nowrap flex-1"
@click="submitReconcilation"
>
My current balance is&nbsp;
<Currency :value="transactions.ReconcilingBalance" />
</Button>
<Button
class="bg-orange-500 p-1 whitespace-nowrap flex-1"
@click="createReconcilationTransaction"
>
No, it's:
<Input
v-model="TargetReconcilingBalance"
class="text-right w-20 bg-transparent dark:bg-transparent border-b-2"
type="number"
/>
(Difference
<Currency
:value="transactions.ReconcilingBalance - TargetReconcilingBalance"
/>)
</Button>
<Button
class="bg-red-500 p-1 flex-1"
@click="cancelReconcilation"
>Cancel</Button>
</span>
</div>
</div>
<table>
<tr class="font-bold">
<td style="width: 90px;">Date</td>
<td style="max-width: 150px;">Payee</td>
<td style="max-width: 200px;">Category</td>
<td
class="hidden md:block"
style="width: 90px;"
>
Date
</td>
<td style="max-width: 150px;">
Payee
</td>
<td style="max-width: 200px;">
Category
</td>
<td>Memo</td>
<td class="text-right">Amount</td>
<td style="width: 20px;"></td>
<td style="width: 20px;"></td>
<td class="text-right">
Amount
</td>
<td style="width: 80px;">
<Checkbox
v-if="transactions.Reconciling"
@input="setReconciled"
/>
</td>
</tr>
<TransactionInputRow :budgetid="budgetid" :accountid="accountid" />
<TransactionInputRow
class="hidden md:table-row"
:budgetid="budgetid"
:accountid="accountid"
/>
<TransactionRow
v-for="(transaction, index) in TransactionsList"
:transaction="transaction"
v-for="(transaction, index) in transactions.TransactionsList"
:key="transaction.ID"
:transactionid="transaction.ID"
:index="index"
/>
</table>
<div class="md:hidden">
<Modal @submit="submitModal">
<template #placeholder>
<Button
class="fixed right-4 bottom-4 font-bold text-lg bg-blue-500 py-2"
>
+
</Button>
</template>
<TransactionInputRow
ref="modalInputRow"
class="grid grid-cols-2"
:budgetid="budgetid"
:accountid="accountid"
/>
</Modal>
</div>
</template>
<style>

View File

@ -1,16 +1,14 @@
<script lang="ts" setup>
import { computed } from "vue";
import Currency from "../components/Currency.vue"
import { useBudgetsStore } from "../stores/budget"
import { useAccountStore } from "../stores/budget-account"
import { useSettingsStore } from "../stores/settings"
import Currency from "../components/Currency.vue";
import { useBudgetsStore } from "../stores/budget";
import { Account, useAccountStore } from "../stores/budget-account";
import { useSettingsStore } from "../stores/settings";
import AccountWithReconciled from "../components/AccountWithReconciled.vue";
const props = defineProps<{
budgetid: string,
accountid: string,
}>();
const ExpandMenu = computed(() => useSettingsStore().Menu.Expand);
const settings = useSettingsStore();
const ExpandMenu = computed(() => settings.Menu.Expand);
const ShowMenu = computed(() => settings.Menu.Show);
const budgetStore = useBudgetsStore();
const CurrentBudgetName = computed(() => budgetStore.CurrentBudgetName);
@ -24,48 +22,84 @@ const OffBudgetAccountsBalance = computed(() => accountStore.OffBudgetAccountsBa
</script>
<template>
<div class="flex flex-col">
<span class="m-1 p-1 px-3 text-xl">
<router-link to="/dashboard"></router-link>
{{CurrentBudgetName}}
<div
:class="[ExpandMenu ? 'md:w-72' : 'md:w-36', ShowMenu ? '' : 'hidden']"
class="md:block flex-shrink-0 w-full bg-gray-500 border-r-4 border-black"
>
<div class="flex flex-col mt-14 md:mt-0">
<span
class="m-2 p-1 px-3 h-10 overflow-hidden"
:class="[ExpandMenu ? 'text-2xl' : 'text-md']"
>
<router-link
to="/dashboard"
style="font-size: 150%"
></router-link>
{{ CurrentBudgetName }}
</span>
<span class="bg-orange-200 rounded-lg m-1 p-1 px-3 flex flex-col">
<router-link :to="'/budget/'+budgetid+'/budgeting'">Budget</router-link><br />
<span class="bg-gray-100 dark:bg-gray-700 p-2 px-3 flex flex-col">
<router-link :to="'/budget/' + CurrentBudgetID + '/budgeting'">Budget</router-link>
<br>
<!--<router-link :to="'/budget/'+CurrentBudgetID+'/reports'">Reports</router-link>-->
<!--<router-link :to="'/budget/'+CurrentBudgetID+'/all-accounts'">All Accounts</router-link>-->
</span>
<li class="bg-orange-200 rounded-lg m-1 p-1 px-3">
<li class="bg-slate-200 dark:bg-slate-700 my-2 p-2 px-3">
<div class="flex flex-row justify-between font-bold">
<span>On-Budget Accounts</span>
<Currency :class="ExpandMenu?'md:inline':'md:hidden'" :value="OnBudgetAccountsBalance" />
<Currency
:class="ExpandMenu ? 'md:inline' : 'md:hidden'"
:value="OnBudgetAccountsBalance"
/>
</div>
<div v-for="account in OnBudgetAccounts" class="flex flex-row justify-between">
<router-link :to="'/budget/'+budgetid+'/account/'+account.ID">{{account.Name}}</router-link>
<Currency :class="ExpandMenu?'md:inline':'md:hidden'" :value="account.Balance" />
<div
v-for="account in OnBudgetAccounts"
:key="account.ID"
class="flex flex-row justify-between"
>
<AccountWithReconciled :account="account" />
<Currency
:class="ExpandMenu ? 'md:inline' : 'md:hidden'"
:value="account.ClearedBalance"
/>
</div>
</li>
<li class="bg-red-200 rounded-lg m-1 p-1 px-3">
<li class="bg-slate-200 dark:bg-slate-700 my-2 p-2 px-3">
<div class="flex flex-row justify-between font-bold">
<span>Off-Budget Accounts</span>
<Currency :class="ExpandMenu?'md:inline':'md:hidden'" :value="OffBudgetAccountsBalance" />
<Currency
:class="ExpandMenu ? 'md:inline' : 'md:hidden'"
:value="OffBudgetAccountsBalance"
/>
</div>
<div v-for="account in OffBudgetAccounts" class="flex flex-row justify-between">
<router-link :to="'/budget/'+budgetid+'/account/'+account.ID">{{account.Name}}</router-link>
<Currency :class="ExpandMenu?'md:inline':'md:hidden'" :value="account.Balance" />
<div
v-for="account in OffBudgetAccounts"
:key="account.ID"
class="flex flex-row justify-between"
>
<AccountWithReconciled :account="account" />
<Currency
:class="ExpandMenu ? 'md:inline' : 'md:hidden'"
:value="account.ClearedBalance"
/>
</div>
</li>
<li class="bg-red-200 rounded-lg m-1 p-1 px-3">
Closed Accounts
<!--
<li class="bg-slate-100 dark:bg-slate-800 my-2 p-2 px-3">
<div class="flex flex-row justify-between font-bold">
<span>Closed Accounts</span>
</div>
+ Add Account
</li>
-->
<!--<li>
<router-link :to="'/budget/'+CurrentBudgetID+'/accounts'">Edit accounts</router-link>
</li>-->
<li class="bg-red-200 rounded-lg m-1 p-1 px-3">
+ Add Account
</li>
<li class="bg-red-200 rounded-lg m-1 p-1 px-3">
<router-link :to="'/budget/'+CurrentBudgetID+'/settings'">Budget-Settings</router-link>
<li class="bg-red-100 dark:bg-slate-600 my-2 p-2 px-3">
<router-link :to="'/budget/' + CurrentBudgetID + '/settings'">
Budget-Settings
</router-link>
</li>
<!--<li><router-link to="/admin">Admin</router-link></li>-->
</div>
</div>
</template>

View File

@ -1,9 +1,11 @@
<script lang="ts" setup>
import { computed, defineProps, onMounted, watchEffect } from "vue";
import { computed, defineProps, onMounted, ref, watchEffect } from "vue";
import Currency from "../components/Currency.vue";
import { useBudgetsStore } from "../stores/budget";
import { useAccountStore } from "../stores/budget-account";
import { Category, useAccountStore } from "../stores/budget-account";
import { useSessionStore } from "../stores/session";
import Input from "../components/Input.vue";
import { POST } from "../api";
const props = defineProps<{
budgetid: string,
@ -14,11 +16,19 @@ const props = defineProps<{
const budgetsStore = useBudgetsStore();
const CurrentBudgetID = computed(() => budgetsStore.CurrentBudgetID);
const categoriesForMonth = useAccountStore().CategoriesForMonth;
const Categories = computed(() => {
return [...categoriesForMonth(selected.value.Year, selected.value.Month)];
const accountStore = useAccountStore();
const categoriesForMonth = accountStore.CategoriesForMonthAndGroup;
function GetCategories(group: string) {
return [...categoriesForMonth(selected.value.Year, selected.value.Month, group)];
};
const groupsForMonth = accountStore.CategoryGroupsForMonth;
const GroupsForMonth = computed(() => {
return [...groupsForMonth(selected.value.Year, selected.value.Month)];
});
const previous = computed(() => ({
Year: new Date(selected.value.Year, selected.value.Month - 1, 1).getFullYear(),
Month: new Date(selected.value.Year, selected.value.Month - 1, 1).getMonth(),
@ -44,49 +54,120 @@ watchEffect(() => {
onMounted(() => {
useSessionStore().setTitle("Budget for " + selected.value.Month + "/" + selected.value.Year);
})
const expandedGroups = ref<Map<string, boolean>>(new Map<string, boolean>())
function toggleGroup(group: { Name: string, Expand: boolean }) {
expandedGroups.value.set(group.Name, !(expandedGroups.value.get(group.Name) ?? group.Expand))
}
function getGroupState(group: { Name: string, Expand: boolean }): boolean {
return expandedGroups.value.get(group.Name) ?? group.Expand;
}
function assignedChanged(e : Event, category : Category){
const target = e.target as HTMLInputElement;
const value = target.valueAsNumber;
POST("/budget/"+CurrentBudgetID.value+"/category/" + category.ID + "/" + selected.value.Year + "/" + (selected.value.Month+1),
JSON.stringify({Assigned: category.Assigned}));
}
</script>
<template>
<h1>Budget for {{ selected.Month + 1 }}/{{ selected.Year }}</h1>
<span>Available balance:
<Currency
:value="accountStore.GetIncomeAvailable(selected.Year, selected.Month)"
/></span>
<div>
<router-link
:to="'/budget/' + CurrentBudgetID + '/budgeting/' + previous.Year + '/' + previous.Month"
>Previous Month</router-link>-
>
&lt;&lt;
</router-link>&nbsp;
<router-link
:to="'/budget/' + CurrentBudgetID + '/budgeting/' + current.Year + '/' + current.Month"
>Current Month</router-link>-
>
Current Month
</router-link>&nbsp;
<router-link
:to="'/budget/' + CurrentBudgetID + '/budgeting/' + next.Year + '/' + next.Month"
>Next Month</router-link>
>
&gt;&gt;
</router-link>
</div>
<div
id="content"
class="container col-lg-12 grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-5"
>
<span class="hidden sm:block" />
<span class="hidden lg:block text-right">Leftover</span>
<span class="hidden sm:block text-right">Assigned</span>
<span class="hidden sm:block text-right">Activity</span>
<span class="hidden sm:block text-right">Available</span>
<template
v-for="group in GroupsForMonth"
:key="group.Name"
>
<span
class="text-lg font-bold mt-2"
@click="toggleGroup(group)"
>{{ (getGroupState(group) ? "" : "+") + " " + group.Name }}</span>
<Currency
:value="group.AvailableLastMonth"
class="hidden lg:block mt-2"
positive-class="text-slate-500"
negative-class="text-red-700 dark:text-red-400"
/>
<Currency
:value="group.Assigned"
class="hidden sm:block mx-2 mt-2 text-right"
positive-class="text-slate-500"
negative-class="text-red-700 dark:text-red-400"
/>
<Currency
:value="group.Activity"
class="hidden sm:block mt-2"
positive-class="text-slate-500"
negative-class="text-red-700 dark:text-red-400"
/>
<Currency
:value="group.Available"
class="mt-2"
positive-class="text-slate-500"
negative-class="text-red-700 dark:text-red-400"
/>
<template
v-for="category in GetCategories(group.Name)"
:key="category.ID"
>
<div
v-if="getGroupState(group)"
class="contents"
>
<span
class="whitespace-nowrap overflow-hidden"
>{{ category.Name }}</span>
<Currency
:value="category.AvailableLastMonth"
class="hidden lg:block"
/>
<Input
v-model="category.Assigned"
type="number"
class="hidden sm:block mx-2 text-right"
@input="(evt) => assignedChanged(evt, category)"
/>
<Currency
:value="category.Activity"
class="hidden sm:block"
/>
<Currency
:value="accountStore.GetCategoryAvailable(category)"
/>
</div>
</template>
</template>
</div>
<table class="container col-lg-12" id="content">
<tr>
<th>Group</th>
<th>Category</th>
<th></th>
<th></th>
<th>Leftover</th>
<th>Assigned</th>
<th>Activity</th>
<th>Available</th>
</tr>
<tr v-for="category in Categories">
<td>{{ category.Group }}</td>
<td>{{ category.Name }}</td>
<td></td>
<td></td>
<td class="text-right">
<Currency :value="category.AvailableLastMonth" />
</td>
<td class="text-right">
<Currency :value="category.Assigned" />
</td>
<td class="text-right">
<Currency :value="category.Activity" />
</td>
<td class="text-right">
<Currency :value="category.Available" />
</td>
</tr>
</table>
</template>

View File

@ -1,6 +1,6 @@
<script lang="ts" setup>
import NewBudget from '../dialogs/NewBudget.vue';
import Card from '../components/Card.vue';
import RowCard from '../components/RowCard.vue';
import { useSessionStore } from '../stores/session';
const props = defineProps<{
@ -13,13 +13,20 @@ const BudgetsList = useSessionStore().BudgetsList;
<template>
<h1>Budgets</h1>
<div class="grid md:grid-cols-2 gap-6">
<Card v-for="budget in BudgetsList">
<router-link v-bind:to="'/budget/'+budget.ID+'/budgeting'" class="contents">
<RowCard
v-for="budget in BudgetsList"
:key="budget.ID"
>
<router-link
:to="'/budget/'+budget.ID+'/budgeting'"
class="contents"
>
<!--<svg class="w-24"></svg>-->
<p class="w-24 text-center text-6xl"></p>
<span class="text-lg">{{budget.Name}}{{budget.ID == budgetid ? " *" : ""}}</span>
<p class="w-24 text-center text-6xl" />
<span class="text-lg">{{ budget.Name
}}{{ budget.ID == budgetid ? " *" : "" }}</span>
</router-link>
</Card>
</RowCard>
<NewBudget />
</div>
</template>

View File

@ -1,13 +0,0 @@
<script lang="ts" setup>
</script>
<template>
<div>
<div class="font-bold" id="content">
Willkommen bei Budgeteer, der neuen App für's Budget!
</div>
<div class="container col-md-4" id="login">
<router-link to="/login">Login</router-link> or <router-link to="/login">register</router-link>
</div>
</div>
</template>

View File

@ -2,9 +2,11 @@
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { useSessionStore } from "../stores/session";
import Input from "../components/Input.vue";
const error = ref("");
const login = ref({ user: "", password: "" });
const router = useRouter(); // has to be called in setup
onMounted(() => {
useSessionStore().setTitle("Login");
@ -15,7 +17,8 @@ function formSubmit(e: MouseEvent) {
useSessionStore().login(login.value)
.then(x => {
error.value = "";
useRouter().replace("/dashboard");
router.replace("/dashboard");
return x;
})
.catch(x => error.value = "The entered credentials are invalid!");
@ -26,23 +29,31 @@ function formSubmit(e: MouseEvent) {
<template>
<div>
<input
type="text"
<Input
v-model="login.user"
type="text"
placeholder="Username"
class="border-2 border-black rounded-lg block px-2 my-2 w-48"
/>
<input
type="password"
<Input
v-model="login.password"
type="password"
placeholder="Password"
class="border-2 border-black rounded-lg block px-2 my-2 w-48"
/>
</div>
<div>{{ error }}</div>
<button type="submit" @click="formSubmit" class="bg-blue-300 rounded-lg p-2 w-48">Login</button>
<button
type="submit"
class="bg-blue-300 rounded-lg p-2 w-48"
@click="formSubmit"
>
Login
</button>
<p>
New user?
<router-link to="/register">Register</router-link>instead!
<router-link to="/register">
Register
</router-link> instead!
</p>
</template>

View File

@ -1,16 +1,26 @@
<script lang="ts" setup>
import { ref } from 'vue';
import { useSessionStore } from '../stores/session';
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { useSessionStore } from "../stores/session";
import Input from "../components/Input.vue";
const error = ref("");
const login = ref({ email: "", password: "", name: "" });
const showPassword = ref(false);
const router = useRouter(); // has to be called in setup
function formSubmit(e: FormDataEvent) {
onMounted(() => {
useSessionStore().setTitle("Login");
});
function formSubmit(e: MouseEvent) {
e.preventDefault();
useSessionStore().register(login)
.then(() => error.value = "")
.catch(() => error.value = "Something went wrong!");
useSessionStore().register(login.value)
.then(x => {
error.value = "";
router.replace("/dashboard");
return x;
})
.catch(x => error.value = "The entered credentials are invalid!");
// TODO display invalidCredentials
// TODO redirect to dashboard on success
@ -18,44 +28,38 @@ function formSubmit(e: FormDataEvent) {
</script>
<template>
<v-container>
<v-row>
<v-col cols="12">
<v-text-field v-model="login.email" type="text" label="E-Mail" />
</v-col>
<v-col cols="12">
<v-text-field v-model="login.name" type="text" label="Name" />
</v-col>
<v-col cols="6">
<v-text-field
v-model="login.password"
label="Password"
:append-icon="showPassword ? 'mdi-eye' : 'mdi-eye-off'"
:type="showPassword ? 'text' : 'password'"
@click:append="showPassword = showPassword"
:error-message="error"
error-count="2"
error
<div>
<Input
v-model="login.name"
type="text"
placeholder="Name"
class="border-2 border-black rounded-lg block px-2 my-2 w-48"
/>
</v-col>
<v-col cols="6">
<v-text-field
v-model="login.password"
label="Repeat password"
:append-icon="showPassword ? 'mdi-eye' : 'mdi-eye-off'"
:type="showPassword ? 'text' : 'password'"
@click:append="showPassword = showPassword"
:error-message="error"
error-count="2"
error
<Input
v-model="login.email"
type="text"
placeholder="Email"
class="border-2 border-black rounded-lg block px-2 my-2 w-48"
/>
</v-col>
</v-row>
<div class="form-group">{{ error }}</div>
<v-btn type="submit" @click="formSubmit">Register</v-btn>
<Input
v-model="login.password"
type="password"
placeholder="Password"
class="border-2 border-black rounded-lg block px-2 my-2 w-48"
/>
</div>
<div>{{ error }}</div>
<button
type="submit"
class="bg-blue-300 rounded-lg p-2 w-48"
@click="formSubmit"
>
Register
</button>
<p>
Existing user?
<router-link to="/login">Login</router-link>instead!
<router-link to="/login">
Login
</router-link> instead!
</p>
</v-container>
</template>

View File

@ -4,6 +4,10 @@ import { useRouter } from "vue-router";
import { DELETE, POST } from "../api";
import { useBudgetsStore } from "../stores/budget";
import { useSessionStore } from "../stores/session";
import RowCard from "../components/RowCard.vue";
import Button from "../components/SimpleButton.vue";
import { saveAs } from 'file-saver';
import Input from "../components/Input.vue";
const transactionsFile = ref<File | undefined>(undefined);
const assignmentsFile = ref<File | undefined>(undefined);
@ -13,6 +17,10 @@ onMounted(() => {
useSessionStore().setTitle("Settings");
});
const budgetStore = useBudgetsStore();
const CurrentBudgetID = computed(() => budgetStore.CurrentBudgetID);
const CurrentBudgetName = computed(() => budgetStore.CurrentBudgetName);
function gotAssignments(e: Event) {
const input = (<HTMLInputElement>e.target);
if (input.files != null)
@ -24,19 +32,17 @@ function gotTransactions(e: Event) {
transactionsFile.value = input.files[0];
};
function deleteBudget() {
const currentBudgetID = useBudgetsStore().CurrentBudgetID;
if (currentBudgetID == null)
if (CurrentBudgetID.value == null)
return;
DELETE("/budget/" + currentBudgetID);
DELETE("/budget/" + CurrentBudgetID.value);
const budgetStore = useSessionStore();
budgetStore.Budgets.delete(currentBudgetID);
budgetStore.Budgets.delete(CurrentBudgetID.value);
useRouter().push("/")
};
function clearBudget() {
const currentBudgetID = useBudgetsStore().CurrentBudgetID;
POST("/budget/" + currentBudgetID + "/settings/clear", null)
POST("/budget/" + CurrentBudgetID.value + "/settings/clear", null)
};
function cleanNegative() {
// <a href="/budget/{{.Budget.ID}}/settings/clean-negative">Fix all historic negative category-balances</a>
@ -51,75 +57,120 @@ function ynabImport() {
const budgetStore = useBudgetsStore();
budgetStore.ImportYNAB(formData);
};
function ynabExport() {
const timeStamp = new Date().toISOString();
POST("/budget/"+CurrentBudgetID.value+"/export/ynab/assignments", "")
.then(x => x.text())
.then(x => {
var blob = new Blob([x], {type: "text/plain;charset=utf-8"});
saveAs(blob, timeStamp + " " + CurrentBudgetName.value + " - Budget.tsv");
})
POST("/budget/"+CurrentBudgetID.value+"/export/ynab/transactions", "")
.then(x => x.text())
.then(x => {
var blob = new Blob([x], {type: "text/plain;charset=utf-8"});
saveAs(blob, timeStamp + " " + CurrentBudgetName.value + " - Transactions.tsv");
})
}
</script>
<template>
<v-container>
<div>
<h1>Danger Zone</h1>
<v-row>
<v-col cols="12" md="6" xl="3">
<v-card>
<v-card-header>
<v-card-header-text>
<v-card-title>Clear Budget</v-card-title>
<v-card-subtitle>This removes transactions and assignments to start from scratch. Accounts and categories are kept. Not undoable!</v-card-subtitle>
</v-card-header-text>
</v-card-header>
<v-card-actions class="justify-center">
<v-btn @click="clearBudget">Clear budget</v-btn>
</v-card-actions>
</v-card>
</v-col>
<v-col cols="12" md="6" xl="3">
<v-card>
<v-card-header>
<v-card-header-text>
<v-card-title>Delete Budget</v-card-title>
<v-card-subtitle>This deletes the whole bugdet including all transactions, assignments, accounts and categories. Not undoable!</v-card-subtitle>
</v-card-header-text>
</v-card-header>
<v-card-actions class="justify-center">
<v-btn @click="deleteBudget">Delete budget</v-btn>
</v-card-actions>
</v-card>
</v-col>
<v-col cols="12" md="6" xl="3">
<v-card>
<v-card-header>
<v-card-header-text>
<v-card-title>Fix all historic negative category-balances</v-card-title>
<v-card-subtitle>This restores YNABs functionality, that would substract any overspent categories' balances from next months inflows.</v-card-subtitle>
</v-card-header-text>
</v-card-header>
<v-card-actions class="justify-center">
<v-btn @click="cleanNegative">Fix negative</v-btn>
</v-card-actions>
</v-card>
</v-col>
<v-col cols="12" xl="6">
<v-card>
<v-card-header>
<v-card-header-text>
<v-card-title>Import YNAB Budget</v-card-title>
</v-card-header-text>
</v-card-header>
<div class="grid md:grid-cols-2 gap-6">
<RowCard class="flex-col p-3">
<h2 class="text-lg font-bold">
Clear Budget
</h2>
<p>
This removes transactions and assignments to start from
scratch. Accounts and categories are kept. Not undoable!
</p>
<Button
class="bg-red-500 py-2"
@click="clearBudget"
>
Clear budget
</Button>
</RowCard>
<RowCard class="flex-col p-3">
<h2 class="text-lg font-bold">
Delete Budget
</h2>
<p>
This deletes the whole bugdet including all transactions,
assignments, accounts and categories. Not undoable!
</p>
<Button
class="bg-red-500 py-2"
@click="deleteBudget"
>
Delete budget
</Button>
</RowCard>
<RowCard class="flex-col p-3">
<h2 class="text-lg font-bold">
Fix all historic negative category-balances
</h2>
<p>
This restores YNABs functionality, that would substract any
overspent categories' balances from next months inflows.
</p>
<Button
class="bg-orange-500 py-2"
@click="cleanNegative"
>
Fix negative
</Button>
</RowCard>
<RowCard class="flex-col p-3">
<h2 class="text-lg font-bold">
Import YNAB Budget
</h2>
<div>
<label for="transactions_file">
Transaktionen:
<input type="file" @change="gotTransactions" accept="text/*" />
<input
type="file"
accept="text/*"
@change="gotTransactions"
>
</label>
<br />
<br>
<label for="assignments_file">
Budget:
<input type="file" @change="gotAssignments" accept="text/*" />
<input
type="file"
accept="text/*"
@change="gotAssignments"
>
</label>
</div>
<v-card-actions class="justify-center">
<v-btn :disabled="filesIncomplete" @click="ynabImport">Importieren</v-btn>
</v-card-actions>
</v-card>
</v-col>
</v-row>
<v-card></v-card>
</v-container>
<Button
class="bg-blue-500 py-2"
:disabled="filesIncomplete"
@click="ynabImport"
>
Importieren
</Button>
</RowCard>
<RowCard class="flex-col p-3">
<h2 class="text-lg font-bold">
Export as YNAB TSV
</h2>
<div class="flex flex-row">
<Button
class="bg-blue-500 py-2"
@click="ynabExport"
>
Export
</Button>
</div>
</RowCard>
</div>
</div>
</template>

View File

@ -0,0 +1,24 @@
<script lang="ts" setup>
</script>
<template>
<div>
<div
id="content"
class="font-bold"
>
Willkommen bei Budgeteer, der neuen App für's Budget!
</div>
<div
id="login"
class="container col-md-4"
>
<router-link to="/login">
Login
</router-link> or
<router-link to="/login">
register
</router-link>
</div>
</div>
</template>

View File

@ -1,4 +1,9 @@
import { PiniaPluginContext, StoreGeneric, _ActionsTree, _StoreOnActionListenerContext } from 'pinia';
import {
PiniaPluginContext,
StoreGeneric,
_ActionsTree,
_StoreOnActionListenerContext,
} from "pinia";
const cloneDeep = <T>(obj: T): T => {
try {
@ -8,23 +13,26 @@ const cloneDeep = <T>(obj: T): T => {
}
};
const formatTime = (date = new Date()) => {
const hours = date.getHours().toString().padStart(2, '0');
const minutes = date.getMinutes().toString().padStart(2, '0');
const seconds = date.getSeconds().toString().padStart(2, '0');
const milliseconds = date.getMilliseconds().toString();
const hours = date.getHours().toString().padStart(2, "0");
const minutes = date.getMinutes().toString().padStart(2, "0");
const seconds = date.getSeconds().toString().padStart(2, "0");
return `${hours}:${minutes}:${seconds}:${milliseconds}`;
return `${hours}:${minutes}:${seconds}`;
};
export interface PiniaLoggerOptions {
disabled?: boolean;
expanded?: boolean;
showDuration?: boolean
showDuration?: boolean;
showStoreName?: boolean;
logErrors?: boolean;
}
export type PiniaActionListenerContext = _StoreOnActionListenerContext<StoreGeneric, string, _ActionsTree>;
export type PiniaActionListenerContext = _StoreOnActionListenerContext<
StoreGeneric,
string,
_ActionsTree
>;
const defaultOptions: PiniaLoggerOptions = {
logErrors: true,
@ -34,7 +42,9 @@ const defaultOptions: PiniaLoggerOptions = {
showDuration: false,
};
export const PiniaLogger = (config = defaultOptions) => (ctx: PiniaPluginContext) => {
export const PiniaLogger =
(config = defaultOptions) =>
(ctx: PiniaPluginContext) => {
const options = {
...defaultOptions,
...config,
@ -42,28 +52,43 @@ export const PiniaLogger = (config = defaultOptions) => (ctx: PiniaPluginContext
if (options.disabled) return;
ctx.store.$onAction((action: PiniaActionListenerContext) => {
const startTime = Date.now();
const prevState = cloneDeep(ctx.store.$state);
const log = (isError?: boolean, error?: any) => {
const endTime = Date.now();
const duration = endTime - startTime + 'ms';
const duration = endTime - startTime + "ms";
const nextState = cloneDeep(ctx.store.$state);
const storeName = action.store.$id;
const title = `action 🍍 ${options.showStoreName ? `[${storeName}] ` : ''}${action.name} ${isError ? `failed after ${duration} ` : ''}@ ${formatTime()}`;
const title = `${formatTime()} action 🍍 ${
options.showStoreName ? `[${storeName}] ` : ""
}${action.name} ${
isError ? `failed after ` : ""
}in ${duration}`;
console[options.expanded ? 'group' : 'groupCollapsed'](`%c${title}`, `font-weight: bold; ${isError ? 'color: #ed4981;' : ''}`);
console.log('%cprev state', 'font-weight: bold; color: grey;', prevState);
console.log('%caction', 'font-weight: bold; color: #69B7FF;', {
console[options.expanded ? "group" : "groupCollapsed"](
`%c${title}`,
`font-weight: bold; ${isError ? "color: #ed4981;" : ""}`
);
console.log(
"%cprev state",
"font-weight: bold; color: grey;",
prevState
);
console.log("%caction", "font-weight: bold; color: #69B7FF;", {
type: action.name,
args: action.args.length > 0 ? { ...action.args } : undefined,
args:
action.args.length > 0 ? { ...action.args } : undefined,
...(options.showStoreName && { store: action.store.$id }),
...(options.showDuration && { duration }),
...(isError && { error }),
});
console.log('%cnext state', 'font-weight: bold; color: #4caf50;', nextState);
console.log(
"%cnext state",
"font-weight: bold; color: #4caf50;",
nextState
);
console.groupEnd();
};
@ -77,6 +102,6 @@ export const PiniaLogger = (config = defaultOptions) => (ctx: PiniaPluginContext
});
}
});
};
};
export default PiniaLogger;

View File

@ -1,29 +1,75 @@
import { createRouter, createWebHistory, RouteLocationNormalized } from 'vue-router'
import Dashboard from '../pages/Dashboard.vue';
import Login from '../pages/Login.vue';
import Index from '../pages/Index.vue';
import Register from '../pages/Register.vue';
import Account from '@/pages/Account.vue';
import Settings from '../pages/Settings.vue';
import Budgeting from '../pages/Budgeting.vue';
import BudgetSidebar from '../pages/BudgetSidebar.vue';
import {
createRouter,
createWebHistory,
RouteLocationNormalized,
} from "vue-router";
import Account from "@/pages/Account.vue";
import Budgeting from "../pages/Budgeting.vue";
import BudgetSidebar from "../pages/BudgetSidebar.vue";
import Dashboard from "../pages/Dashboard.vue";
import Login from "../pages/Login.vue";
import Register from "../pages/Register.vue";
import Settings from "../pages/Settings.vue";
import WelcomePage from "../pages/WelcomePage.vue";
const routes = [
{ path: "/", name: "Index", component: Index },
{ path: "/dashboard", name: "Dashboard", component: Dashboard },
{ path: "/login", name: "Login", component: Login },
{ path: "/register", name: "Register", component: Register },
{ path: "/budget/:budgetid/budgeting", name: "Budget", redirect: (to : RouteLocationNormalized) =>
'/budget/' + to.params.budgetid + '/budgeting/' + new Date().getFullYear() + '/' + new Date().getMonth()
{ path: "/", name: "Index", component: WelcomePage },
{
path: "/dashboard",
name: "Dashboard",
component: Dashboard,
meta: { requiresAuth: true },
},
{ path: "/budget/:budgetid/budgeting/:year/:month", name: "Budget with date", components: { default: Budgeting, sidebar: BudgetSidebar }, props: true },
{ path: "/budget/:budgetid/Settings", name: "Budget Settings", components: { default: Settings, sidebar: BudgetSidebar }, props: true },
{ path: "/budget/:budgetid/account/:accountid", name: "Account", components: { default: Account, sidebar: BudgetSidebar }, props: true },
]
{
path: "/login",
name: "Login",
component: Login,
meta: { hideForAuth: true },
},
{
path: "/register",
name: "Register",
component: Register,
meta: { hideForAuth: true },
},
{
path: "/budget/:budgetid/budgeting",
name: "Budget",
redirect: (to: RouteLocationNormalized) =>
"/budget/" +
to.params.budgetid +
"/budgeting/" +
new Date().getFullYear() +
"/" +
new Date().getMonth(),
meta: { requiresAuth: true },
},
{
path: "/budget/:budgetid/budgeting/:year/:month",
name: "Budget with date",
components: { default: Budgeting, sidebar: BudgetSidebar },
props: true,
meta: { requiresAuth: true },
},
{
path: "/budget/:budgetid/Settings",
name: "Budget Settings",
components: { default: Settings, sidebar: BudgetSidebar },
props: true,
meta: { requiresAuth: true },
},
{
path: "/budget/:budgetid/account/:accountid",
name: "Account",
components: { default: Account, sidebar: BudgetSidebar },
props: true,
meta: { requiresAuth: true },
},
];
const router = createRouter({
history: createWebHistory(),
routes,
})
});
export default router
export default router;

View File

@ -1,44 +1,41 @@
import { defineStore } from "pinia"
import { defineStore } from "pinia";
import { GET, POST } from "../api";
import { useBudgetsStore } from "./budget";
import { useSessionStore } from "./session";
import { useTransactionsStore } from "./transactions";
interface State {
Accounts: Map<string, Account>,
CurrentAccountID: string | null,
Categories: Map<string, Category>,
Months: Map<number, Map<number, Map<string, Category>>>,
Transactions: any[],
Assignments: []
}
export interface Transaction {
ID: string,
Date: string,
TransferAccount: string,
CategoryGroup: string,
Category: string,
Memo: string,
Status: string,
GroupID: string,
Payee: string,
Amount: number,
Accounts: Map<string, Account>;
CurrentAccountID: string | null;
Categories: Map<string, Category>;
Months: Map<number, Map<number, Map<string, Category>>>;
Assignments: [];
}
export interface Account {
ID: string
Name: string
OnBudget: boolean
Balance: number
ID: string;
Name: string;
OnBudget: boolean;
IsOpen: boolean;
ClearedBalance: number;
WorkingBalance: number;
ReconciledBalance: number;
Transactions: string[];
LastReconciled: NullDate;
}
interface NullDate {
Valid: boolean;
Time: Date;
}
export interface Category {
ID: string
Group: string
Name: string
AvailableLastMonth: number
Assigned: number
Activity: number
Available: number
ID: string;
Group: string;
Name: string;
AvailableLastMonth: number;
Assigned: number;
Activity: number;
}
export const useAccountStore = defineStore("budget/account", {
@ -47,67 +44,180 @@ export const useAccountStore = defineStore("budget/account", {
CurrentAccountID: null,
Months: new Map<number, Map<number, Map<string, Category>>>(),
Categories: new Map<string, Category>(),
Transactions: [],
Assignments: []
Assignments: [],
}),
getters: {
AccountsList(state) {
return [...state.Accounts.values()];
},
CategoriesForMonth: (state) => (year: number, month: number) => {
AllCategoriesForMonth: (state) => (year: number, month: number) => {
const yearMap = state.Months.get(year);
const monthMap = yearMap?.get(month);
console.log("MTH", monthMap)
return [...monthMap?.values() || []];
return [...(monthMap?.values() || [])];
},
GetCategoryAvailable(state) {
return (category: Category): number => {
return (
category.AvailableLastMonth +
Number(category.Assigned) +
category.Activity
);
};
},
GetIncomeCategoryID(state) {
const budget = useBudgetsStore();
return budget.CurrentBudget?.IncomeCategoryID;
},
GetIncomeAvailable(state) {
return (year: number, month: number) => {
const IncomeCategoryID = this.GetIncomeCategoryID;
if (IncomeCategoryID == null) return 0;
const categories = this.AllCategoriesForMonth(year, month);
const category = categories.filter(
(x) => x.ID == IncomeCategoryID
)[0];
if (category == null) return 0;
return category.AvailableLastMonth;
};
},
CategoryGroupsForMonth(state) {
return (year: number, month: number) => {
const categories = this.AllCategoriesForMonth(year, month);
const categoryGroups = [];
let prev = undefined;
for (const category of categories) {
if (category.ID == this.GetIncomeCategoryID) continue;
if (prev == undefined || category.Group != prev.Name) {
prev = {
Name: category.Group,
Available: this.GetCategoryAvailable(category),
AvailableLastMonth: category.AvailableLastMonth,
Activity: category.Activity,
Assigned: category.Assigned,
};
categoryGroups.push({
...prev,
Expand: prev.Name != "Hidden Categories",
});
} else {
categoryGroups[categoryGroups.length - 1].Available +=
this.GetCategoryAvailable(category);
categoryGroups[
categoryGroups.length - 1
].AvailableLastMonth += category.AvailableLastMonth;
categoryGroups[categoryGroups.length - 1].Activity +=
category.Activity;
categoryGroups[categoryGroups.length - 1].Assigned +=
category.Assigned;
continue;
}
}
return categoryGroups;
};
},
CategoriesForMonthAndGroup(state) {
return (year: number, month: number, group: string) => {
const categories = this.AllCategoriesForMonth(year, month);
return categories.filter((x) => x.Group == group);
};
},
GetAccount(state) {
return (accountid: string) => {
return this.Accounts.get(accountid);
};
},
CurrentAccount(state): Account | undefined {
if (state.CurrentAccountID == null)
return undefined;
if (state.CurrentAccountID == null) return undefined;
return state.Accounts.get(state.CurrentAccountID);
return this.GetAccount(state.CurrentAccountID);
},
OnBudgetAccounts(state) {
return [...state.Accounts.values()].filter(x => x.OnBudget);
return [...state.Accounts.values()].filter((x) => x.OnBudget);
},
OnBudgetAccountsBalance(state): number {
return this.OnBudgetAccounts.reduce((prev, curr) => prev + Number(curr.Balance), 0);
return this.OnBudgetAccounts.reduce(
(prev, curr) => prev + Number(curr.ClearedBalance),
0
);
},
OffBudgetAccounts(state) {
return [...state.Accounts.values()].filter(x => !x.OnBudget);
return [...state.Accounts.values()].filter((x) => !x.OnBudget);
},
OffBudgetAccountsBalance(state): number {
return this.OffBudgetAccounts.reduce((prev, curr) => prev + Number(curr.Balance), 0);
return this.OffBudgetAccounts.reduce(
(prev, curr) => prev + Number(curr.ClearedBalance),
0
);
},
TransactionsList(state) {
return (state.Transactions || []);
}
},
actions: {
async SetCurrentAccount(budgetid: string, accountid: string) {
if (budgetid == null)
return
if (budgetid == null) return;
this.CurrentAccountID = accountid;
if (this.CurrentAccount == undefined)
return
useSessionStore().setTitle(this.CurrentAccount.Name);
await this.FetchAccount(accountid);
if (accountid == null) return;
const account = this.GetAccount(accountid)!;
useSessionStore().setTitle(account.Name);
await this.FetchAccount(account);
},
async FetchAccount(accountid: string) {
const result = await GET("/account/" + accountid + "/transactions");
async FetchAccount(account: Account) {
const result = await GET(
"/account/" + account.ID + "/transactions"
);
const response = await result.json();
this.Transactions = response.Transactions;
const transactionsStore = useTransactionsStore();
const transactions = transactionsStore.AddTransactions(
response.Transactions
);
account.Transactions = transactions;
},
async FetchMonthBudget(budgetid: string, year: number, month: number) {
const result = await GET("/budget/" + budgetid + "/" + year + "/" + month);
const result = await GET(
"/budget/" + budgetid + "/" + year + "/" + (month + 1)
);
const response = await result.json();
if (
response.Categories == undefined ||
response.Categories.length <= 0
)
return;
this.addCategoriesForMonth(year, month, response.Categories);
},
addCategoriesForMonth(year: number, month: number, categories: Category[]): void {
async EditAccount(
accountid: string,
name: string,
onBudget: boolean,
isOpen: boolean
) {
const result = await POST(
"/account/" + accountid,
JSON.stringify({
name: name,
onBudget: onBudget,
isOpen: isOpen,
})
);
const response = await result.json();
useBudgetsStore().MergeBudgetingData(response);
if (!isOpen) {
this.Accounts.delete(accountid);
}
},
addCategoriesForMonth(
year: number,
month: number,
categories: Category[]
): void {
this.$patch((state) => {
const yearMap = state.Months.get(year) || new Map<number, Map<string, Category>>();
const monthMap = yearMap.get(month) || new Map<string, Category>();
const yearMap =
state.Months.get(year) ||
new Map<number, Map<string, Category>>();
const monthMap =
yearMap.get(month) || new Map<string, Category>();
for (const category of categories) {
monthMap.set(category.ID, category);
}
@ -117,13 +227,7 @@ export const useAccountStore = defineStore("budget/account", {
});
},
logout() {
this.$reset()
this.$reset();
},
async saveTransaction(payload: string) {
const result = await POST("/transaction/new", payload);
const response = await result.json();
this.Transactions.unshift(response);
}
}
})
},
});

View File

@ -4,17 +4,16 @@ import { useAccountStore } from "./budget-account";
import { Budget, useSessionStore } from "./session";
interface State {
CurrentBudgetID: string | null,
CurrentBudgetID: string | null;
}
export const useBudgetsStore = defineStore('budget', {
export const useBudgetsStore = defineStore("budget", {
state: (): State => ({
CurrentBudgetID: null,
}),
getters: {
CurrentBudget(): Budget | undefined {
if (this.CurrentBudgetID == null)
return undefined;
if (this.CurrentBudgetID == null) return undefined;
const sessionStore = useSessionStore();
return sessionStore.Budgets.get(this.CurrentBudgetID);
@ -27,7 +26,7 @@ export const useBudgetsStore = defineStore('budget', {
ImportYNAB(formData: FormData) {
return POST(
"/budget/" + this.CurrentBudgetID + "/import/ynab",
formData,
formData
);
},
async NewBudget(budgetName: string): Promise<void> {
@ -43,20 +42,29 @@ export const useBudgetsStore = defineStore('budget', {
async SetCurrentBudget(budgetid: string): Promise<void> {
this.CurrentBudgetID = budgetid;
if (budgetid == null)
return
if (budgetid == null) return;
await this.FetchBudget(budgetid);
},
async FetchBudget(budgetid: string) {
const result = await GET("/budget/" + budgetid);
const response = await result.json();
this.MergeBudgetingData(response);
},
MergeBudgetingData(response: any) {
const accounts = useAccountStore();
for (const account of response.Accounts || []) {
useAccountStore().Accounts.set(account.ID, account);
const existingAccount = accounts.Accounts.get(account.ID);
account.Transactions = existingAccount?.Transactions ?? [];
if (account.LastReconciled.Valid)
account.LastReconciled.Time = new Date(
account.LastReconciled.Time
);
accounts.Accounts.set(account.ID, account);
}
for (const category of response.Categories || []) {
useAccountStore().Categories.set(category.ID, category);
accounts.Categories.set(category.ID, category);
}
},
}
})
},
});

View File

@ -1,56 +1,74 @@
import { StorageSerializers, useStorage } from '@vueuse/core';
import { defineStore } from 'pinia'
import { POST } from '../api';
import { StorageSerializers, useStorage } from "@vueuse/core";
import { defineStore } from "pinia";
import { POST } from "../api";
interface State {
Session: Session | null
Budgets: Map<string, Budget>,
Session: Session | null;
Budgets: Map<string, Budget>;
}
interface Session {
Token: string
User: string
Token: string;
User: string;
}
export interface Budget {
ID: string
Name: string
AvailableBalance: number
ID: string;
Name: string;
AvailableBalance: number;
IncomeCategoryID: string;
}
export const useSessionStore = defineStore('session', {
export const useSessionStore = defineStore("session", {
state: () => ({
Session: useStorage<Session>('session', null, undefined, { serializer: StorageSerializers.object }),
Budgets: useStorage<Map<string, Budget>>('budgets', new Map<string, Budget>(), undefined, { serializer: StorageSerializers.map }),
Session: useStorage<Session | null>("session", null, undefined, {
serializer: StorageSerializers.object,
}),
Budgets: useStorage<Map<string, Budget>>(
"budgets",
new Map<string, Budget>(),
undefined,
{ serializer: StorageSerializers.map }
),
}),
getters: {
BudgetsList: (state) => [ ...state.Budgets.values() ],
AuthHeaders: (state) => ({'Authorization': 'Bearer ' + state.Session.Token}),
BudgetsList: (state) => [...state.Budgets.values()],
AuthHeaders: (state) => ({
Authorization: "Bearer " + state.Session?.Token,
}),
LoggedIn: (state) => state.Session != null,
},
actions: {
setTitle(title : string) {
setTitle(title: string) {
document.title = "Budgeteer - " + title;
},
loginSuccess(x : any) {
loginSuccess(x: any) {
this.Session = {
User: x.User,
Token: x.Token,
},
this.Budgets = x.Budgets;
};
for (const budget of x.Budgets) {
this.Budgets.set(budget.ID, budget);
}
},
async login(login: any) {
const response = await POST("/user/login", JSON.stringify(login));
const result = await response.json();
return this.loginSuccess(result);
this.loginSuccess(result);
return result;
},
async register(login : any) {
const response = await POST("/user/register", JSON.stringify(login));
async register(login: any) {
const response = await POST(
"/user/register",
JSON.stringify(login)
);
const result = await response.json();
return this.loginSuccess(result);
this.loginSuccess(result);
return result;
},
logout() {
this.$reset()
this.Session = null;
this.Budgets.clear();
},
}
})
},
});

View File

@ -2,17 +2,17 @@ import { useStorage } from "@vueuse/core";
import { defineStore } from "pinia";
interface State {
Menu: MenuSettings
Menu: MenuSettings;
}
interface MenuSettings {
Show: boolean | null,
Expand: boolean | null,
Show: boolean | null;
Expand: boolean | null;
}
export const useSettingsStore = defineStore('settings', {
export const useSettingsStore = defineStore("settings", {
state: () => ({
Menu: useStorage<MenuSettings>('settings', {
Menu: useStorage<MenuSettings>("settings", {
Show: null,
Expand: false,
}),
@ -24,5 +24,5 @@ export const useSettingsStore = defineStore('settings', {
toggleMenuSize() {
this.Menu.Expand = !this.Menu.Expand;
},
}
},
});

View File

@ -0,0 +1,110 @@
import { defineStore } from "pinia";
import { POST } from "../api";
import { useAccountStore } from "./budget-account";
interface State {
Transactions: Map<string, Transaction>;
Reconciling: boolean;
}
export interface Transaction {
ID: string;
Date: Date;
TransferAccount: string;
CategoryGroup: string;
Category: string;
CategoryID: string | undefined;
Memo: string;
Status: string;
GroupID: string;
Payee: string;
PayeeID: string | undefined;
Amount: number;
Reconciled: boolean;
}
export const useTransactionsStore = defineStore("budget/transactions", {
state: (): State => ({
Transactions: new Map<string, Transaction>(),
Reconciling: false,
}),
getters: {
ReconcilingBalance(state): number {
const accountsStore = useAccountStore();
let reconciledBalance =
accountsStore.CurrentAccount!.ReconciledBalance;
for (const transaction of this.TransactionsList) {
if (transaction.Reconciled)
reconciledBalance += transaction.Amount;
}
return reconciledBalance;
},
TransactionsList(state): Transaction[] {
const accountsStore = useAccountStore();
return accountsStore.CurrentAccount!.Transactions.map((x) => {
return this.Transactions.get(x)!;
});
},
},
actions: {
AddTransactions(transactions: Array<Transaction>) {
const transactionIds = [] as Array<string>;
this.$patch(() => {
for (const transaction of transactions) {
transaction.Date = new Date(transaction.Date);
this.Transactions.set(transaction.ID, transaction);
transactionIds.push(transaction.ID);
}
});
return transactionIds;
},
SetReconciledForAllTransactions(value: boolean) {
for (const transaction of this.TransactionsList) {
if (transaction.Status == "Reconciled") continue;
transaction.Reconciled = value;
}
},
async SubmitReconcilation(reconciliationTransactionAmount: number) {
const accountsStore = useAccountStore();
const account = accountsStore.CurrentAccount!;
const reconciledTransactions = this.TransactionsList.filter(
(x) => x.Reconciled
);
for (const transaction of reconciledTransactions) {
account.ReconciledBalance += transaction.Amount;
transaction.Status = "Reconciled";
transaction.Reconciled = false;
}
const result = await POST(
"/account/" + accountsStore.CurrentAccountID + "/reconcile",
JSON.stringify({
transactionIDs: reconciledTransactions.map((x) => x.ID),
reconciliationTransactionAmount:
reconciliationTransactionAmount.toString(),
})
);
const response = await result.json();
const recTrans = response.ReconciliationTransaction;
if (recTrans) {
this.AddTransactions([recTrans]);
account.Transactions.unshift(recTrans.ID);
}
},
logout() {
this.$reset();
},
async saveTransaction(payload: string) {
const accountsStore = useAccountStore();
const result = await POST("/transaction/new", payload);
const response = (await result.json()) as Transaction;
this.AddTransactions([response]);
accountsStore.CurrentAccount?.Transactions.unshift(response.ID);
},
async editTransaction(transactionid: string, payload: string) {
const result = await POST("/transaction/" + transactionid, payload);
const response = (await result.json()) as Transaction;
this.AddTransactions([response]);
},
},
});

View File

@ -1,10 +1,7 @@
module.exports = {
content: [
"./index.html",
"./src/**/*.{vue,js,ts,jsx,tsx}"
],
content: ["./index.html", "./src/**/*.{vue,js,ts,jsx,tsx}"],
theme: {
extend: {},
},
plugins: [],
}
};

View File

@ -1,7 +1,7 @@
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import path from 'path'
import path from "path";
// https://vitejs.dev/config/
export default defineConfig({
@ -9,21 +9,21 @@ export default defineConfig({
vue(),
// https://github.com/vuetifyjs/vuetify-loader/tree/next/packages/vite-plugin
],
define: { 'process.env': {} },
define: { "process.env": {} },
resolve: {
alias: {
'@': path.resolve(__dirname, 'src'),
"@": path.resolve(__dirname, "src"),
},
},
server: {
host: '0.0.0.0',
host: "0.0.0.0",
proxy: {
'/api': {
target: 'http://10.0.0.162:1323/',
changeOrigin: true
}
}
}
"/api": {
target: "http://10.0.0.162:1323/",
changeOrigin: true,
},
},
},
/* remove the need to specify .vue files https://vitejs.dev/config/#resolve-extensions
resolve: {
extensions: [
@ -37,4 +37,4 @@ export default defineConfig({
]
},
*/
})
});

File diff suppressed because it is too large Load Diff