Compare commits

...

422 Commits

Author SHA1 Message Date
James Cole
31128020f0 Merge branch 'release/3.4.0.2' 2015-05-08 07:57:06 +02:00
James Cole
7a2f169dfc Push new version. 2015-05-08 07:56:55 +02:00
James Cole
ed910b99a7 Update travis configuration [skip ci] 2015-05-08 07:48:04 +02:00
James Cole
54195c0826 Updated tests. 2015-05-08 07:39:05 +02:00
James Cole
cefbbcd1df Fixed some tests. 2015-05-08 07:27:29 +02:00
James Cole
cc01592085 Cover some more account repository. 2015-05-08 06:01:39 +02:00
James Cole
5a98a5252d Added tests. 2015-05-07 21:26:00 +02:00
James Cole
184e8b1132 Some new tests. 2015-05-07 20:56:27 +02:00
James Cole
2b6b896c2e Some more coverage. 2015-05-06 18:09:45 +02:00
James Cole
96d06b7a93 Added incomplete tests. 2015-05-05 22:46:28 +02:00
James Cole
f54f1611b5 First tests for account repository. 2015-05-05 20:46:13 +02:00
James Cole
69ad757e8b Lazily remove todo's [skip ci] 2015-05-05 13:03:39 +02:00
James Cole
e0beb796ad Some cleaning up [skip ci] 2015-05-05 13:03:04 +02:00
James Cole
f331e7d820 Removed unnecessary imports (use statements) [skip ci] 2015-05-05 12:57:27 +02:00
James Cole
cbb62d3d78 Added new line at the end of files. [skip ci] 2015-05-05 12:51:57 +02:00
James Cole
c85bc59c1d Merge branch 'release/3.4.0.1' into develop 2015-05-05 12:35:23 +02:00
James Cole
8081eeb007 Merge branch 'release/3.4.0.1' 2015-05-05 12:35:22 +02:00
James Cole
56f91bd10d Increment version. 2015-05-05 12:35:11 +02:00
James Cole
8e20b78731 Cleanup. 2015-05-05 10:30:39 +02:00
James Cole
23a09b7081 Code cleanup. 2015-05-05 10:23:01 +02:00
James Cole
67fdd27499 Various code cleanup [skip ci] 2015-05-05 07:51:02 +02:00
James Cole
e1941daedd Updated phpdoc. [skip ci] 2015-05-05 07:48:34 +02:00
James Cole
f28bc568a4 Some cleanup [skip ci] 2015-05-05 07:43:16 +02:00
James Cole
f24cfe39aa Expanded some tests. 2015-05-05 07:41:30 +02:00
James Cole
59d2bf3f79 Covered transaction controller. 2015-05-05 07:28:04 +02:00
James Cole
3176e54614 Partial coverage of the transaction controller. 2015-05-04 23:46:14 +02:00
James Cole
eb090f7265 Better factory. 2015-05-04 22:33:52 +02:00
James Cole
6d3a9bfd18 Some cleaning up 2015-05-04 22:33:03 +02:00
James Cole
76f08b7acb Full coverage for chart controller. 2015-05-04 19:28:49 +02:00
James Cole
1ff99346aa Update chart [skip ci] 2015-05-04 18:51:51 +02:00
James Cole
369695ab32 Update chart [skip ci] 2015-05-04 18:51:38 +02:00
James Cole
7e23dd1d66 Update composer.lock [skip ci] 2015-05-04 18:45:32 +02:00
James Cole
0205d3fc5c Overspent transactions have a separate colour [skip ci] 2015-05-04 18:45:20 +02:00
James Cole
4660cf2ad5 Fixed a bug in the display of the current currency code. 2015-05-03 16:16:43 +02:00
James Cole
e26d08d674 Update git ignore. [skip ci] 2015-05-03 16:14:15 +02:00
James Cole
0932bf2797 Don't need these files [skip ci] 2015-05-03 16:13:38 +02:00
James Cole
f560fc6d76 Covered search controller. 2015-05-03 15:55:19 +02:00
James Cole
aa6209af00 Covered tag controller. 2015-05-03 15:00:39 +02:00
James Cole
4a51176193 General cleanup. 2015-05-03 12:58:55 +02:00
James Cole
bb84f7a434 Fixed parameter order [skip ci] 2015-05-03 12:54:39 +02:00
James Cole
48168b1ef0 Covered report controller. 2015-05-03 11:02:34 +02:00
James Cole
8281c7c83e Don't escape currency symbol [skip ci] 2015-05-03 10:11:16 +02:00
James Cole
a07c1e3c71 See code. [skip ci] 2015-05-03 10:07:18 +02:00
James Cole
0766bb31fe Better amount formatting [skip ci] 2015-05-03 10:03:50 +02:00
James Cole
ff4472c1a5 FormatAmountPlain is HTML safe [skip ci] 2015-05-03 10:01:38 +02:00
James Cole
17424740e5 Show plain amount instead of coloured amounts. [skip ci] 2015-05-03 10:00:47 +02:00
James Cole
dad0b2fcd3 Show plain amount instead of coloured amounts. [skip ci] 2015-05-03 10:00:03 +02:00
James Cole
c48dbf030f Covered the reminder controller. 2015-05-03 09:55:22 +02:00
James Cole
617808d603 Covered profile controller with tests. 2015-05-03 09:19:14 +02:00
James Cole
845149deee Boxes are empty, so even when it's zero, place the amount. 2015-05-03 08:56:44 +02:00
James Cole
1a9e009327 Merge branch 'release/3.4' into develop 2015-05-02 23:51:45 +02:00
James Cole
ae90815708 Merge branch 'release/3.4' 2015-05-02 23:51:44 +02:00
James Cole
1c460343b7 New version! 2015-05-02 23:51:34 +02:00
James Cole
26079622f9 Fixed JSON controller tests. 2015-05-02 23:39:39 +02:00
James Cole
06c6d6096f Fixed coverage. 2015-05-02 23:28:04 +02:00
James Cole
c8183aea51 Format amount [skip ci] 2015-05-02 22:50:40 +02:00
James Cole
7531134ad2 Some tag related fine tuning. 2015-05-02 22:41:32 +02:00
James Cole
cd0c6439c2 Delete tags now possible. 2015-05-02 22:30:59 +02:00
James Cole
c918c93f51 Forget me own head next. [skip ci] 2015-05-02 22:13:37 +02:00
James Cole
97d3bd68ed Show balance act tags. 2015-05-02 22:12:26 +02:00
James Cole
75f1e034ae Fixed menu. [skip ci] 2015-05-02 22:09:21 +02:00
James Cole
8e72f218f1 Show HTML 2015-05-02 22:05:57 +02:00
James Cole
d643e05c5a Basic amount format fix. 2015-05-02 22:05:18 +02:00
James Cole
fea44834d0 Fixed test to match fixed controller. 2015-05-02 21:22:27 +02:00
James Cole
195a2d7523 Removed all the old views. 2015-05-02 21:18:04 +02:00
James Cole
b2fd346ef8 Merge branch 'feature/twig' into develop 2015-05-02 21:16:21 +02:00
James Cole
1ff8b62cb7 And now with actual coverage. 2015-05-02 19:44:31 +02:00
James Cole
c7ae15a41a This should fix all twig tests. Let's find out! 2015-05-02 19:44:12 +02:00
James Cole
efe6f59f79 Last templates. Should cover everything. [skip ci] 2015-05-02 19:19:47 +02:00
James Cole
8e31d0491d Fixed search [skip ci] 2015-05-02 18:30:59 +02:00
James Cole
73d4a10351 Fixed reports [skip ci] 2015-05-02 18:26:55 +02:00
James Cole
81d9d4dbc7 Various files updated to twig [skip ci] 2015-05-02 13:20:49 +02:00
James Cole
184ec13f99 Fixed bills [skip ci] 2015-05-02 12:51:02 +02:00
James Cole
dee0422eff Fix preferences [skip ci] 2015-05-02 12:22:19 +02:00
James Cole
81a2975f1a Show piggy banks [skip ci] 2015-05-02 11:32:45 +02:00
James Cole
5cd2ef4a5e Some generic templates and the first piggy bank ones [skip ci] 2015-05-02 10:53:54 +02:00
James Cole
466c2a68c2 Add delete form [skip ci] 2015-05-02 10:42:41 +02:00
James Cole
0fb9fba531 New currency routes 2015-05-02 10:40:20 +02:00
James Cole
356dd2c6cd Creat / edit / index [skip ci] 2015-05-02 10:37:16 +02:00
James Cole
32c4661233 Fixed no budget / no category bread crumb [skip ci] 2015-05-02 09:49:37 +02:00
James Cole
a245b504ec Fixed bread crumbs. 2015-05-02 09:31:57 +02:00
James Cole
a2f5fbdfd3 Working on two more views [skip ci] 2015-05-02 09:29:34 +02:00
James Cole
04be26adc5 Fixed title [skip ci] 2015-05-02 09:26:20 +02:00
James Cole
be0adb7cf2 Create / edit category 2015-05-02 09:25:45 +02:00
James Cole
84fd92bf5a Categories [skip ci] 2015-05-02 09:21:42 +02:00
James Cole
ee4e061739 Removed code from budget index [skip ci] 2015-05-02 09:21:32 +02:00
James Cole
4a2b01cd9a Menu fixes [skip ci] 2015-05-02 09:16:17 +02:00
James Cole
efdd6460fb Fixed injection. 2015-05-02 09:08:41 +02:00
James Cole
803827e05c Fixed more views. [skip ci] 2015-05-02 09:06:07 +02:00
James Cole
a41d5e9ab3 New budget [skip ci] 2015-05-02 08:32:20 +02:00
James Cole
e94333f877 Can view budgets [skip ci] 2015-05-02 08:28:24 +02:00
James Cole
6dbb80d687 Optimisations [skip ci] 2015-05-02 08:09:54 +02:00
James Cole
31a1031624 And delete is fixed. 2015-05-01 23:39:45 +02:00
James Cole
f8e9ce0d52 Can edit as well. 2015-05-01 23:35:35 +02:00
James Cole
11baa968cd Can create accounts. 2015-05-01 23:17:17 +02:00
James Cole
3e5e5b376f Made it almost to the accounts. 2015-05-01 22:44:35 +02:00
James Cole
bda18f296d Optimised Twig extensions. 2015-05-01 20:17:06 +02:00
James Cole
287d110c84 Small bug fix in budget chart. 2015-05-01 18:45:42 +02:00
James Cole
c98275e73a More templates converted to twig. 2015-05-01 18:44:49 +02:00
James Cole
aa573cc951 Fix redirect 2015-05-01 14:32:31 +02:00
James Cole
883d3d86e3 Update a test. 2015-05-01 14:32:26 +02:00
James Cole
fb047bd5f4 Fix migration. 2015-05-01 08:34:53 +02:00
James Cole
66a04d8365 Slightly different chart on index. 2015-05-01 08:34:44 +02:00
James Cole
a0e501f9fd First attempt at implementing Twig. 2015-05-01 08:29:41 +02:00
James Cole
8b40d3346d An attempt at showing tag info. 2015-05-01 06:47:24 +02:00
James Cole
eddf5cd250 Fix button, close #74 2015-05-01 06:38:48 +02:00
James Cole
ee5c534ca3 Took the time to fix the tests. 2015-04-30 17:32:00 +02:00
James Cole
fd4e77ae0f Catch empty tags. 2015-04-28 21:01:54 +02:00
James Cole
b747c50aa3 Fix method to return object, not key. 2015-04-28 21:00:26 +02:00
James Cole
deebdd86a6 And another small JS fix [skip ci] 2015-04-28 20:20:16 +02:00
James Cole
b2db79cc10 Fixed some small CSS / JS problems. 2015-04-28 20:17:31 +02:00
James Cole
bbab370b1e Some new code. 2015-04-28 17:10:52 +02:00
James Cole
db4adf399d Cleaning up. 2015-04-28 15:26:30 +02:00
James Cole
0683c87e52 Small check in tags. 2015-04-28 14:08:58 +02:00
James Cole
3f62b647fc Removed code related to "related transactions". 2015-04-28 13:50:53 +02:00
James Cole
2562a5b30d Don't save all tags unconditionally. 2015-04-28 13:47:13 +02:00
James Cole
e232f2e223 Delete tags 2015-04-28 11:04:46 +02:00
James Cole
21644ff4dd Routes will throw 404's 2015-04-28 11:04:38 +02:00
James Cole
be96a4fce5 Show tags in transaction. 2015-04-28 10:51:56 +02:00
James Cole
a1cabcbed3 Show tag icons. 2015-04-28 10:50:43 +02:00
James Cole
ce933b1f06 Edit and update tags. 2015-04-28 10:36:13 +02:00
James Cole
51ae130922 Fixed the build by adding new migrations for each step. 2015-04-28 09:54:22 +02:00
James Cole
da1bc18a47 Better list for piggy banks. 2015-04-28 09:15:31 +02:00
James Cole
e7165a526b First attempt at basic tag functionality. 2015-04-28 08:58:01 +02:00
James Cole
6081cc399f Small bug fixes and cleaning up. 2015-04-28 08:12:12 +02:00
James Cole
7c5c24e15d Moved edit buttons. 2015-04-26 07:42:55 +02:00
James Cole
e3e55b4347 Moved all create-buttons lower. 2015-04-26 07:39:49 +02:00
James Cole
40d8e7d1ad Fixed a bug where transfers away from a piggy bank's account would not properly reflect the piggy bank. 2015-04-24 12:06:13 +02:00
James Cole
59e23b89f2 Removed unnecessary sort. 2015-04-24 11:54:23 +02:00
James Cole
cc33af8193 Could not set order. 2015-04-24 10:00:56 +02:00
James Cole
0e1e7eb2a9 Merge branch 'release/3.3.9' 2015-04-22 08:08:14 +02:00
James Cole
52a28a7758 Merge branch 'release/3.3.9' into develop 2015-04-22 08:08:14 +02:00
James Cole
3f752d6832 New read me. 2015-04-22 08:08:05 +02:00
James Cole
fe714e9989 Built a routine that will allow you to completely delete an account. 2015-04-22 07:54:56 +02:00
James Cole
0d3213a379 Covered the preferences controller. 2015-04-21 17:19:14 +02:00
James Cole
44056629e8 Use local db instead of constant migrating. 2015-04-20 22:08:24 +02:00
James Cole
54125c05d3 New tests and prep for future runs. 2015-04-20 21:57:20 +02:00
James Cole
7d32e50f25 Mentioned wrong amount. 2015-04-20 20:56:28 +02:00
James Cole
4af9ff49a0 Fixed a bug in the report controller that grouped transactions wrong. 2015-04-20 20:54:55 +02:00
James Cole
23faef845c Merge branch 'release/3.3.8' 2015-04-20 18:07:02 +02:00
James Cole
41dad4091a Merge branch 'release/3.3.8' into develop 2015-04-20 18:07:02 +02:00
James Cole
daf859b977 Updated read me. 2015-04-20 18:06:37 +02:00
James Cole
f47ba6c977 Update example file. 2015-04-20 18:06:21 +02:00
James Cole
4b9b207d92 Removed development references. 2015-04-20 17:59:04 +02:00
James Cole
875cbf66af 1 should be 0 2015-04-19 19:10:53 +02:00
James Cole
412d6d4fd7 Small CSS fix for piggy banks [skip ci] 2015-04-19 17:43:04 +02:00
James Cole
91c6deeb1f Renamed another field. 2015-04-19 14:28:17 +02:00
James Cole
6d1978fd9a Showed the wrong value. 2015-04-19 14:27:08 +02:00
James Cole
52d23b6ef5 Referred to an id which turned out to be a index. 2015-04-19 14:19:25 +02:00
James Cole
0656ccbdd9 Fixed a bug where the query would include deleted transactions. 2015-04-19 13:57:43 +02:00
James Cole
e774ebd0a3 Possible bug in account create thing. [skip ci] 2015-04-18 16:04:21 +02:00
James Cole
edbda32a84 Fix balance. 2015-04-13 21:13:05 +02:00
James Cole
721fa04e3c Added home screen information about piggy banks. 2015-04-13 20:43:58 +02:00
James Cole
9fd8d8915d amount > queryAmount 2015-04-12 10:53:53 +02:00
James Cole
7a9f5ebdd1 Added "what" variable. 2015-04-12 10:22:15 +02:00
James Cole
a3423f0321 Add the correct path to category overview. 2015-04-12 10:19:37 +02:00
James Cole
c37e9a4467 Covered the JSON controller. 2015-04-11 19:59:41 +02:00
James Cole
6157d82a0b time format 2015-04-11 18:52:03 +02:00
James Cole
38b27fec92 Without moment.js 2015-04-11 18:49:57 +02:00
James Cole
c43439bb68 Test for date. 2015-04-11 18:47:37 +02:00
James Cole
8d9561d7a5 Removed data-value. 2015-04-11 18:45:01 +02:00
James Cole
2a72cce3b7 Included date format. 2015-04-11 15:11:45 +02:00
James Cole
d3bbb6fb1f Removed date value. 2015-04-11 15:11:19 +02:00
James Cole
7b6723e9a2 Update date format. 2015-04-11 15:10:29 +02:00
James Cole
1ee741460d Updated empty entries as well. 2015-04-11 15:09:48 +02:00
James Cole
967b0b493b Switched dates around. 2015-04-11 15:07:42 +02:00
James Cole
b53aaf7dde Fixed sort format. 2015-04-11 15:06:10 +02:00
James Cole
714c13bdbf Include moment.js 2015-04-11 15:04:16 +02:00
James Cole
651a4fd3cc Sortable accounts. 2015-04-11 15:01:42 +02:00
James Cole
505aee22bb Sortable categories. 2015-04-11 14:53:22 +02:00
James Cole
ca3d59dc33 Another fix. 2015-04-11 12:51:58 +02:00
James Cole
13890e32a1 Fixed a view and a botched include. 2015-04-11 12:50:56 +02:00
James Cole
df8976eabe Journals that no longer match a bill will be removed. 2015-04-11 12:40:47 +02:00
James Cole
3e01daa172 Query & loop optimizations. 2015-04-11 12:36:17 +02:00
James Cole
f6999f355b Some foreach loop cleaning up. 2015-04-11 12:27:56 +02:00
James Cole
5c06b45eb1 Code cleanup. 2015-04-11 07:32:11 +02:00
James Cole
1802bb967a Moved JSON money boxes to individual functions. 2015-04-11 07:24:07 +02:00
James Cole
d8d92f147f Removed logging, found bug. 2015-04-10 07:29:36 +02:00
James Cole
4a95bdd8ba Added temporary debug to google chart. 2015-04-10 07:25:24 +02:00
James Cole
db5d94d956 Added temporary debug entries. 2015-04-10 07:19:45 +02:00
James Cole
06f2e34bb5 Renamed the amount variable so it stops interfering with another variable 2015-04-10 06:57:39 +02:00
James Cole
2ef7a01945 Fixed a bug where the bill chart and boxes would inaccurately reflect the amount of bills yet to pay. 2015-04-10 06:52:36 +02:00
James Cole
d3f642551d Fixed a small bug in the bill-chart and simplified yet another Json box. 2015-04-09 21:36:58 +02:00
James Cole
490997157e Switched two queries around. 2015-04-09 21:30:35 +02:00
James Cole
2432af7883 Simplified the in and out-box. 2015-04-09 21:29:58 +02:00
James Cole
7abeece3f0 Simplified the "out"-box. 2015-04-09 21:27:35 +02:00
James Cole
3851652821 Renamed various fields from 'amount' to 'queryAmount' to prevent interfering with the getAmountAttribute property. 2015-04-09 21:18:18 +02:00
James Cole
1d67d2250a Renamed various fields from 'amount' to 'queryAmount' to prevent interfering with the getAmountAttribute property. 2015-04-09 21:16:35 +02:00
James Cole
37f40d8637 Renamed various fields from 'amount' to 'queryAmount' to prevent interfering with the getAmountAttribute property. 2015-04-09 21:14:15 +02:00
James Cole
0224d1d59b Accidentally commented out date limits in query. 2015-04-09 21:01:08 +02:00
James Cole
587b94153d Removed some foreach() routines that are no longer necessary now that getAmountAttribute() exists. 2015-04-09 20:58:57 +02:00
James Cole
5124ce0302 Fixed a bug where getAmountAttribute would interfere with queries that contained a "amount"-field. 2015-04-09 20:52:47 +02:00
James Cole
950c4045b0 Fix total savings to accurately reflect end of current period. 2015-04-09 19:10:24 +02:00
James Cole
9c8ba66873 Order categories by name. 2015-04-09 17:54:24 +02:00
James Cole
25d1d1be1b Merge pull request #72 from vbali/feature/savings-total
Add savings total for savings widget on dashboard
2015-04-09 17:47:24 +02:00
James Cole
339c352505 Fixed a bug where categories would be created even though they already existed. 2015-04-09 17:46:47 +02:00
Balazs Varkonyi
c587081fe4 Add savings total for savings widget on dashboard 2015-04-09 11:52:35 +02:00
James Cole
8f9b1b866b Included full home controller tests. 2015-04-07 20:54:43 +02:00
James Cole
ff5ecf6182 More tests. 2015-04-07 19:58:49 +02:00
James Cole
05670cf393 Optimize test code. 2015-04-07 18:52:15 +02:00
James Cole
f10f5d30bf Mock previously unmocked calls. 2015-04-07 18:48:34 +02:00
James Cole
0d336727e8 Automated code cleanup. 2015-04-07 18:26:14 +02:00
James Cole
bf354275b3 Some general cleaning up. 2015-04-07 18:25:21 +02:00
James Cole
1932bf277a More tests 2015-04-07 17:51:22 +02:00
James Cole
192db4bb6e Accidentally included JS twice. 2015-04-07 10:14:20 +02:00
James Cole
701efb943d Lots of new tests. 2015-04-07 10:14:10 +02:00
James Cole
b2674971f1 Updated composer.lock. 2015-04-06 09:20:45 +02:00
James Cole
c907cb4cf1 General cleanup and new (incomplete) tests. 2015-04-06 09:15:59 +02:00
James Cole
bb1462b4d9 Merge branch 'release/3.3.7' 2015-04-05 21:15:01 +02:00
James Cole
1035f0e139 Merge branch 'release/3.3.7' into develop 2015-04-05 21:15:01 +02:00
James Cole
8475757716 Removed iconv() commented code. See other commit. 2015-04-05 21:14:41 +02:00
James Cole
20ffd8d61b New read me. 2015-04-05 21:14:25 +02:00
James Cole
8601428c4c Fixed a bug in the form request that wouldn't accept fairly long names. 2015-04-05 21:12:54 +02:00
James Cole
59998573ee Removed iconv thing that doesn't seem to matter. See screenshot at https://imgur.com/8r26ZZu 2015-04-05 21:12:31 +02:00
James Cole
293cd72001 Add currency tests. 2015-04-05 20:47:19 +02:00
James Cole
22ab9ebb2f Included tests for the category controller. 2015-04-05 19:43:20 +02:00
James Cole
9136e592d3 Included bill controller. 2015-04-05 18:20:06 +02:00
James Cole
ed8e392616 Fixed budget controller tests. 2015-04-05 15:53:03 +02:00
James Cole
e57ce6e644 Test now works. 2015-04-05 15:25:35 +02:00
James Cole
8204e46086 Removed inspiring quotes. 2015-04-05 10:38:53 +02:00
James Cole
9e365d9f80 Mar tests. 2015-04-05 10:36:28 +02:00
James Cole
6b40a933e9 And.. completed the account controller. 2015-04-04 22:53:49 +02:00
James Cole
8520a5002f Another attempt at fixing some tests. I'm probably searching in the wrong direction with this. 2015-04-04 22:27:51 +02:00
James Cole
b38ed06f6e New tests. 2015-04-04 21:52:56 +02:00
James Cole
48427b1143 A mediocre fix for the database failures. 2015-04-04 21:33:36 +02:00
James Cole
5d505f4ed0 Fixed more tests but the factories are not perfect yet. 2015-04-04 21:23:37 +02:00
James Cole
0c02a08954 Merge pull request #65 from vbali/master
Fixes for chart and account creation
2015-04-04 06:50:30 +02:00
Balazs Varkonyi
0221bd0f80 Merge branch 'hotfix/diff–fix' 2015-04-04 01:56:25 +02:00
Balazs Varkonyi
28216cbcb5 Removed merge conflict from CategoryController 2015-04-04 01:56:19 +02:00
Balazs Varkonyi
3e08a8cd6b Merge branch 'hotfix/account-fix' 2015-04-04 01:37:05 +02:00
Balazs Varkonyi
67fafdeef7 Return the new account from firstOrCreateEncrypted 2015-04-04 01:36:55 +02:00
Balazs Varkonyi
cc82505b66 Merge branch 'hotfix/chart-fix' 2015-04-04 01:33:36 +02:00
Balazs Varkonyi
fd5f075f63 Chart fix for accounts with accented letters 2015-04-04 01:31:57 +02:00
James Cole
a115960411 Merge branch 'release/3.3.6'
Conflicts:
	app/Http/Controllers/CategoryController.php
2015-04-03 23:31:29 +02:00
James Cole
e9fa4ca816 New version in read me. 2015-04-03 23:30:54 +02:00
James Cole
75d92bc7f0 Allow FF to send events. 2015-04-03 23:22:23 +02:00
James Cole
74aa6e911e Make boxes respond to unpaid / paid credit card bills. 2015-04-03 23:10:51 +02:00
James Cole
9d000c1898 Added amount because debug. 2015-04-03 23:05:50 +02:00
James Cole
b2254875b2 Expanded to credit cards. 2015-04-03 22:54:21 +02:00
James Cole
78d04230d5 New CC help text. 2015-04-03 21:25:04 +02:00
James Cole
1c04477393 Support credit cards (in name only). 2015-04-03 21:12:54 +02:00
James Cole
2a9679c94e Textual fix in bill [skip ci] 2015-04-03 21:05:41 +02:00
James Cole
6009f8ecde Better chart for bills. 2015-04-03 21:05:01 +02:00
James Cole
35cdbec70a Clean up for budget limits. 2015-04-03 19:39:36 +02:00
James Cole
0faef542c1 Fixed a bug in the budget controller. 2015-04-03 19:11:55 +02:00
James Cole
8b085af6a1 First attempt at account controller::index. 2015-04-03 12:14:40 +02:00
James Cole
e3b11a9eb2 New test for edit form that is more inclusive. 2015-04-03 09:30:44 +02:00
James Cole
72fc88f3c6 Even more tests. 2015-04-03 08:55:24 +02:00
James Cole
a5b759f268 Updates TestCase.php 2015-04-03 08:37:53 +02:00
James Cole
6a9ffae25d New tests and factories. 2015-04-03 08:31:50 +02:00
James Cole
64c031c7fe Small updates [skip ci] 2015-04-03 07:44:44 +02:00
James Cole
720926c50d Tests now run without a database, as they should. 2015-04-03 07:33:18 +02:00
James Cole
36ec974284 Add heavy but working migrate routine. Will fix the tests but must be optimised. Also, should not be necessary. 2015-04-02 22:51:00 +02:00
James Cole
cff77c39e2 Update travis-ci and composer.lock and composer.json 2015-04-02 22:46:50 +02:00
James Cole
056a0a1736 Smaller boxes. 2015-04-02 22:43:12 +02:00
James Cole
f301da83c6 Fixed the tests. 2015-04-02 22:39:31 +02:00
James Cole
5362231efa Ignore virtual balance in select places. 2015-04-01 19:46:16 +02:00
James Cole
4bb14cad73 Allow virtual balance to be ignored. 2015-04-01 19:45:13 +02:00
James Cole
7f5188f5a4 Added something fancy called "virtual balance". 2015-04-01 19:42:14 +02:00
James Cole
a80b7aac6c Fix more redirections. 2015-04-01 18:59:34 +02:00
James Cole
83f32478fa Fixed more redirections. 2015-04-01 09:43:19 +02:00
James Cole
7578ec6801 Fix redirections in budget. 2015-04-01 09:40:19 +02:00
James Cole
e14a32f76f Also fix delete/destroy redirection routine. 2015-04-01 09:23:51 +02:00
James Cole
58faa189ac Can now actually store transactions without an expense / revenue account. 2015-04-01 09:17:07 +02:00
James Cole
9b4f87d44a Fix checkbox for edit screen. 2015-04-01 09:16:51 +02:00
James Cole
7830a64170 Fix redirect. 2015-04-01 09:16:41 +02:00
James Cole
8f0fa02107 Better redirection for new transactions. 2015-04-01 09:12:49 +02:00
James Cole
e000fb5d80 Optimized decryption. 2015-03-31 22:46:11 +02:00
James Cole
566fadad15 Add decryption routine. 2015-03-31 21:18:22 +02:00
James Cole
cf23858c10 Gokje. 2015-03-31 20:52:48 +02:00
James Cole
216a223617 Fix in year list. 2015-03-31 20:49:02 +02:00
James Cole
638f38d823 New flush method. 2015-03-31 20:46:37 +02:00
James Cole
98ee70f04e Fix range thing. 2015-03-31 20:45:06 +02:00
James Cole
b365db5a4b New hidden id field. 2015-03-31 20:39:28 +02:00
James Cole
02e55496df Remove reminders when piggy bank is reminded. 2015-03-31 20:22:51 +02:00
James Cole
e11e53913a Some new code + GA 2015-03-31 19:21:49 +02:00
James Cole
f8a5fb4225 Fixed tests. 2015-03-31 17:49:47 +02:00
James Cole
3a49450461 Made sure migrations can be rolled back. 2015-03-31 15:38:44 +02:00
James Cole
3c375fb955 Remove build stuff because sqlite does not work with change things. 2015-03-31 15:24:13 +02:00
James Cole
011fea2cc6 Fix encryption in home chart. 2015-03-31 15:10:22 +02:00
James Cole
a079eec2cb Better unicity for objects. 2015-03-31 14:16:25 +02:00
James Cole
776b37f4ea Clean up some code, optimise the 503 error. 2015-03-30 21:24:56 +02:00
James Cole
a4d8bbe3da Fixed a bug where certain types of accounts could not be validated. 2015-03-30 20:16:33 +02:00
James Cole
72166743fa Merge branches 'develop' and 'develop' of https://github.com/JC5/firefly-iii into develop 2015-03-30 20:08:40 +02:00
James Cole
c4312c0b11 Extra large code cleanup. 2015-03-30 20:08:27 +02:00
James Cole
38ba645415 Add hidden-xs class. 2015-03-30 09:23:18 +02:00
James Cole
ac12a47071 Hide inactive budgets when there are none. 2015-03-29 21:29:37 +02:00
James Cole
bea321939e Code rearrange and optimise. 2015-03-29 21:27:51 +02:00
James Cole
210f84b6ea Allow edit from budget overview, and allow changing of active setting. 2015-03-29 21:27:13 +02:00
James Cole
d4c642741f Fixed division by zero. 2015-03-29 21:09:33 +02:00
James Cole
e6b1b58379 Enable inactive budgets. 2015-03-29 19:50:29 +02:00
James Cole
8d982c1a90 Some extensions. 2015-03-29 19:44:59 +02:00
James Cole
be10e836dc Updated composer.lock 2015-03-29 19:40:22 +02:00
James Cole
9be05e7e17 Small optimisations. 2015-03-29 18:28:49 +02:00
James Cole
bd96b2819f Removed double code. 2015-03-29 12:32:00 +02:00
James Cole
f601af3da0 Cleaned up report controller. 2015-03-29 12:25:46 +02:00
James Cole
70a01c082b Removed some double code. 2015-03-29 12:12:06 +02:00
James Cole
bcf066ead7 Cleaned up some double code. 2015-03-29 11:51:26 +02:00
James Cole
24dd3578ed Merge branch 'release/3.3.5' into develop 2015-03-29 08:43:55 +02:00
James Cole
d5c39d54d8 Merge branch 'release/3.3.5' 2015-03-29 08:43:54 +02:00
James Cole
6e3f6abc67 New read me. 2015-03-29 08:43:46 +02:00
James Cole
463201df2c New gitignore. 2015-03-29 08:43:03 +02:00
James Cole
a7501c396f Renamed some methods. 2015-03-29 08:24:56 +02:00
James Cole
4c8bc49a7e Add newlines. 2015-03-29 08:22:48 +02:00
James Cole
f254674f88 Add newlines. 2015-03-29 08:21:33 +02:00
James Cole
a97c267378 Added new lines 2015-03-29 08:20:37 +02:00
James Cole
eaa947894b Updated composer.son 2015-03-29 08:20:30 +02:00
James Cole
fb3a26510b Removed some unused use statements. 2015-03-29 08:20:20 +02:00
James Cole
bfe8b14e49 Cleaned up. 2015-03-29 08:18:15 +02:00
James Cole
afb47eb742 Add newlines. 2015-03-29 08:14:32 +02:00
James Cole
ba97f96288 Removed unused use statements. 2015-03-29 08:03:53 +02:00
James Cole
ecbafb8f4b Removed commented out code. 2015-03-29 07:59:18 +02:00
James Cole
12d3800d67 Removed unused use statements. 2015-03-29 07:51:56 +02:00
James Cole
d586b82372 New composer.son file. 2015-03-29 07:45:14 +02:00
James Cole
ba9877c9b4 Add typehints to object parameters 2015-03-29 07:43:20 +02:00
James Cole
907933f3df Removed debug logic and bad operators. 2015-03-29 07:32:24 +02:00
James Cole
2e91d21a88 Add return to form routine to budgets. 2015-03-28 18:22:36 +01:00
James Cole
dca395a018 Merge branch 'release/3.3.4' 2015-03-28 17:45:56 +01:00
James Cole
625070a5b9 Merge branch 'release/3.3.4' into develop 2015-03-28 17:45:56 +01:00
James Cole
f875c7cbf5 Updated read me file. 2015-03-28 17:45:46 +01:00
James Cole
eed88fc103 Don't fail on repeated piggy banks, just log it. 2015-03-28 17:45:15 +01:00
James Cole
6fc54d1d27 Fixed the tests 2015-03-28 07:00:53 +01:00
James Cole
0ef52bf909 Remove recurring transactions [skip ci] 2015-03-28 06:59:43 +01:00
James Cole
95e34af6ef Update script [skip ci] 2015-03-28 06:51:54 +01:00
James Cole
650b99ead2 Ignore apple files. [skip ci] 2015-03-28 06:50:26 +01:00
James Cole
57941a19de Excutable. 2015-03-28 06:48:54 +01:00
James Cole
6157db0b6a Some new tests 2015-03-28 06:48:38 +01:00
James Cole
c9358acf5d Update tests and token replace routine. 2015-03-28 06:25:36 +01:00
James Cole
ed29eb8a5d New lock file. 2015-03-28 06:19:37 +01:00
James Cole
bcf7452312 Some new tests. 2015-03-28 06:19:09 +01:00
James Cole
b9000519e4 Fixed unique piggy check. 2015-03-27 20:20:52 +01:00
James Cole
2694297466 Fixed a bug where start / end would be used incorrectly. 2015-03-27 19:48:55 +01:00
James Cole
53ff5c1490 Wrong operator, 2015-03-27 19:47:31 +01:00
James Cole
32a036b076 Add certainty to chart. 2015-03-27 19:45:47 +01:00
James Cole
aae2ab2693 Unnecessary if statement. 2015-03-27 19:43:53 +01:00
James Cole
4ef23e28a3 Update year report. 2015-03-27 19:43:20 +01:00
James Cole
38beb7f8d2 Fallback. 2015-03-27 19:42:35 +01:00
James Cole
0129a66906 Debug hidden accounts in year reports. 2015-03-27 19:37:00 +01:00
James Cole
45bced7b34 Hide accounts with no activity during a year. 2015-03-27 19:34:37 +01:00
James Cole
7f5a55dffb Small updates to read me. 2015-03-27 19:21:51 +01:00
James Cole
80289df6d3 Capital letter 2015-03-27 18:58:28 +01:00
James Cole
2115c3ced8 Read me 2015-03-27 18:58:11 +01:00
James Cole
1c2d0e6618 Updated read me file 2015-03-27 18:57:49 +01:00
James Cole
ea4f7f79ce Removed more references. 2015-03-27 18:17:15 +01:00
James Cole
b17f8ac311 Removed references to repeated expenses. 2015-03-27 18:15:10 +01:00
James Cole
6870d13b72 Removed repeated expenses. 2015-03-27 18:14:17 +01:00
James Cole
81fa304fd2 Removed repeated expenses. 2015-03-27 18:13:53 +01:00
James Cole
a663ddb0d9 Hide accounts with no activity. 2015-03-27 13:39:12 +01:00
James Cole
f7969afc22 Hide accounts with no activity in budget report. 2015-03-27 13:36:33 +01:00
James Cole
52ce4cd313 Resort array. 2015-03-27 13:25:46 +01:00
James Cole
247175881f Moved some code. 2015-03-27 13:24:04 +01:00
James Cole
fcf5009338 Moved some code around. 2015-03-27 13:20:48 +01:00
James Cole
12542d8f63 Auto fill transaction descriptions. 2015-03-27 13:16:14 +01:00
James Cole
e94194e28b New favicon. 2015-03-27 13:04:53 +01:00
James Cole
115499f3b2 New favicon. 2015-03-27 11:59:07 +01:00
James Cole
12af05b94f Only display budgets when there's money in the envelope or when there's money spent. 2015-03-27 09:43:29 +01:00
James Cole
88b83d8164 Merge branch 'release/3.3.3' into develop 2015-03-27 09:36:04 +01:00
James Cole
fcc22c692a Merge branch 'release/3.3.3' 2015-03-27 09:36:03 +01:00
James Cole
a876e8005c New version. 2015-03-27 09:35:52 +01:00
James Cole
2288e3705a Fixed order view. 2015-03-27 09:29:14 +01:00
James Cole
e8b58154e0 Bug fix. 2015-03-27 09:24:26 +01:00
James Cole
4393475af3 Remove debug. 2015-03-27 09:22:08 +01:00
James Cole
3fc560597c Validation bug. 2015-03-27 09:21:09 +01:00
James Cole
9f9af0b693 Moved to account list. 2015-03-27 08:11:13 +01:00
James Cole
a83fe2caea Correct ordering (everywhere). 2015-03-27 07:32:06 +01:00
James Cole
30c5376217 Fix order. 2015-03-27 07:29:01 +01:00
James Cole
6dddd6629d Thing with order and should fix Travis. 2015-03-27 07:20:32 +01:00
James Cole
f80de12cb5 Fix sorting. 2015-03-26 22:53:34 +01:00
James Cole
544ffca3a5 Sortable transactions. 2015-03-26 22:52:49 +01:00
James Cole
e0730c7b39 Fixed double named accounts. 2015-03-26 18:05:23 +01:00
James Cole
3d59d141c4 Push! 2015-03-26 17:46:08 +01:00
James Cole
ccddc2623d Merge branch 'develop' of github.com:JC5/firefly-iii into develop 2015-03-26 17:45:58 +01:00
James Cole
fcc47b58b4 Return to edit / create screen when user indicates. 2015-03-26 17:45:03 +01:00
James Cole
f67ac2e25e Update AccountController.php 2015-03-26 14:50:49 +01:00
James Cole
26127c9ccf Update AccountController.php 2015-03-26 14:49:02 +01:00
James Cole
d624efa799 Fix registration bug. 2015-03-25 22:30:36 +01:00
James Cole
ed3d40a4e0 Whoops. 2015-03-25 22:29:32 +01:00
James Cole
6e90ce5496 Cant dismiss reminders again. 2015-03-25 19:12:33 +01:00
James Cole
ab851b1be4 Fixed transfers 2015-03-25 17:44:06 +01:00
James Cole
340de53825 Use normal logging. 2015-03-25 17:42:33 +01:00
James Cole
a867b60af0 Update CategoryController.php 2015-03-25 16:14:28 +01:00
James Cole
26eafb0bd2 Update CategoryController.php 2015-03-25 16:13:39 +01:00
James Cole
0dbe44764b Update GoogleChartController.php 2015-03-25 16:00:06 +01:00
James Cole
2159df6802 Update GoogleChartController.php
Fixed chart.
2015-03-25 15:58:37 +01:00
James Cole
23389b9f17 Update FireflyValidator.php
Update uniqueForUser.
2015-03-25 15:56:32 +01:00
James Cole
6d3e3b894a Update AccountFormRequest.php
Update rules to include belongsToUser.
2015-03-25 15:55:39 +01:00
James Cole
55340aefa3 Remove code. 2015-03-24 21:06:45 +01:00
James Cole
94bc751e41 Sum starts at 0. 2015-03-24 21:05:15 +01:00
James Cole
89259c11e2 Fix chart. 2015-03-24 21:04:53 +01:00
James Cole
6bbaf1523c Fixed a bug in relevantOnDate 2015-03-24 21:00:42 +01:00
James Cole
fa3f18b60f Expand log for event. 2015-03-24 20:56:58 +01:00
James Cole
3dc794002f This should catch the missing piggy bank events. 2015-03-24 20:54:25 +01:00
James Cole
f50b133f2e Cleaned up some icons, improved routine for repeated expenses. 2015-03-21 21:33:52 +01:00
James Cole
1d6f6d28c9 Update font in calendar. 2015-03-21 10:29:25 +01:00
James Cole
c913de3c8b Fix percentage. 2015-03-21 08:56:24 +01:00
James Cole
bbc7b54a38 Catch 0 start balance. 2015-03-21 08:55:55 +01:00
James Cole
05fa1b40d1 Support > 100% 2015-03-21 08:53:43 +01:00
James Cole
6a88c8634d Added a block with savings. 2015-03-21 08:51:34 +01:00
James Cole
8ae1efa230 Added type savings account. 2015-03-20 23:17:59 +01:00
James Cole
ab8df4c8ab Fixed css reference. 2015-03-20 22:50:50 +01:00
James Cole
c259a46ed3 Clean up sql codes. 2015-03-20 22:39:07 +01:00
James Cole
5dc0677599 Fixed search sort 2015-03-20 18:30:17 +01:00
James Cole
7ed662ecc2 Fixed search in encrypted entries. 2015-03-20 18:21:14 +01:00
James Cole
4361cc69d4 Update font options in charts. 2015-03-20 15:54:40 +01:00
James Cole
461cbcbc28 Update to use Roboto font. 2015-03-20 13:34:59 +01:00
James Cole
09ae6c488b Fixed a bug where the session date would be edited by a chart. 2015-03-20 08:16:16 +01:00
James Cole
271a0ade26 Add code coverage to phpunit. 2015-03-18 22:24:54 +01:00
James Cole
4b076d227a Touch db so it can be created. 2015-03-18 22:17:18 +01:00
James Cole
3c4e7158a1 Config for test database. 2015-03-18 22:16:00 +01:00
James Cole
0b16765f37 Add sudo: false to enable container based builds. 2015-03-18 21:51:56 +01:00
James Cole
20c2ff3443 Add debug output to phpunit. 2015-03-18 21:43:19 +01:00
James Cole
96f2e598f4 Better position for titles. 2015-03-16 19:03:52 +01:00
James Cole
7374f0f9dd Removed Material Design. 2015-03-16 18:02:52 +01:00
James Cole
ccc44a74a0 Removed debug information. 2015-03-15 19:02:33 +01:00
James Cole
66cd63a68d Fixed a bug. 2015-03-15 18:08:52 +01:00
James Cole
decf7e5485 Set order in title. 2015-03-15 18:02:40 +01:00
James Cole
063c8025aa Allow piggy banks to be ordered. 2015-03-15 18:00:33 +01:00
James Cole
2fa7d2bd56 Add some text alignments. 2015-03-15 14:24:25 +01:00
James Cole
e55e7bce74 Misspelled a class name. 2015-03-15 14:23:26 +01:00
James Cole
f572445a65 Small updates. 2015-03-15 09:34:57 +01:00
James Cole
8b4f656d90 Switched to Google Material design line charts. 2015-03-15 08:38:12 +01:00
James Cole
6c1e093ebd Merge branch 'release/3.3.2' into develop 2015-03-14 22:06:12 +01:00
377 changed files with 18603 additions and 7389 deletions

View File

@@ -1,3 +1,3 @@
src_dir: .
coverage_clover: storage/coverage/clover.xml
json_path: storage/coverage/coveralls-upload.json
json_path: storage/coverage/coveralls-upload.json

View File

@@ -1,5 +1,5 @@
APP_ENV=local
APP_DEBUG=true
APP_ENV=production
APP_DEBUG=false
APP_KEY=SomeRandomString
DB_CONNECTION=mysql
@@ -12,5 +12,7 @@ CACHE_DRIVER=file
SESSION_DRIVER=file
EMAIL_SMTP=
EMAIL_DRIVER=smtp
EMAIL_USERNAME=
EMAIL_PASSWORD=
ANALYTICS_ID=

View File

@@ -8,6 +8,10 @@ DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
CACHE_DRIVER=file
SESSION_DRIVER=file
CACHE_DRIVER=array
SESSION_DRIVER=array
EMAIL_SMTP=
EMAIL_USERNAME=
EMAIL_PASSWORD=
ANALYTICS_ID=ABC

5
.gitignore vendored
View File

@@ -26,3 +26,8 @@ db.sqlite-journal
tests/_output/*
.env
clover.xml
node_modules/
addNewLines.php
.phpstorm.meta.php
.env.backup
.env.local

View File

@@ -1,4 +1,6 @@
language: php
sudo: false
php:
- 5.5
@@ -9,8 +11,7 @@ addons:
repo_token: 26489f9e854fcdf7e7660ba29c1455694685465b1f90329a79f7d2bf448acb61
install:
- rm composer.lock
- composer install
- composer update
- php artisan env
- mv -v .env.testing .env

View File

@@ -1,11 +1,12 @@
Firefly III (v3.3.2)
Firefly III (v3.4.0.2)
===========
[![Build Status](https://travis-ci.org/JC5/firefly-iii.svg?branch=develop)](https://travis-ci.org/JC5/firefly-iii)
[![Project Status](http://stillmaintained.com/JC5/firefly-iii.png?a=b)](http://stillmaintained.com/JC5/firefly-iii)
[![SensioLabsInsight](https://insight.sensiolabs.com/projects/d44c7012-5f50-41ad-add8-8445330e4102/mini.png)](https://insight.sensiolabs.com/projects/d44c7012-5f50-41ad-add8-8445330e4102)
[![Code Climate](https://codeclimate.com/github/JC5/firefly-iii/badges/gpa.svg)](https://codeclimate.com/github/JC5/firefly-iii)
[![Test Coverage](https://codeclimate.com/github/JC5/firefly-iii/badges/coverage.svg)](https://codeclimate.com/github/JC5/firefly-iii)
[![Coverage Status](https://coveralls.io/repos/JC5/firefly-iii/badge.svg?branch=master)](https://coveralls.io/r/JC5/firefly-iii?branch=master)
[![Coverage Status](https://coveralls.io/repos/JC5/firefly-iii/badge.svg?branch=develop)](https://coveralls.io/r/JC5/firefly-iii?branch=develop)
[![Latest Stable Version](https://poser.pugx.org/grumpydictator/firefly-iii/v/stable.svg)](https://packagist.org/packages/grumpydictator/firefly-iii)
[![Total Downloads](https://poser.pugx.org/grumpydictator/firefly-iii/downloads.svg)](https://packagist.org/packages/grumpydictator/firefly-iii)
@@ -18,16 +19,27 @@ Firefly Mark III is a new version of Firefly built upon best practices and lesso
from building [Firefly](https://github.com/JC5/Firefly). It's Mark III since the original Firefly never made it outside of my
laptop and [Firefly II](https://github.com/JC5/Firefly) is live.
If you're not sure if this tool is for you, please read the [full description](https://github.com/JC5/firefly-iii/wiki/full-description).
To install and use Firefly III, please read [the installation guide](https://github.com/JC5/firefly-iii/wiki/Installation),
[the upgrade guide](https://github.com/JC5/firefly-iii/wiki/Upgrade-instructions) (if applicable) and the **[first use guide](https://github.com/JC5/firefly-iii/wiki/First-use)**.
If you want to try out Firefly III, you can do so on [this dedicated website](https://geld.nder.be/). This site always runs the latest version of Firefly III. If you want to use it, please read the [privacy considerations](https://github.com/JC5/firefly-iii/wiki/Privacy-on-demo-site) for this demo-site.
## Current features
- [A double-entry bookkeeping system](http://en.wikipedia.org/wiki/Double-entry_bookkeeping_system);
- [A double-entry bookkeeping system](https://en.wikipedia.org/wiki/Double-entry_bookkeeping_system);
- You can store, edit and remove withdrawals, deposits and transfers. This allows you full financial management;
- It's possible to create, change and manage money using _budgets_;
- You can manage different types of accounts
- Asset accounts
- Shared asset accounts (household accounts)
- Saving accounts
- Credit cards
- It's possible to create, change and manage money using _[budgets](https://en.wikipedia.org/wiki/Envelope_system)_;
- Organize transactions using categories;
- Save towards a goal using piggy banks;
- Predict and anticipate large expenses using "repeated expenses" (ie. yearly taxes);
- Predict and anticipate bills using "recurring transactions" (rent for example);
- View basic income / expense reports.
- Predict and anticipate bills;
- View income / expense reports;
- Lots of help text in case you don't get it;
Everything is organised:
@@ -44,9 +56,7 @@ Firefly III will feature, but does not feature yet:
- More control over other resources outside of personal finance
- Accounts shared with a partner (household accounts)
- Debts
- Credit cards
- More test-coverage;
- Firefly will be able to split transactions; a single purchase can be split in multiple entries, for more fine-grained control.
- Firefly will be able to join transactions.
@@ -55,7 +65,6 @@ Firefly III will feature, but does not feature yet:
Some stuff has been removed:
- The nesting of budgets, categories and beneficiaries is removed because it was pretty pointless.
- Firefly will not encrypt the content of the (MySQL) tables. Old versions of Firefly had this capability but it sucks when searching, sorting and organizing entries.
## Screenshots
@@ -70,7 +79,4 @@ Some stuff has been removed:
## Current state
I have the basics up and running. Test coverage is currently coming, slowly.
Although I have not checked extensively, some forms and views have CSRF vulnerabilities. This is because not all
views escape all characters by default. Will be fixed.
Questions, ideas or other things to contribute? [Let me know](https://github.com/JC5/firefly-iii/issues/new)!

View File

@@ -1,37 +0,0 @@
<?php namespace FireflyIII\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Foundation\Inspiring;
/**
* Class Inspire
*
* @package FireflyIII\Console\Commands
*/
class Inspire extends Command
{
/**
* The console command description.
*
* @var string
*/
protected $description = 'Display an inspiring quote';
/**
* The console command name.
*
* @var string
*/
protected $name = 'inspire';
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$this->comment(PHP_EOL . Inspiring::quote() . PHP_EOL);
}
}

View File

@@ -18,7 +18,6 @@ class Kernel extends ConsoleKernel
*/
protected $commands
= [
'FireflyIII\Console\Commands\Inspire',
];
/**
@@ -30,8 +29,6 @@ class Kernel extends ConsoleKernel
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('inspire')
->hourly();
}
}

View File

@@ -1,31 +1,33 @@
<?php namespace FireflyIII\Events;
use FireflyIII\Events\Event;
use FireflyIII\Models\TransactionJournal;
use Illuminate\Queue\SerializesModels;
class JournalCreated extends Event {
/**
* Class JournalCreated
*
* @package FireflyIII\Events
*/
class JournalCreated extends Event
{
use SerializesModels;
use SerializesModels;
public $journal;
public $piggyBankId;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct(TransactionJournal $journal, $piggyBankId)
{
//
$this->journal = $journal;
/**
* Create a new event instance.
*
* @param TransactionJournal $journal
* @param $piggyBankId
*/
public function __construct(TransactionJournal $journal, $piggyBankId)
{
//
$this->journal = $journal;
$this->piggyBankId = $piggyBankId;
}
}
}

View File

@@ -2,6 +2,11 @@
use Illuminate\Queue\SerializesModels;
/**
* Class JournalDeleted
*
* @package FireflyIII\Events
*/
class JournalDeleted extends Event
{
@@ -10,7 +15,6 @@ class JournalDeleted extends Event
/**
* Create a new event instance.
*
* @return void
*/
public function __construct()
{

View File

@@ -1,25 +1,29 @@
<?php namespace FireflyIII\Events;
use FireflyIII\Events\Event;
use FireflyIII\Models\TransactionJournal;
use Illuminate\Queue\SerializesModels;
class JournalSaved extends Event {
/**
* Class JournalSaved
*
* @package FireflyIII\Events
*/
class JournalSaved extends Event
{
use SerializesModels;
use SerializesModels;
public $journal;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct(TransactionJournal $journal)
{
//
/**
* Create a new event instance.
*
* @param TransactionJournal $journal
*/
public function __construct(TransactionJournal $journal)
{
//
$this->journal = $journal;
}
}
}

View File

@@ -49,8 +49,7 @@ class Handler extends ExceptionHandler
*/
public function report(Exception $e)
{
/** @noinspection PhpInconsistentReturnPointsInspection */
return parent::report($e);
parent::report($e);
}
}

View File

@@ -19,7 +19,6 @@ class ConnectJournalToPiggyBank
/**
* Create the event handler.
*
* @return void
*/
public function __construct()
{
@@ -38,6 +37,9 @@ class ConnectJournalToPiggyBank
/** @var TransactionJournal $journal */
$journal = $event->journal;
$piggyBankId = $event->piggyBankId;
if (intval($piggyBankId) < 1) {
return;
}
Log::debug('JournalCreated event: ' . $journal->id . ', ' . $piggyBankId);
@@ -48,14 +50,7 @@ class ConnectJournalToPiggyBank
return;
}
Log::debug('Found a piggy bank');
$amount = 0;
/** @var Transaction $transaction */
foreach ($journal->transactions()->get() as $transaction) {
if ($transaction->account_id === $piggyBank->account_id) {
// this transaction is the relevant one.
$amount = floatval($transaction->amount);
}
}
$amount = $journal->amount;
Log::debug('Amount: ' . $amount);
if ($amount == 0) {
return;
@@ -63,10 +58,28 @@ class ConnectJournalToPiggyBank
// update piggy bank rep for date of transaction journal.
$repetition = $piggyBank->piggyBankRepetitions()->relevantOnDate($journal->date)->first();
if (is_null($repetition)) {
Log::debug('Found no repetition for piggy bank for date ' . $journal->date->format('Y M d'));
return;
}
Log::debug('Found rep! ' . $repetition->id);
/*
* Add amount when
*/
/** @var Transaction $transaction */
foreach ($journal->transactions()->get() as $transaction) {
if ($transaction->account_id == $piggyBank->account_id) {
if ($transaction->amount < 0) {
$amount = $amount * -1;
Log::debug('Transaction is away from piggy, so amount becomes ' . $amount);
} else {
Log::debug('Transaction is to from piggy, so amount stays ' . $amount);
}
}
}
$repetition->currentamount += $amount;
$repetition->save();

View File

@@ -1,16 +1,18 @@
<?php namespace FireflyIII\Handlers\Events;
use FireflyIII\Events\JournalDeleted;
use Illuminate\Contracts\Queue\ShouldBeQueued;
use Illuminate\Queue\InteractsWithQueue;
/**
* Class JournalDeletedHandler
*
* @package FireflyIII\Handlers\Events
*/
class JournalDeletedHandler
{
/**
* Create the event handler.
*
* @return void
*/
public function __construct()
{

View File

@@ -1,8 +1,8 @@
<?php namespace FireflyIII\Handlers\Events;
use App;
use FireflyIII\Events\JournalSaved;
use Log;
use App;
/**
* Class RescanJournal
@@ -15,7 +15,6 @@ class RescanJournal
/**
* Create the event handler.
*
* @return void
*/
public function __construct()
{
@@ -41,7 +40,7 @@ class RescanJournal
Log::debug('Found ' . $list->count() . ' bills to check.');
/** @var Bill $bill */
/** @var \FireflyIII\Models\Bill $bill */
foreach ($list as $bill) {
Log::debug('Now calling bill #' . $bill->id . ' (' . $bill->name . ')');
$repository->scan($bill, $journal);

View File

@@ -2,16 +2,18 @@
use FireflyIII\Events\JournalSaved;
use FireflyIII\Models\PiggyBankEvent;
use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionJournal;
/**
* Class UpdateJournalConnection
*
* @package FireflyIII\Handlers\Events
*/
class UpdateJournalConnection
{
/**
* Create the event handler.
*
* @return void
*/
public function __construct()
{
@@ -31,8 +33,8 @@ class UpdateJournalConnection
// get the event connected to this journal:
/** @var PiggyBankEvent $event */
$event = PiggyBankEvent::where('transaction_journal_id', $journal->id)->first();
if(is_null($event)) {
$event = PiggyBankEvent::where('transaction_journal_id', $journal->id)->first();
if (is_null($event)) {
return;
}
$piggyBank = $event->piggyBank()->first();
@@ -41,17 +43,8 @@ class UpdateJournalConnection
if (is_null($repetition)) {
return;
}
$amount = 0;
/** @var Transaction $transaction */
foreach ($journal->transactions()->get() as $transaction) {
if ($transaction->account_id === $piggyBank->account_id) {
// this transaction is the relevant one.
$amount = floatval($transaction->amount);
}
}
// update current repetition:
$diff = $amount - $event->amount;
$amount = $journal->amount;
$diff = $amount - $event->amount;// update current repetition
$repetition->currentamount += $diff;
$repetition->save();

87
app/Helpers/Help/Help.php Normal file
View File

@@ -0,0 +1,87 @@
<?php
namespace FireflyIII\Helpers\Help;
use Cache;
use ErrorException;
use League\CommonMark\CommonMarkConverter;
use Log;
use Route;
/**
* Class Help
*
* @package FireflyIII\Helpers\Help
*/
class Help implements HelpInterface
{
/**
* @param $key
*
* @return string
*/
public function getFromCache($key)
{
return Cache::get($key);
}
/**
* @param $route
*
* @return array
*/
public function getFromGithub($route)
{
$uri = 'https://raw.githubusercontent.com/JC5/firefly-iii-help/master/' . e($route) . '.md';
$content = [
'text' => '<p>There is no help for this route!</p>',
'title' => $route,
];
try {
$content['text'] = file_get_contents($uri);
} catch (ErrorException $e) {
Log::error(trim($e->getMessage()));
}
if (strlen(trim($content['text'])) == 0) {
$content['text'] = '<p>There is no help for this route.</p>';
}
$converter = new CommonMarkConverter();
$content['text'] = $converter->convertToHtml($content['text']);
return $content;
}
/**
* @param $route
*
* @return bool
*/
public function hasRoute($route)
{
return Route::has($route);
}
/**
* @param $route
* @param array $content
*
* @internal param $title
*/
public function putInCache($route, array $content)
{
Cache::put('help.' . $route . '.text', $content['text'], 10080); // a week.
Cache::put('help.' . $route . '.title', $content['title'], 10080);
}
/**
* @param $route
*
* @return bool
*/
public function inCache($route)
{
return Cache::has('help.' . $route . '.title') && Cache::has('help.' . $route . '.text');
}
}

View File

@@ -0,0 +1,48 @@
<?php
namespace FireflyIII\Helpers\Help;
/**
* Interface HelpInterface
*
* @package FireflyIII\Helpers\Help
*/
interface HelpInterface
{
/**
* @param $key
*
* @return string
*/
public function getFromCache($key);
/**
* @param $route
*
* @return array
*/
public function getFromGithub($route);
/**
* @param $route
*
* @return bool
*/
public function hasRoute($route);
/**
* @param $route
*
* @return bool
*/
public function inCache($route);
/**
* @param $route
* @param array $content
*
* @return void
*/
public function putInCache($route, array $content);
}

View File

@@ -25,10 +25,7 @@ class ReminderHelper implements ReminderHelperInterface
*/
public function createReminder(PiggyBank $piggyBank, Carbon $start, Carbon $end)
{
$reminder = Auth::user()->reminders()
->where('remindersable_id', $piggyBank->id)
->onDates($start, $end)
->first();
$reminder = Auth::user()->reminders()->where('remindersable_id', $piggyBank->id)->onDates($start, $end)->first();
if (is_null($reminder)) {
if (!is_null($piggyBank->targetdate)) {
@@ -98,7 +95,6 @@ class ReminderHelper implements ReminderHelperInterface
if (!is_null($piggyBank->targetdate)) {
// count back until now.
// echo 'Count back!<br>';
$start = $piggyBank->targetdate;
$end = $piggyBank->startdate;
@@ -134,7 +130,8 @@ class ReminderHelper implements ReminderHelperInterface
{
/** @var PiggyBank $piggyBank */
$piggyBank = $reminder->remindersable;
if(is_null($piggyBank)) {
if (is_null($piggyBank)) {
return 'Piggy bank no longer exists.';
}
@@ -145,4 +142,4 @@ class ReminderHelper implements ReminderHelperInterface
return 'Add ' . Amount::format($reminder->metadata->perReminder) . ' to fill this piggy bank on ' . $piggyBank->targetdate->format('jS F Y');
}
}
}

View File

@@ -2,16 +2,17 @@
namespace FireflyIII\Helpers\Reminders;
use FireflyIII\Models\Reminder;
use FireflyIII\Models\PiggyBank;
use Carbon\Carbon;
use FireflyIII\Models\PiggyBank;
use FireflyIII\Models\Reminder;
/**
* Interface ReminderHelperInterface
*
* @package FireflyIII\Helpers\Reminders
*/
interface ReminderHelperInterface {
interface ReminderHelperInterface
{
/**
* Takes a reminder, finds the piggy bank and tells you what to do now.
* Aka how much money to put in.
@@ -48,4 +49,4 @@ interface ReminderHelperInterface {
* @return Reminder
*/
public function createReminder(PiggyBank $piggyBank, Carbon $start, Carbon $end);
}
}

View File

@@ -2,6 +2,7 @@
namespace FireflyIII\Helpers\Report;
use App;
use Auth;
use Carbon\Carbon;
use FireflyIII\Models\Account;
@@ -40,40 +41,43 @@ class ReportHelper implements ReportHelperInterface
* This method gets some kind of list for a monthly overview.
*
* @param Carbon $date
* @param bool $showSharedReports
*
* @return Collection
*/
public function getBudgetsForMonth(Carbon $date)
public function getBudgetsForMonth(Carbon $date, $showSharedReports = false)
{
/** @var \FireflyIII\Helpers\Report\ReportQueryInterface $query */
$query = App::make('FireflyIII\Helpers\Report\ReportQueryInterface');
$start = clone $date;
$start->startOfMonth();
$end = clone $date;
$end->endOfMonth();
// all budgets
$set = Auth::user()->budgets()
->leftJoin(
'budget_limits', function (JoinClause $join) use ($date) {
$join->on('budget_limits.budget_id', '=', 'budgets.id')->where('budget_limits.startdate', '=', $date->format('Y-m-d'));
}
)
->get(['budgets.*', 'budget_limits.amount as amount']);
$set = Auth::user()->budgets()->orderBy('budgets.name', 'ASC')
->leftJoin(
'budget_limits', function (JoinClause $join) use ($date) {
$join->on('budget_limits.budget_id', '=', 'budgets.id')->where('budget_limits.startdate', '=', $date->format('Y-m-d'));
}
)
->get(['budgets.*', 'budget_limits.amount as queryAmount']);
$budgets = Steam::makeArray($set);
$amountSet = $query->journalsByBudget($start, $end, $showSharedReports);
$amounts = Steam::makeArray($amountSet);
$budgets = Steam::mergeArrays($budgets, $amounts);
$budgets[0]['spent'] = isset($budgets[0]['spent']) ? $budgets[0]['spent'] : 0.0;
$budgets[0]['queryAmount'] = isset($budgets[0]['queryAmount']) ? $budgets[0]['queryAmount'] : 0.0;
$budgets[0]['name'] = 'No budget';
$budgets = $this->_helper->makeArray($set);
$amountSet = $this->_queries->journalsByBudget($start, $end);
$amounts = $this->_helper->makeArray($amountSet);
$combined = $this->_helper->mergeArrays($budgets, $amounts);
$combined[0]['spent'] = isset($combined[0]['spent']) ? $combined[0]['spent'] : 0.0;
$combined[0]['amount'] = isset($combined[0]['amount']) ? $combined[0]['amount'] : 0.0;
$combined[0]['name'] = 'No budget';
// find transactions to shared expense accounts, which are without a budget by default:
$transfers = $this->_queries->sharedExpenses($start, $end);
foreach ($transfers as $transfer) {
$combined[0]['spent'] += floatval($transfer->amount) * -1;
// find transactions to shared asset accounts, which are without a budget by default:
// which is only relevant when shared asset accounts are hidden.
if ($showSharedReports === false) {
$transfers = $query->sharedExpenses($start, $end)->sum('queryAmount');
$budgets[0]['spent'] += floatval($transfers) * -1;
}
return $combined;
return $budgets;
}
/**
@@ -87,11 +91,11 @@ class ReportHelper implements ReportHelperInterface
$end = Carbon::now();
$months = [];
while ($start <= $end) {
$year = $start->format('Y');
$year = $start->year;
$months[$year][] = [
'formatted' => $start->format('F Y'),
'month' => intval($start->format('m')),
'year' => intval($start->format('Y')),
'month' => $start->month,
'year' => $year,
];
$start->addMonth();
}
@@ -110,9 +114,12 @@ class ReportHelper implements ReportHelperInterface
$end = Carbon::now();
$years = [];
while ($start <= $end) {
$years[] = $start->format('Y');
$years[] = $start->year;
$start->addYear();
}
$years[] = Carbon::now()->year;
// force the current year.
$years = array_unique($years);
return $years;
}
@@ -141,23 +148,26 @@ class ReportHelper implements ReportHelperInterface
}
$accounts = Auth::user()->accounts()->accountTypeIn(['Default account', 'Asset account'])->orderBy('accounts.name', 'ASC')->get(['accounts.*'])
->filter(
function (Account $account) use ($sharedAccounts) {
if (!in_array($account->id, $sharedAccounts)) {
return $account;
}
->filter(
function (Account $account) use ($sharedAccounts) {
if (!in_array($account->id, $sharedAccounts)) {
return $account;
}
return null;
}
);
return null;
}
);
$report = [];
$start->startOfYear()->subDay();
$end->endOfYear();
foreach ($accounts as $account) {
$report[] = [
'start' => Steam::balance($account, $start),
'end' => Steam::balance($account, $end),
$startBalance = Steam::balance($account, $start);
$endBalance = Steam::balance($account, $end);
$report[] = [
'start' => $startBalance,
'end' => $endBalance,
'hide' => ($startBalance == 0 && $endBalance == 0),
'account' => $account,
'shared' => $account->accountRole == 'sharedAsset'
];
@@ -165,4 +175,4 @@ class ReportHelper implements ReportHelperInterface
return $report;
}
}
}

View File

@@ -55,4 +55,4 @@ interface ReportHelperInterface
* @return array
*/
public function yearBalanceReport(Carbon $date, $showSharedReports = false);
}
}

View File

@@ -4,10 +4,12 @@ namespace FireflyIII\Helpers\Report;
use Auth;
use Carbon\Carbon;
use Crypt;
use DB;
use FireflyIII\Models\Account;
use FireflyIII\Models\TransactionJournal;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Query\JoinClause;
use Illuminate\Support\Collection;
use Steam;
@@ -87,11 +89,14 @@ class ReportQuery implements ReportQueryInterface
->whereNull('budget_transaction_journal.budget_id')->whereNull('transaction_journals.deleted_at')
->whereNull('otherJournals.deleted_at')
->where('transactions.account_id', $account->id)
->orderBy('transaction_journals.date', 'DESC')
->orderBy('transaction_journals.order', 'ASC')
->orderBy('transaction_journals.id', 'DESC')
->whereNotNull('transaction_group_transaction_journal.transaction_group_id')
->get(
[
'transaction_journals.*',
'transactions.amount'
'transactions.amount as queryAmount'
]
);
@@ -106,17 +111,11 @@ class ReportQuery implements ReportQueryInterface
* @param Carbon $start
* @param Carbon $end
*
* @return Collection
* @return float
*/
public function balancedTransactionsSum(Account $account, Carbon $start, Carbon $end)
{
$set = $this->balancedTransactionsList($account, $start, $end);
$sum = 0;
foreach ($set as $entry) {
$sum += floatval($entry->amount);
}
return $sum;
return floatval($this->balancedTransactionsList($account, $start, $end)->sum('queryAmount'));
}
/**
@@ -140,7 +139,7 @@ class ReportQuery implements ReportQueryInterface
)
->orderBy('accounts.name', 'ASC')
->where(
function (Builder $query) use ($showSharedReports) {
function (Builder $query) {
$query->where('account_meta.data', '!=', '"sharedAsset"');
$query->orWhereNull('account_meta.data');
@@ -151,8 +150,16 @@ class ReportQuery implements ReportQueryInterface
$set = $query->get(['accounts.*']);
$set->each(
function (Account $account) use ($start, $end) {
/**
* The balance for today always incorporates transactions
* made on today. So to get todays "start" balance, we sub one
* day.
*/
$yesterday = clone $start;
$yesterday->subDay();
/** @noinspection PhpParamsInspection */
$account->startBalance = Steam::balance($account, $start);
$account->startBalance = Steam::balance($account, $yesterday);
$account->endBalance = Steam::balance($account, $end);
}
);
@@ -171,26 +178,9 @@ class ReportQuery implements ReportQueryInterface
*/
public function getBudgetSummary(Account $account, Carbon $start, Carbon $end)
{
$set = TransactionJournal::
leftJoin('budget_transaction_journal', 'budget_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id')
->leftJoin('budgets', 'budgets.id', '=', 'budget_transaction_journal.budget_id')
->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id')
->leftJoin(
'transactions', function (JoinClause $join) {
$join->on('transactions.transaction_journal_id', '=', 'transaction_journals.id')->where('transactions.amount', '<', 0);
}
)
->leftJoin('accounts', 'accounts.id', '=', 'transactions.account_id')
->before($end)
->after($start)
->where('accounts.id', $account->id)
->where('transaction_journals.user_id', Auth::user()->id)
->where('transaction_types.type', 'Withdrawal')
->groupBy('budgets.id')
->orderBy('budgets.name', 'ASC')
->get(['budgets.id', 'budgets.name', DB::Raw('SUM(`transactions`.`amount`) as `amount`')]);
$query = $this->queryJournalsNoBudget($account, $start, $end);
return $set;
return $query->get(['budgets.id', 'budgets.name', DB::Raw('SUM(`transactions`.`amount`) as `queryAmount`')]);
}
@@ -206,26 +196,9 @@ class ReportQuery implements ReportQueryInterface
*/
public function getTransactionsWithoutBudget(Account $account, Carbon $start, Carbon $end)
{
$set = TransactionJournal::
leftJoin('budget_transaction_journal', 'budget_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id')
->leftJoin('budgets', 'budgets.id', '=', 'budget_transaction_journal.budget_id')
->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id')
->leftJoin(
'transactions', function (JoinClause $join) {
$join->on('transactions.transaction_journal_id', '=', 'transaction_journals.id')->where('transactions.amount', '<', 0);
}
)
->leftJoin('accounts', 'accounts.id', '=', 'transactions.account_id')
->before($end)
->after($start)
->where('accounts.id', $account->id)
->where('transaction_journals.user_id', Auth::user()->id)
->where('transaction_types.type', 'Withdrawal')
->whereNull('budgets.id')
->orderBy('transaction_journals.date', 'ASC')
->get(['budgets.name', 'transactions.amount', 'transaction_journals.*']);
$query = $this->queryJournalsNoBudget($account, $start, $end);
return $set;
return $query->get(['budgets.name', 'transactions.amount as queryAmount', 'transaction_journals.*']);
}
/**
@@ -241,43 +214,20 @@ class ReportQuery implements ReportQueryInterface
*/
public function incomeByPeriod(Carbon $start, Carbon $end, $showSharedReports = false)
{
$query = TransactionJournal::
leftJoin(
'transactions as t_from', function (JoinClause $join) {
$join->on('t_from.transaction_journal_id', '=', 'transaction_journals.id')->where('t_from.amount', '<', 0);
}
)
->leftJoin('accounts as ac_from', 't_from.account_id', '=', 'ac_from.id')
->leftJoin(
'account_meta as acm_from', function (JoinClause $join) {
$join->on('ac_from.id', '=', 'acm_from.account_id')->where('acm_from.name', '=', 'accountRole');
}
)
->leftJoin(
'transactions as t_to', function (JoinClause $join) {
$join->on('t_to.transaction_journal_id', '=', 'transaction_journals.id')->where('t_to.amount', '>', 0);
}
)
->leftJoin('accounts as ac_to', 't_to.account_id', '=', 'ac_to.id')
->leftJoin(
'account_meta as acm_to', function (JoinClause $join) {
$join->on('ac_to.id', '=', 'acm_to.account_id')->where('acm_to.name', '=', 'accountRole');
}
)
->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id');
$query = $this->queryJournalsWithTransactions($start, $end);
if ($showSharedReports === false) {
// only get deposits not to a shared account
// and transfers to a shared account.
$query->where(
function ($query) {
function (Builder $query) {
$query->where(
function ($q) {
function (Builder $q) {
$q->where('transaction_types.type', 'Deposit');
$q->where('acm_to.data', '!=', '"sharedAsset"');
}
);
$query->orWhere(
function ($q) {
function (Builder $q) {
$q->where('transaction_types.type', 'Transfer');
$q->where('acm_from.data', '=', '"sharedAsset"');
}
@@ -288,20 +238,29 @@ class ReportQuery implements ReportQueryInterface
// any deposit is fine.
$query->where('transaction_types.type', 'Deposit');
}
$query->before($end)->after($start)
->where('transaction_journals.user_id', Auth::user()->id)
->groupBy('t_from.account_id')->orderBy('transaction_journals.date');
$query->groupBy('transaction_journals.id')->orderBy('transaction_journals.date');
return $query->get(
// get everything, decrypt and return
$data = $query->get(
['transaction_journals.id',
'transaction_journals.description',
'transaction_journals.encrypted',
'transaction_types.type',
DB::Raw('SUM(`t_to`.`amount`) as `amount`'),
DB::Raw('SUM(`t_to`.`amount`) as `queryAmount`'),
'transaction_journals.date',
't_from.account_id as account_id',
'ac_from.name as name']
'ac_from.name as name',
'ac_from.encrypted as account_encrypted'
]
);
$data->each(
function (Model $object) {
$object->name = intval($object->account_encrypted) == 1 ? Crypt::decrypt($object->name) : $object->name;
}
);
return $data;
}
/**
@@ -377,9 +336,17 @@ class ReportQuery implements ReportQueryInterface
->where('transaction_journals.date', '<=', $end->format('Y-m-d'))
->where('transaction_types.type', 'Withdrawal')
->groupBy('categories.id')
->orderBy('amount');
->orderBy('queryAmount');
return $query->get(['categories.id', 'categories.name', DB::Raw('SUM(`transactions`.`amount`) AS `amount`')]);
$data = $query->get(['categories.id', 'categories.encrypted', 'categories.name', DB::Raw('SUM(`transactions`.`amount`) AS `queryAmount`')]);
// decrypt data:
$data->each(
function (Model $object) {
$object->name = intval($object->encrypted) == 1 ? Crypt::decrypt($object->name) : $object->name;
}
);
return $data;
}
@@ -397,42 +364,20 @@ class ReportQuery implements ReportQueryInterface
*/
public function journalsByExpenseAccount(Carbon $start, Carbon $end, $showSharedReports = false)
{
$query = TransactionJournal::leftJoin(
'transactions as t_from', function (JoinClause $join) {
$join->on('t_from.transaction_journal_id', '=', 'transaction_journals.id')->where('t_from.amount', '<', 0);
}
)->leftJoin('accounts as ac_from', 't_from.account_id', '=', 'ac_from.id')
->leftJoin(
'account_meta as acm_from', function (JoinClause $join) {
$join->on('ac_from.id', '=', 'acm_from.account_id')->where('acm_from.name', '=', 'accountRole');
}
)
->leftJoin(
'transactions as t_to', function (JoinClause $join) {
$join->on('t_to.transaction_journal_id', '=', 'transaction_journals.id')->where('t_to.amount', '>', 0);
}
)
->leftJoin('accounts as ac_to', 't_to.account_id', '=', 'ac_to.id')
->leftJoin(
'account_meta as acm_to', function (JoinClause $join) {
$join->on('ac_to.id', '=', 'acm_to.account_id')->where('acm_to.name', '=', 'accountRole');
}
)
->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id');
$query = $this->queryJournalsWithTransactions($start, $end);
if ($showSharedReports === false) {
// get all withdrawals not from a shared accounts
// and all transfers to a shared account
$query->where(
function ($query) {
function (Builder $query) {
$query->where(
function ($q) {
function (Builder $q) {
$q->where('transaction_types.type', 'Withdrawal');
$q->where('acm_from.data', '!=', '"sharedAsset"');
}
);
$query->orWhere(
function ($q) {
function (Builder $q) {
$q->where('transaction_types.type', 'Transfer');
$q->where('acm_to.data', '=', '"sharedAsset"');
}
@@ -443,13 +388,21 @@ class ReportQuery implements ReportQueryInterface
// any withdrawal goes:
$query->where('transaction_types.type', 'Withdrawal');
}
$query->before($end)
->after($start)
$query->before($end)->after($start)
->where('transaction_journals.user_id', Auth::user()->id)
->groupBy('t_to.account_id')
->orderBy('amount', 'DESC');
->orderBy('queryAmount', 'DESC');
return $query->get(['t_to.account_id as id', 'ac_to.name as name', DB::Raw('SUM(t_to.amount) as `amount`')]);
$data = $query->get(['t_to.account_id as id', 'ac_to.name as name', 'ac_to.encrypted', DB::Raw('SUM(t_to.amount) as `queryAmount`')]);
// decrypt
$data->each(
function (Model $object) {
$object->name = intval($object->encrypted) == 1 ? Crypt::decrypt($object->name) : $object->name;
}
);
return $data;
}
/**
@@ -463,44 +416,21 @@ class ReportQuery implements ReportQueryInterface
*/
public function journalsByRevenueAccount(Carbon $start, Carbon $end, $showSharedReports = false)
{
$query = TransactionJournal::
leftJoin(
'transactions as t_from', function (JoinClause $join) {
$join->on('t_from.transaction_journal_id', '=', 'transaction_journals.id')->where('t_from.amount', '<', 0);
}
)
->leftJoin('accounts as ac_from', 't_from.account_id', '=', 'ac_from.id')
->leftJoin(
'account_meta as acm_from', function (JoinClause $join) {
$join->on('ac_from.id', '=', 'acm_from.account_id')->where('acm_from.name', '=', 'accountRole');
}
)
->leftJoin(
'transactions as t_to', function (JoinClause $join) {
$join->on('t_to.transaction_journal_id', '=', 'transaction_journals.id')->where('t_to.amount', '>', 0);
}
)
->leftJoin('accounts as ac_to', 't_to.account_id', '=', 'ac_to.id')
->leftJoin(
'account_meta as acm_to', function (JoinClause $join) {
$join->on('ac_to.id', '=', 'acm_to.account_id')->where('acm_to.name', '=', 'accountRole');
}
)
->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id');
$query = $this->queryJournalsWithTransactions($start, $end);
if ($showSharedReports === false) {
// show queries where transfer type is deposit, and its not to a shared account
// or where its a transfer and its from a shared account (both count as incomes)
$query->where(
function ($query) {
function (Builder $query) {
$query->where(
function ($q) {
function (Builder $q) {
$q->where('transaction_types.type', 'Deposit');
$q->where('acm_to.data', '!=', '"sharedAsset"');
}
);
$query->orWhere(
function ($q) {
function (Builder $q) {
$q->where('transaction_types.type', 'Transfer');
$q->where('acm_from.data', '=', '"sharedAsset"');
}
@@ -511,11 +441,20 @@ class ReportQuery implements ReportQueryInterface
// any deposit goes:
$query->where('transaction_types.type', 'Deposit');
}
$query->before($end)->after($start)
->where('transaction_journals.user_id', Auth::user()->id)
->groupBy('t_from.account_id')->orderBy('amount');
return $query->get(['t_from.account_id as account_id', 'ac_from.name as name', DB::Raw('SUM(t_from.amount) as `amount`')]);
$query->groupBy('t_from.account_id')->orderBy('queryAmount');
$data = $query->get(
['t_from.account_id as account_id', 'ac_from.name as name', 'ac_from.encrypted as encrypted', DB::Raw('SUM(t_from.amount) as `queryAmount`')]
);
// decrypt
$data->each(
function (Model $object) {
$object->name = intval($object->encrypted) == 1 ? Crypt::decrypt($object->name) : $object->name;
}
);
return $data;
}
/**
@@ -551,7 +490,7 @@ class ReportQuery implements ReportQueryInterface
->where('transaction_journals.user_id', Auth::user()->id)
->get(
['transaction_journals.id', 'transaction_journals.description', 'transactions.account_id', 'accounts.name',
'transactions.amount']
'transactions.amount as queryAmount']
);
}
@@ -596,9 +535,79 @@ class ReportQuery implements ReportQueryInterface
[
'categories.id',
'categories.name as name',
DB::Raw('SUM(`transactions`.`amount`) * -1 AS `amount`')
DB::Raw('SUM(`transactions`.`amount`) * -1 AS `queryAmount`')
]
);
}
}
/**
*
* This query will get all transaction journals and budget information for a specified account
* in a certain date range, where the transaction journal does not have a budget.
* There is no get() specified, this is up to the method itself.
*
* @param Account $account
* @param Carbon $start
* @param Carbon $end
*
* @return Builder
*/
protected function queryJournalsNoBudget(Account $account, Carbon $start, Carbon $end)
{
return TransactionJournal::
leftJoin('budget_transaction_journal', 'budget_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id')
->leftJoin('budgets', 'budgets.id', '=', 'budget_transaction_journal.budget_id')
->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id')
->leftJoin(
'transactions', function (JoinClause $join) {
$join->on('transactions.transaction_journal_id', '=', 'transaction_journals.id')->where('transactions.amount', '<', 0);
}
)
->leftJoin('accounts', 'accounts.id', '=', 'transactions.account_id')
->before($end)
->after($start)
->where('accounts.id', $account->id)
->where('transaction_journals.user_id', Auth::user()->id)
->where('transaction_types.type', 'Withdrawal')
->groupBy('budgets.id')
->orderBy('budgets.name', 'ASC');
}
/**
* @param Carbon $start
* @param Carbon $end
*
* @return Builder
*/
protected function queryJournalsWithTransactions(Carbon $start, Carbon $end)
{
$query = TransactionJournal::
leftJoin(
'transactions as t_from', function (JoinClause $join) {
$join->on('t_from.transaction_journal_id', '=', 'transaction_journals.id')->where('t_from.amount', '<', 0);
}
)
->leftJoin('accounts as ac_from', 't_from.account_id', '=', 'ac_from.id')
->leftJoin(
'account_meta as acm_from', function (JoinClause $join) {
$join->on('ac_from.id', '=', 'acm_from.account_id')->where('acm_from.name', '=', 'accountRole');
}
)
->leftJoin(
'transactions as t_to', function (JoinClause $join) {
$join->on('t_to.transaction_journal_id', '=', 'transaction_journals.id')->where('t_to.amount', '>', 0);
}
)
->leftJoin('accounts as ac_to', 't_to.account_id', '=', 'ac_to.id')
->leftJoin(
'account_meta as acm_to', function (JoinClause $join) {
$join->on('ac_to.id', '=', 'acm_to.account_id')->where('acm_to.name', '=', 'accountRole');
}
)
->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id');
$query->before($end)->after($start)->where('transaction_journals.user_id', Auth::user()->id);
return $query;
}
}

View File

@@ -43,7 +43,7 @@ interface ReportQueryInterface
* @param Carbon $start
* @param Carbon $end
*
* @return Collection
* @return float
*/
public function balancedTransactionsSum(Account $account, Carbon $start, Carbon $end);
@@ -163,4 +163,4 @@ interface ReportQueryInterface
* @return Collection
*/
public function sharedExpensesByCategory(Carbon $start, Carbon $end);
}
}

View File

@@ -7,11 +7,11 @@ use FireflyIII\Http\Requests;
use FireflyIII\Http\Requests\AccountFormRequest;
use FireflyIII\Models\Account;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use Illuminate\Pagination\LengthAwarePaginator;
use Input;
use Redirect;
use Session;
use Steam;
use URL;
use View;
/**
@@ -26,6 +26,7 @@ class AccountController extends Controller
*/
public function __construct()
{
parent::__construct();
View::share('mainTitleIcon', 'fa-credit-card');
View::share('title', 'Accounts');
}
@@ -37,9 +38,15 @@ class AccountController extends Controller
*/
public function create($what = 'asset')
{
$subTitleIcon = Config::get('firefly.subTitlesByIdentifier.' . $what);
$subTitleIcon = Config::get('firefly.subIconsByIdentifier.' . $what);
$subTitle = 'Create a new ' . e($what) . ' account';
// put previous url in session if not redirect from store (not "create another").
if (Session::get('accounts.create.fromStore') !== true) {
Session::put('accounts.create.url', URL::previous());
}
Session::forget('accounts.create.fromStore');
return view('accounts.create', compact('subTitleIcon', 'what', 'subTitle'));
}
@@ -53,15 +60,19 @@ class AccountController extends Controller
{
$subTitle = 'Delete ' . strtolower(e($account->accountType->type)) . ' "' . e($account->name) . '"';
// put previous url in session
Session::put('accounts.delete.url', URL::previous());
return view('accounts.delete', compact('account', 'subTitle'));
}
/**
* @param Account $account
* @param AccountRepositoryInterface $repository
* @param Account $account
*
* @return \Illuminate\Http\RedirectResponse
*/
public function destroy(Account $account, AccountRepositoryInterface $repository)
public function destroy(AccountRepositoryInterface $repository, Account $account)
{
$type = $account->accountType->type;
@@ -72,35 +83,46 @@ class AccountController extends Controller
Session::flash('success', 'The ' . e($typeName) . ' account "' . e($name) . '" was deleted.');
return Redirect::route('accounts.index', $typeName);
return Redirect::to(Session::get('accounts.delete.url'));
}
/**
* @param Account $account
* @param AccountRepositoryInterface $repository
* @param Account $account
*
* @return View
*/
public function edit(Account $account, AccountRepositoryInterface $repository)
public function edit(AccountRepositoryInterface $repository, Account $account)
{
$what = Config::get('firefly.shortNamesByFullName')[$account->accountType->type];
$subTitle = 'Edit ' . strtolower(e($account->accountType->type)) . ' "' . e($account->name) . '"';
$subTitleIcon = Config::get('firefly.subIconsByIdentifier.' . $what);
$openingBalance = $repository->openingBalanceTransaction($account);
// put previous url in session if not redirect from store (not "return_to_edit").
if (Session::get('accounts.edit.fromUpdate') !== true) {
Session::put('accounts.edit.url', URL::previous());
}
Session::forget('accounts.edit.fromUpdate');
// pre fill some useful values.
// the opening balance is tricky:
$openingBalanceAmount = null;
if ($openingBalance) {
$transaction = $openingBalance->transactions()->where('account_id', $account->id)->first();
$transaction = $repository->getFirstTransaction($openingBalance, $account);
$openingBalanceAmount = $transaction->amount;
}
$preFilled = [
'accountRole' => $account->getMeta('accountRole'),
'openingBalanceDate' => $openingBalance ? $openingBalance->date->format('Y-m-d') : null,
'openingBalance' => $openingBalanceAmount
'accountRole' => $account->getMeta('accountRole'),
'ccType' => $account->getMeta('ccType'),
'ccMonthlyPaymentDate' => $account->getMeta('ccMonthlyPaymentDate'),
'openingBalanceDate' => $openingBalance ? $openingBalance->date->format('Y-m-d') : null,
'openingBalance' => $openingBalanceAmount,
'virtualBalance' => floatval($account->virtual_balance)
];
Session::flash('preFilled', $preFilled);
@@ -108,66 +130,49 @@ class AccountController extends Controller
}
/**
* @param string $what
* @param AccountRepositoryInterface $repository
* @param $what
*
* @return View
*/
public function index($what = 'default')
public function index(AccountRepositoryInterface $repository, $what)
{
$subTitle = Config::get('firefly.subTitlesByIdentifier.' . $what);
$subTitleIcon = Config::get('firefly.subIconsByIdentifier.' . $what);
$types = Config::get('firefly.accountTypesByIdentifier.' . $what);
$size = 50;
$page = intval(Input::get('page')) == 0 ? 1 : intval(Input::get('page'));
$offset = ($page - 1) * $size;
// move to repository:
$set = Auth::user()->accounts()->with(
['accountmeta' => function ($query) {
$query->where('name', 'accountRole');
}]
)->accountTypeIn($types)->take($size)->offset($offset)->orderBy('accounts.name', 'ASC')->get(['accounts.*']);
$total = Auth::user()->accounts()->accountTypeIn($types)->count();
$accounts = $repository->getAccounts($types);
// last activity:
$start = clone Session::get('start');
/**
* HERE WE ARE
*/
$start = clone Session::get('start', Carbon::now()->startOfMonth());
$start->subDay();
$set->each(
function (Account $account) use ($start) {
$lastTransaction = $account->transactions()->leftJoin(
'transaction_journals', 'transactions.transaction_journal_id', '=', 'transaction_journals.id'
)->orderBy('transaction_journals.date', 'DESC')->first(['transactions.*', 'transaction_journals.date']);
if ($lastTransaction) {
$account->lastActivityDate = $lastTransaction->transactionjournal->date;
} else {
$account->lastActivityDate = null;
}
$account->startBalance = Steam::balance($account, $start);
$account->endBalance = Steam::balance($account, Session::get('end'));
$accounts->each(
function (Account $account) use ($start, $repository) {
$account->lastActivityDate = $repository->getLastActivity($account);
$account->startBalance = Steam::balance($account, $start);
$account->endBalance = Steam::balance($account, clone Session::get('end', Carbon::now()->endOfMonth()));
}
);
$accounts = new LengthAwarePaginator($set, $total, $size, $page);
$accounts->setPath(route('accounts.index', $what));
return view('accounts.index', compact('what', 'subTitleIcon', 'subTitle', 'accounts'));
}
/**
* @param Account $account
* @param AccountRepositoryInterface $repository
* @param Account $account
*
* @return View
*/
public function show(Account $account, AccountRepositoryInterface $repository)
public function show(AccountRepositoryInterface $repository, Account $account)
{
$page = intval(Input::get('page')) == 0 ? 1 : intval(Input::get('page'));
$subTitleIcon = Config::get('firefly.subTitlesByIdentifier.' . $account->accountType->type);
$what = Config::get('firefly.shortNamesByFullName.' . $account->accountType->type);
$journals = $repository->getJournals($account, $page);
$subTitle = 'Details for ' . strtolower(e($account->accountType->type)) . ' "' . e($account->name) . '"';
$journals->setPath('accounts/show/' . $account->id);
return view('accounts.show', compact('account', 'what', 'subTitleIcon', 'journals', 'subTitle'));
}
@@ -183,6 +188,7 @@ class AccountController extends Controller
$accountData = [
'name' => $request->input('name'),
'accountType' => $request->input('what'),
'virtualBalance' => floatval($request->input('virtualBalance')),
'active' => true,
'user' => Auth::user()->id,
'accountRole' => $request->input('accountRole'),
@@ -196,31 +202,39 @@ class AccountController extends Controller
Session::flash('success', 'New account "' . $account->name . '" stored!');
if (intval(Input::get('create_another')) === 1) {
return Redirect::route('accounts.create', $request->input('what'));
// set value so create routine will not overwrite URL:
Session::put('accounts.create.fromStore', true);
return Redirect::route('accounts.create')->withInput();
}
return Redirect::route('accounts.index', $request->input('what'));
// redirect to previous URL.
return Redirect::to(Session::get('accounts.create.url'));
}
/**
* @param Account $account
* @param AccountFormRequest $request
* @param AccountRepositoryInterface $repository
* @param Account $account
*
* @return \Illuminate\Http\RedirectResponse
* @return $this|\Illuminate\Http\RedirectResponse
*/
public function update(Account $account, AccountFormRequest $request, AccountRepositoryInterface $repository)
public function update(AccountFormRequest $request, AccountRepositoryInterface $repository, Account $account)
{
$what = Config::get('firefly.shortNamesByFullName.' . $account->accountType->type);
$accountData = [
'name' => $request->input('name'),
'active' => $request->input('active'),
'user' => Auth::user()->id,
'accountRole' => $request->input('accountRole'),
'virtualBalance' => floatval($request->input('virtualBalance')),
'openingBalance' => floatval($request->input('openingBalance')),
'openingBalanceDate' => new Carbon($request->input('openingBalanceDate')),
'openingBalanceCurrency' => intval($request->input('balance_currency_id')),
'ccType' => $request->input('ccType'),
'ccMonthlyPaymentDate' => $request->input('ccMonthlyPaymentDate'),
];
$repository->update($account, $accountData);
@@ -228,10 +242,14 @@ class AccountController extends Controller
Session::flash('success', 'Account "' . $account->name . '" updated.');
if (intval(Input::get('return_to_edit')) === 1) {
return Redirect::route('accounts.edit', $account->id);
// set value so edit routine will not overwrite URL:
Session::put('accounts.edit.fromUpdate', true);
return Redirect::route('accounts.edit', $account->id)->withInput(['return_to_edit' => 1]);
}
return Redirect::route('accounts.index', $what);
// redirect to previous URL.
return Redirect::to(Session::get('accounts.edit.url'));
}

View File

@@ -5,8 +5,10 @@ use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Auth\Registrar;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Illuminate\Http\Request;
use Illuminate\Mail\Message;
use Mail;
use Session;
use Twig;
/**
* Class AuthController
@@ -46,6 +48,16 @@ class AuthController extends Controller
$this->middleware('guest', ['except' => 'getLogout']);
}
/**
* Show the application login form.
*
* @return \Illuminate\Http\Response
*/
public function getLogin()
{
return Twig::render('auth.login');
}
/**
* Handle a registration request for the application.
*
@@ -63,20 +75,25 @@ class AuthController extends Controller
);
}
$this->auth->login($this->registrar->create($request->all()));
$data = $request->all();
$data['password'] = bcrypt($data['password']);
$this->auth->login($this->registrar->create($data));
// get the email address
$email = $this->auth->user()->email;
// send email.
Mail::send(
'emails.registered', [], function ($message) use ($email) {
'emails.registered', [], function (Message $message) use ($email) {
$message->to($email, $email)->subject('Welcome to Firefly III!');
}
);
// set flash message
Session::flash('success', 'You have registered successfully!');
Session::flash('gaEventCategory', 'user');
Session::flash('gaEventAction', 'new-registration');
return redirect($this->redirectPath());

View File

@@ -1,12 +1,13 @@
<?php namespace FireflyIII\Http\Controllers;
use Auth;
use Carbon\Carbon;
use Config;
use FireflyIII\Http\Requests;
use FireflyIII\Http\Requests\BillFormRequest;
use FireflyIII\Models\Account;
use FireflyIII\Models\Bill;
use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionJournal;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Bill\BillRepositoryInterface;
use Input;
use Redirect;
@@ -22,20 +23,75 @@ use View;
class BillController extends Controller
{
/**
*
*/
public function __construct()
{
parent::__construct();
View::share('title', 'Bills');
View::share('mainTitleIcon', 'fa-calendar-o');
}
/**
* @param AccountRepositoryInterface $repository
* @param Bill $bill
*
* @return \Illuminate\Http\RedirectResponse
*/
public function add(AccountRepositoryInterface $repository, Bill $bill)
{
$matches = explode(',', $bill->match);
$description = [];
$expense = null;
// get users expense accounts:
$accounts = $repository->getAccounts(Config::get('firefly.accountTypesByIdentifier.expense'));
foreach ($matches as $match) {
$match = strtolower($match);
// find expense account for each word if not found already:
if (is_null($expense)) {
/** @var Account $account */
foreach ($accounts as $account) {
$name = strtolower($account->name);
if (!(strpos($name, $match) === false)) {
$expense = $account;
break;
}
}
}
if (is_null($expense)) {
$description[] = $match;
}
}
$parameters = [
'description' => ucfirst(join(' ', $description)),
'expense_account' => is_null($expense) ? '' : $expense->name,
'amount' => round(($bill->amount_min + $bill->amount_max), 2),
];
Session::put('preFilled', $parameters);
return Redirect::to(route('transactions.create', 'withdrawal'));
}
/**
* @return $this
*/
public function create()
{
$periods = \Config::get('firefly.periods_to_text');
$periods = Config::get('firefly.periods_to_text');
return view('bills.create')->with('periods', $periods)->with('subTitle', 'Create new');
// put previous url in session if not redirect from store (not "create another").
if (Session::get('bills.create.fromStore') !== true) {
Session::put('bills.create.url', URL::previous());
}
Session::forget('bills.create.fromStore');
$subTitle = 'Create new bill';
return view('bills.create', compact('periods', 'subTitle'));
}
/**
@@ -45,20 +101,26 @@ class BillController extends Controller
*/
public function delete(Bill $bill)
{
return view('bills.delete')->with('bill', $bill)->with('subTitle', 'Delete "' . e($bill->name) . '"');
// put previous url in session
Session::put('bills.delete.url', URL::previous());
$subTitle = 'Delete "' . e($bill->name) . '"';
return view('bills.delete', compact('bill', 'subTitle'));
}
/**
* @param Bill $bill
* @param BillRepositoryInterface $repository
* @param Bill $bill
*
* @return \Illuminate\Http\RedirectResponse
*/
public function destroy(Bill $bill)
public function destroy(BillRepositoryInterface $repository, Bill $bill)
{
$bill->delete();
$repository->destroy($bill);
Session::flash('success', 'The bill was deleted.');
return Redirect::route('bills.index');
return Redirect::to(Session::get('bills.delete.url'));
}
@@ -69,9 +131,16 @@ class BillController extends Controller
*/
public function edit(Bill $bill)
{
$periods = \Config::get('firefly.periods_to_text');
$periods = Config::get('firefly.periods_to_text');
$subTitle = 'Edit "' . e($bill->name) . '"';
return view('bills.edit')->with('periods', $periods)->with('bill', $bill)->with('subTitle', 'Edit "' . e($bill->name) . '"');
// put previous url in session if not redirect from store (not "return_to_edit").
if (Session::get('bills.edit.fromUpdate') !== true) {
Session::put('bills.edit.url', URL::previous());
}
Session::forget('bills.edit.fromUpdate');
return view('bills.edit', compact('subTitle', 'periods', 'bill'));
}
/**
@@ -81,15 +150,11 @@ class BillController extends Controller
*/
public function index(BillRepositoryInterface $repository)
{
$bills = Auth::user()->bills()->orderBy('name', 'ASC')->get();
$bills = $repository->getBills();
$bills->each(
function (Bill $bill) use ($repository) {
$bill->nextExpectedMatch = $repository->nextExpectedMatch($bill);
$last = $bill->transactionjournals()->orderBy('date', 'DESC')->first();
$bill->lastFoundMatch = null;
if ($last) {
$bill->lastFoundMatch = $last->date;
}
$bill->lastFoundMatch = $repository->lastFoundMatch($bill);
}
);
@@ -97,34 +162,25 @@ class BillController extends Controller
}
/**
* @param Bill $bill
* @param BillRepositoryInterface $repository
* @param Bill $bill
*
* @return mixed
* @return \Illuminate\Http\RedirectResponse
*/
public function rescan(Bill $bill, BillRepositoryInterface $repository)
public function rescan(BillRepositoryInterface $repository, Bill $bill)
{
if (intval($bill->active) == 0) {
Session::flash('warning', 'Inactive bills cannot be scanned.');
return Redirect::intended('/');
return Redirect::to(URL::previous());
}
$set = \DB::table('transactions')->where('amount', '>', 0)->where('amount', '>=', $bill->amount_min)->where('amount', '<=', $bill->amount_max)->get(
['transaction_journal_id']
);
$ids = [];
$journals = $repository->getPossiblyRelatedJournals($bill);
/** @var TransactionJournal $journal */
foreach ($journals as $journal) {
$repository->scan($bill, $journal);
}
/** @var Transaction $entry */
foreach ($set as $entry) {
$ids[] = intval($entry->transaction_journal_id);
}
if (count($ids) > 0) {
$journals = Auth::user()->transactionjournals()->whereIn('id', $ids)->get();
/** @var TransactionJournal $journal */
foreach ($journals as $journal) {
$repository->scan($bill, $journal);
}
}
Session::flash('success', 'Rescanned everything.');
@@ -132,119 +188,68 @@ class BillController extends Controller
}
/**
* @param Bill $bill
* @param BillRepositoryInterface $repository
* @param Bill $bill
*
* @return mixed
*/
public function show(Bill $bill, BillRepositoryInterface $repository)
public function show(BillRepositoryInterface $repository, Bill $bill)
{
$journals = $bill->transactionjournals()->withRelevantData()->orderBy('date', 'DESC')->get();
$journals = $repository->getJournals($bill);
$bill->nextExpectedMatch = $repository->nextExpectedMatch($bill);
$hideBill = true;
$subTitle = e($bill->name);
return view('bills.show', compact('journals', 'hideBill', 'bill'))->with('subTitle', e($bill->name));
return view('bills.show', compact('journals', 'hideBill', 'bill', 'subTitle'));
}
/**
* @return $this
* @param BillFormRequest $request
* @param BillRepositoryInterface $repository
*
* @return $this|\Illuminate\Http\RedirectResponse
*/
public function store(BillFormRequest $request, BillRepositoryInterface $repository)
{
var_dump($request->all());
$billData = [
'name' => $request->get('name'),
'match' => $request->get('match'),
'amount_min' => floatval($request->get('amount_min')),
'amount_currency_id' => floatval($request->get('amount_currency_id')),
'amount_max' => floatval($request->get('amount_max')),
'date' => new Carbon($request->get('date')),
'user' => Auth::user()->id,
'repeat_freq' => $request->get('repeat_freq'),
'skip' => intval($request->get('skip')),
'automatch' => intval($request->get('automatch')) === 1,
'active' => intval($request->get('active')) === 1,
];
$bill = $repository->store($billData);
$billData = $request->getBillData();
$bill = $repository->store($billData);
Session::flash('success', 'Bill "' . e($bill->name) . '" stored.');
if (intval(Input::get('create_another')) === 1) {
// set value so create routine will not overwrite URL:
Session::put('bills.create.fromStore', true);
return Redirect::route('bills.create')->withInput();
}
return Redirect::route('bills.index');
// redirect to previous URL.
return Redirect::to(Session::get('bills.create.url'));
}
/**
* @param Bill $bill
* @param BillFormRequest $request
* @param BillRepositoryInterface $repository
* @param Bill $bill
*
* @return $this
* @return $this|\Illuminate\Http\RedirectResponse
*/
public function update(Bill $bill, BillFormRequest $request, BillRepositoryInterface $repository)
public function update(BillFormRequest $request, BillRepositoryInterface $repository, Bill $bill)
{
$billData = [
'name' => $request->get('name'),
'match' => $request->get('match'),
'amount_min' => floatval($request->get('amount_min')),
'amount_currency_id' => floatval($request->get('amount_currency_id')),
'amount_max' => floatval($request->get('amount_max')),
'date' => new Carbon($request->get('date')),
'user' => Auth::user()->id,
'repeat_freq' => $request->get('repeat_freq'),
'skip' => intval($request->get('skip')),
'automatch' => intval($request->get('automatch')) === 1,
'active' => intval($request->get('active')) === 1,
];
$bill = $repository->update($bill, $billData);
if (intval(Input::get('return_to_edit')) === 1) {
return Redirect::route('bills.edit', $bill->id);
}
$billData = $request->getBillData();
$bill = $repository->update($bill, $billData);
Session::flash('success', 'Bill "' . e($bill->name) . '" updated.');
return Redirect::route('bills.index');
if (intval(Input::get('return_to_edit')) === 1) {
// set value so edit routine will not overwrite URL:
Session::put('bills.edit.fromUpdate', true);
return Redirect::route('bills.edit', $bill->id)->withInput(['return_to_edit' => 1]);
}
// $data = Input::except('_token');
// $data['active'] = intval(Input::get('active'));
// $data['automatch'] = intval(Input::get('automatch'));
// $data['user_id'] = Auth::user()->id;
//
// // always validate:
// $messages = $this->_repository->validate($data);
//
// // flash messages:
// Session::flash('warnings', $messages['warnings']);
// Session::flash('successes', $messages['successes']);
// Session::flash('errors', $messages['errors']);
// if ($messages['errors']->count() > 0) {
// Session::flash('error', 'Could not update bill: ' . $messages['errors']->first());
//
// return Redirect::route('bills.edit', $bill->id)->withInput();
// }
//
// // return to update screen:
// if ($data['post_submit_action'] == 'validate_only') {
// return Redirect::route('bills.edit', $bill->id)->withInput();
// }
//
// // update
// $this->_repository->update($bill, $data);
// Session::flash('success', 'Bill "' . e($data['name']) . '" updated.');
//
// // go back to list
// if ($data['post_submit_action'] == 'update') {
// return Redirect::route('bills.index');
// }
//
// // go back to update screen.
// return Redirect::route('bills.edit', $bill->id)->withInput(['post_submit_action' => 'return_to_edit']);
// redirect to previous URL.
return Redirect::to(Session::get('bills.edit.url'));
}

View File

@@ -12,6 +12,7 @@ use Preferences;
use Redirect;
use Response;
use Session;
use URL;
use View;
/**
@@ -22,19 +23,24 @@ use View;
class BudgetController extends Controller
{
/**
*
*/
public function __construct()
{
parent::__construct();
View::share('title', 'Budgets');
View::share('mainTitleIcon', 'fa-tasks');
View::share('hideBudgets', true);
}
/**
* @param Budget $budget
* @param BudgetRepositoryInterface $repository
* @param Budget $budget
*
* @return \Illuminate\Http\JsonResponse
* @throws Exception
* @return \Symfony\Component\HttpFoundation\Response
*/
public function amount(Budget $budget, BudgetRepositoryInterface $repository)
public function amount(BudgetRepositoryInterface $repository, Budget $budget)
{
$amount = intval(Input::get('amount'));
$date = Session::get('start', Carbon::now()->startOfMonth());
@@ -49,7 +55,14 @@ class BudgetController extends Controller
*/
public function create()
{
return view('budgets.create')->with('subTitle', 'Create a new budget');
// put previous url in session if not redirect from store (not "create another").
if (Session::get('budgets.create.fromStore') !== true) {
Session::put('budgets.create.url', URL::previous());
}
Session::forget('budgets.create.fromStore');
$subTitle = 'Create a new budget';
return view('budgets.create', compact('subTitle'));
}
/**
@@ -61,11 +74,15 @@ class BudgetController extends Controller
{
$subTitle = 'Delete budget' . e($budget->name) . '"';
// put previous url in session
Session::put('budgets.delete.url', URL::previous());
return view('budgets.delete', compact('budget', 'subTitle'));
}
/**
* @param Budget $budget
* @param Budget $budget
* @param BudgetRepositoryInterface $repository
*
* @return \Illuminate\Http\RedirectResponse
*/
@@ -75,9 +92,10 @@ class BudgetController extends Controller
$name = $budget->name;
$repository->destroy($budget);
Session::flash('success', 'The budget "' . e($name) . '" was deleted.');
return Redirect::route('budgets.index');
return Redirect::to(Session::get('budgets.delete.url'));
}
/**
@@ -89,59 +107,69 @@ class BudgetController extends Controller
{
$subTitle = 'Edit budget "' . e($budget->name) . '"';
// put previous url in session if not redirect from store (not "return_to_edit").
if (Session::get('budgets.edit.fromUpdate') !== true) {
Session::put('budgets.edit.url', URL::previous());
}
Session::forget('budgets.edit.fromUpdate');
return view('budgets.edit', compact('budget', 'subTitle'));
}
/**
* @return mixed
* @param BudgetRepositoryInterface $repository
*
* @return View
*/
public function index(BudgetRepositoryInterface $repository)
{
$budgets = Auth::user()->budgets()->get();
$budgets = $repository->getActiveBudgets();
$inactive = $repository->getInactiveBudgets();
/**
* Do some cleanup:
*/
$repository->cleanupBudgets();
// loop the budgets:
$budgets->each(
function (Budget $budget) use ($repository) {
$date = Session::get('start', Carbon::now()->startOfMonth());
$budget->spent = $repository->spentInMonth($budget, $date);
$budget->currentRep = $budget->limitrepetitions()->where('limit_repetitions.startdate', $date)->first(['limit_repetitions.*']);
$budget->currentRep = $repository->getCurrentRepetition($budget, $date);
}
);
$date = Session::get('start', Carbon::now()->startOfMonth())->format('FY');
$dateAsString = Session::get('start', Carbon::now()->startOfMonth())->format('FY');
$spent = $budgets->sum('spent');
$amount = Preferences::get('budgetIncomeTotal' . $date, 1000)->data;
$amount = Preferences::get('budgetIncomeTotal' . $dateAsString, 1000)->data;
$overspent = $spent > $amount;
$spentPCT = $overspent ? ceil($amount / $spent * 100) : ceil($spent / $amount * 100);
$budgetMax = Preferences::get('budgetMaximum', 1000);
$budgetMaximum = $budgetMax->data;
return view('budgets.index', compact('budgetMaximum', 'budgets', 'spent', 'spentPCT', 'overspent', 'amount'));
return view('budgets.index', compact('budgetMaximum', 'inactive', 'budgets', 'spent', 'spentPCT', 'overspent', 'amount'));
}
/**
* @return \Illuminate\View\View
* @param BudgetRepositoryInterface $repository
*
* @return View
*/
public function noBudget()
public function noBudget(BudgetRepositoryInterface $repository)
{
$start = \Session::get('start', Carbon::now()->startOfMonth());
$end = \Session::get('end', Carbon::now()->startOfMonth());
$list = Auth::user()
->transactionjournals()
->leftJoin('budget_transaction_journal', 'budget_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id')
->whereNull('budget_transaction_journal.id')
->before($end)
->after($start)
->orderBy('transaction_journals.date')
->get(['transaction_journals.*']);
$subTitle = 'Transactions without a budget in ' . $start->format('F Y');
$start = Session::get('start', Carbon::now()->startOfMonth());
$end = Session::get('end', Carbon::now()->startOfMonth());
$list = $repository->getWithoutBudget($start, $end);
$subTitle = 'Transactions without a budget between ' . $start->format('jS F Y') . ' and ' . $end->format('jS F Y');
return view('budgets.noBudget', compact('list', 'subTitle'));
}
/**
* @return mixed
* @return \Illuminate\Http\RedirectResponse
*/
public function postUpdateIncome()
{
@@ -152,6 +180,35 @@ class BudgetController extends Controller
return Redirect::route('budgets.index');
}
/**
* @param BudgetRepositoryInterface $repository
* @param Budget $budget
* @param LimitRepetition $repetition
*
* @return View
*/
public function show(BudgetRepositoryInterface $repository, Budget $budget, LimitRepetition $repetition = null)
{
if (!is_null($repetition->id) && $repetition->budgetLimit->budget->id != $budget->id) {
$message = 'Invalid selection.';
return view('error', compact('message'));
}
$journals = $repository->getJournals($budget, $repetition);
$limits = !is_null($repetition->id) ? [$repetition->budgetLimit] : $repository->getBudgetLimits($budget);
$subTitle = !is_null($repetition->id) ? e($budget->name) . ' in ' . $repetition->startdate->format('F Y') : e($budget->name);
$journals->setPath('/budgets/show/' . $budget->id);
return view('budgets.show', compact('limits', 'budget', 'repetition', 'journals', 'subTitle'));
}
/**
* @param BudgetFormRequest $request
* @param BudgetRepositoryInterface $repository
*
* @return \Illuminate\Http\RedirectResponse
*/
public function store(BudgetFormRequest $request, BudgetRepositoryInterface $repository)
{
$budgetData = [
@@ -162,61 +219,57 @@ class BudgetController extends Controller
Session::flash('success', 'New budget "' . $budget->name . '" stored!');
return Redirect::route('budgets.index');
if (intval(Input::get('create_another')) === 1) {
// set value so create routine will not overwrite URL:
Session::put('budgets.create.fromStore', true);
}
/**
*
* @param Budget $budget
* @param LimitRepetition $repetition
*
* @return \Illuminate\View\View
*/
public function show(Budget $budget, LimitRepetition $repetition = null, BudgetRepositoryInterface $repository)
{
if (!is_null($repetition->id) && $repetition->budgetLimit->budget->id != $budget->id) {
return view('error')->with('message', 'Invalid selection.');
return Redirect::route('budgets.create')->withInput();
}
$hideBudget = true; // used in transaction list.
$journals = $repository->getJournals($budget, $repetition);
$limits = !is_null($repetition->id) ? [$repetition->budgetLimit] : $budget->budgetLimits()->orderBy('startdate', 'DESC')->get();
$subTitle = !is_null($repetition->id) ? e($budget->name) . ' in ' . $repetition->startdate->format('F Y') : e($budget->name);
// redirect to previous URL.
return Redirect::to(Session::get('budgets.create.url'));
return view('budgets.show', compact('limits', 'budget', 'repetition', 'journals', 'subTitle', 'hideBudget'));
}
/**
* @param Budget $budget
* @param BudgetFormRequest $request
* @param BudgetRepositoryInterface $repository
* @param Budget $budget
*
* @return \Illuminate\Http\RedirectResponse
* @return $this|\Illuminate\Http\RedirectResponse
*/
public function update(Budget $budget, BudgetFormRequest $request, BudgetRepositoryInterface $repository)
public function update(BudgetFormRequest $request, BudgetRepositoryInterface $repository, Budget $budget)
{
$budgetData = [
'name' => $request->input('name'),
'name' => $request->input('name'),
'active' => intval($request->input('active')) == 1
];
$repository->update($budget, $budgetData);
Session::flash('success', 'Budget "' . $budget->name . '" updated.');
return Redirect::route('budgets.index');
if (intval(Input::get('return_to_edit')) === 1) {
// set value so edit routine will not overwrite URL:
Session::put('budgets.edit.fromUpdate', true);
return Redirect::route('budgets.edit', $budget->id)->withInput(['return_to_edit' => 1]);
}
// redirect to previous URL.
return Redirect::to(Session::get('budgets.edit.url'));
}
/**
* @return $this
* @return View
*/
public function updateIncome()
{
$date = Session::get('start', Carbon::now()->startOfMonth())->format('FY');
$budgetAmount = Preferences::get('budgetIncomeTotal' . $date, 1000);
$date = Session::get('start', Carbon::now()->startOfMonth())->format('FY');
$amount = Preferences::get('budgetIncomeTotal' . $date, 1000);
return view('budgets.income')->with('amount', $budgetAmount);
return view('budgets.income', compact('amount'));
}
}

View File

@@ -2,7 +2,6 @@
use Auth;
use Carbon\Carbon;
use FireflyIII\Http\Requests;
use FireflyIII\Http\Requests\CategoryFormRequest;
use FireflyIII\Models\Category;
use FireflyIII\Repositories\Category\CategoryRepositoryInterface;
@@ -10,9 +9,9 @@ use Illuminate\Pagination\LengthAwarePaginator;
use Input;
use Redirect;
use Session;
use URL;
use View;
/**
* Class CategoryController
*
@@ -26,6 +25,7 @@ class CategoryController extends Controller
*/
public function __construct()
{
parent::__construct();
View::share('title', 'Categories');
View::share('mainTitleIcon', 'fa-bar-chart');
}
@@ -35,7 +35,14 @@ class CategoryController extends Controller
*/
public function create()
{
return view('categories.create')->with('subTitle', 'Create a new category');
// put previous url in session if not redirect from store (not "create another").
if (Session::get('categories.create.fromStore') !== true) {
Session::put('categories.create.url', URL::previous());
}
Session::forget('categories.create.fromStore');
$subTitle = 'Create a new category';
return view('categories.create', compact('subTitle'));
}
/**
@@ -45,17 +52,21 @@ class CategoryController extends Controller
*/
public function delete(Category $category)
{
$subTitle = 'Delete category' . e($category->name) . '"';
$subTitle = 'Delete category "' . e($category->name) . '"';
// put previous url in session
Session::put('categories.delete.url', URL::previous());
return view('categories.delete', compact('category', 'subTitle'));
}
/**
* @param Category $category
* @param CategoryRepositoryInterface $repository
* @param Category $category
*
* @return \Illuminate\Http\RedirectResponse
*/
public function destroy(Category $category, CategoryRepositoryInterface $repository)
public function destroy(CategoryRepositoryInterface $repository, Category $category)
{
$name = $category->name;
@@ -63,7 +74,7 @@ class CategoryController extends Controller
Session::flash('success', 'The category "' . e($name) . '" was deleted.');
return Redirect::route('categories.index');
return Redirect::to(Session::get('categories.delete.url'));
}
/**
@@ -75,23 +86,28 @@ class CategoryController extends Controller
{
$subTitle = 'Edit category "' . e($category->name) . '"';
// put previous url in session if not redirect from store (not "return_to_edit").
if (Session::get('categories.edit.fromUpdate') !== true) {
Session::put('categories.edit.url', URL::previous());
}
Session::forget('categories.edit.fromUpdate');
return view('categories.edit', compact('category', 'subTitle'));
}
/**
* @param CategoryRepositoryInterface $repository
*
* @return $this
*/
public function index()
public function index(CategoryRepositoryInterface $repository)
{
$categories = Auth::user()->categories()->orderBy('name', 'ASC')->get();
$categories = $repository->getCategories();
$categories->each(
function (Category $category) {
$latest = $category->transactionjournals()->orderBy('date', 'DESC')->first();
if ($latest) {
$category->lastActivity = $latest->date;
}
function (Category $category) use ($repository) {
$category->lastActivity = $repository->getLatestActivity($category);
}
);
@@ -99,42 +115,34 @@ class CategoryController extends Controller
}
/**
* @param CategoryRepositoryInterface $repository
*
* @return \Illuminate\View\View
*/
public function noCategory()
public function noCategory(CategoryRepositoryInterface $repository)
{
$start = Session::get('start', Carbon::now()->startOfMonth());
$end = Session::get('end', Carbon::now()->startOfMonth());
$list = Auth::user()
->transactionjournals()
->leftJoin('category_transaction_journal', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id')
->whereNull('category_transaction_journal.id')
->before($end)
->after($start)
->orderBy('transaction_journals.date')
->get(['transaction_journals.*']);
$start = Session::get('start', Carbon::now()->startOfMonth());
$end = Session::get('end', Carbon::now()->startOfMonth());
$list = $repository->getWithoutCategory($start, $end);
$subTitle = 'Transactions without a category between ' . $start->format('jS F Y') . ' and ' . $end->format('jS F Y');
return view('categories.noCategory', compact('list', 'subTitle'));
}
/**
* @param Category $category
* @param CategoryRepositoryInterface $repository
* @param Category $category
*
* @return $this
* @return View
*/
public function show(Category $category, CategoryRepositoryInterface $repository)
public function show(CategoryRepositoryInterface $repository, Category $category)
{
$hideCategory = true; // used in list.
$page = intval(Input::get('page'));
$offset = $page > 0 ? $page * 50 : 0;
$set = $category->transactionJournals()->withRelevantData()->take(50)->offset($offset)->orderBy('date', 'DESC')->get(
['transaction_journals.*']
);
$count = $category->transactionJournals()->count();
$journals = new LengthAwarePaginator($set, $count, 50, $page);
$set = $repository->getJournals($category, $page);
$count = $repository->countJournals($category);
$journals = new LengthAwarePaginator($set, $count, 50, $page);
$journals->setPath('categories/show/' . $category->id);
return view('categories.show', compact('category', 'journals', 'hideCategory'));
}
@@ -155,19 +163,24 @@ class CategoryController extends Controller
Session::flash('success', 'New category "' . $category->name . '" stored!');
return Redirect::route('categories.index');
if (intval(Input::get('create_another')) === 1) {
Session::put('categories.create.fromStore', true);
return Redirect::route('categories.create')->withInput();
}
return Redirect::route('categories.index');
}
/**
* @param Category $category
* @param CategoryFormRequest $request
* @param CategoryRepositoryInterface $repository
* @param Category $category
*
* @return \Illuminate\Http\RedirectResponse
*/
public function update(Category $category, CategoryFormRequest $request, CategoryRepositoryInterface $repository)
public function update(CategoryFormRequest $request, CategoryRepositoryInterface $repository, Category $category)
{
$categoryData = [
'name' => $request->input('name'),
@@ -177,7 +190,14 @@ class CategoryController extends Controller
Session::flash('success', 'Category "' . $category->name . '" updated.');
return Redirect::route('categories.index');
if (intval(Input::get('return_to_edit')) === 1) {
Session::put('categories.edit.fromUpdate', true);
return Redirect::route('categories.edit', $category->id);
}
// redirect to previous URL.
return Redirect::to(Session::get('categories.edit.url'));
}

View File

@@ -3,6 +3,7 @@
use Illuminate\Foundation\Bus\DispatchesCommands;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use View;
/**
* Class Controller
@@ -14,4 +15,14 @@ abstract class Controller extends BaseController
use DispatchesCommands, ValidatesRequests;
/**
*
*/
public function __construct()
{
View::share('hideBudgets', false);
View::share('hideCategories', false);
View::share('hideBills', false);
View::share('hideTags', false);
}
}

View File

@@ -5,13 +5,14 @@ use FireflyIII\Http\Requests;
use FireflyIII\Http\Requests\CurrencyFormRequest;
use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use Input;
use Preferences;
use Redirect;
use Session;
use URL;
use View;
/**
* Class CurrencyController
*
@@ -26,7 +27,7 @@ class CurrencyController extends Controller
*/
public function __construct()
{
parent::__construct();
View::share('title', 'Currencies');
View::share('mainTitleIcon', 'fa-usd');
}
@@ -39,6 +40,12 @@ class CurrencyController extends Controller
$subTitleIcon = 'fa-plus';
$subTitle = 'Create a new currency';
// put previous url in session if not redirect from store (not "create another").
if (Session::get('currency.create.fromStore') !== true) {
Session::put('currency.create.url', URL::previous());
}
Session::forget('currency.create.fromStore');
return view('currency.create', compact('subTitleIcon', 'subTitle'));
}
@@ -50,9 +57,7 @@ class CurrencyController extends Controller
public function defaultCurrency(TransactionCurrency $currency)
{
$currencyPreference = Preferences::get('currencyPreference', 'EUR');
$currencyPreference->data = $currency->code;
$currencyPreference->save();
Preferences::set('currencyPreference', $currency->code);
Session::flash('success', $currency->name . ' is now the default currency.');
Cache::forget('FFCURRENCYSYMBOL');
@@ -63,31 +68,38 @@ class CurrencyController extends Controller
}
/**
* @param TransactionCurrency $currency
* @param CurrencyRepositoryInterface $repository
* @param TransactionCurrency $currency
*
* @return \Illuminate\Http\RedirectResponse|\Illuminate\View\View
* @return \Illuminate\Http\RedirectResponse|View
*/
public function delete(TransactionCurrency $currency)
public function delete(CurrencyRepositoryInterface $repository, TransactionCurrency $currency)
{
if ($currency->transactionJournals()->count() > 0) {
if ($repository->countJournals($currency) > 0) {
Session::flash('error', 'Cannot delete ' . e($currency->name) . ' because there are still transactions attached to it.');
return Redirect::route('currency.index');
}
// put previous url in session
Session::put('currency.delete.url', URL::previous());
return view('currency.delete', compact('currency'));
}
/**
* @param TransactionCurrency $currency
* @param CurrencyRepositoryInterface $repository
* @param TransactionCurrency $currency
*
* @return \Illuminate\Http\RedirectResponse
* @throws \Exception
*/
public function destroy(TransactionCurrency $currency)
public function destroy(CurrencyRepositoryInterface $repository, TransactionCurrency $currency)
{
if ($currency->transactionJournals()->count() > 0) {
Session::flash('error', 'Cannot delete ' . e($currency->name) . ' because there are still transactions attached to it.');
if ($repository->countJournals($currency) > 0) {
Session::flash('error', 'Cannot destroy ' . e($currency->name) . ' because there are still transactions attached to it.');
return Redirect::route('currency.index');
}
@@ -96,7 +108,7 @@ class CurrencyController extends Controller
$currency->delete();
return Redirect::route('currency.index');
return Redirect::to(Session::get('currency.delete.url'));
}
/**
@@ -110,73 +122,79 @@ class CurrencyController extends Controller
$subTitle = 'Edit currency "' . e($currency->name) . '"';
$currency->symbol = htmlentities($currency->symbol);
// put previous url in session if not redirect from store (not "return_to_edit").
if (Session::get('currency.edit.fromUpdate') !== true) {
Session::put('currency.edit.url', URL::previous());
}
Session::forget('currency.edit.fromUpdate');
return view('currency.edit', compact('currency', 'subTitle', 'subTitleIcon'));
}
/**
* @param CurrencyRepositoryInterface $repository
*
* @return \Illuminate\View\View
*/
public function index()
public function index(CurrencyRepositoryInterface $repository)
{
$currencies = TransactionCurrency::get();
$currencyPreference = Preferences::get('currencyPreference', 'EUR');
$defaultCurrency = TransactionCurrency::whereCode($currencyPreference->data)->first();
$currencies = $repository->get();
$defaultCurrency = $repository->getCurrencyByPreference(Preferences::get('currencyPreference', 'EUR'));
return view('currency.index', compact('currencies', 'defaultCurrency'));
}
/**
* @SuppressWarnings("CyclomaticComplexity") // It's exactly 5. So I don't mind.
*
* @param CurrencyFormRequest $request
* @param CurrencyRepositoryInterface $repository
*
* @return $this|\Illuminate\Http\RedirectResponse
*/
public function store(CurrencyFormRequest $request)
public function store(CurrencyFormRequest $request, CurrencyRepositoryInterface $repository)
{
$data = $request->getCurrencyData();
$currency = $repository->store($data);
// no repository, because the currency controller is relatively simple.
$currency = TransactionCurrency::create(
[
'name' => $request->get('name'),
'code' => $request->get('code'),
'symbol' => $request->get('symbol'),
]
);
Session::flash('success', 'Currency "' . $currency->name . '" created');
if (intval(Input::get('create_another')) === 1) {
return Redirect::route('currency.create');
Session::put('currency.create.fromStore', true);
return Redirect::route('currency.create')->withInput();
}
return Redirect::route('currency.index');
// redirect to previous URL.
return Redirect::to(Session::get('currency.create.url'));
}
/**
* @param TransactionCurrency $currency
* @param CurrencyFormRequest $request
* @param CurrencyRepositoryInterface $repository
* @param TransactionCurrency $currency
*
* @return $this|\Illuminate\Http\RedirectResponse
* @return \Illuminate\Http\RedirectResponse
*/
public function update(TransactionCurrency $currency, CurrencyFormRequest $request)
public function update(CurrencyFormRequest $request, CurrencyRepositoryInterface $repository, TransactionCurrency $currency)
{
$currency->code = $request->get('code');
$currency->symbol = $request->get('symbol');
$currency->name = $request->get('name');
$currency->save();
$data = $request->getCurrencyData();
$currency = $repository->update($currency, $data);
Session::flash('success', 'Currency "' . e($currency->name) . '" updated.');
if (intval(Input::get('return_to_edit')) === 1) {
Session::put('currency.edit.fromUpdate', true);
return Redirect::route('currency.edit', $currency->id);
}
return Redirect::route('currency.index');
// redirect to previous URL.
return Redirect::to(Session::get('currency.edit.url'));
}

View File

@@ -1,12 +1,8 @@
<?php namespace FireflyIII\Http\Controllers;
use App;
use Auth;
use Carbon\Carbon;
use DB;
use Exception;
use Crypt;
use FireflyIII\Helpers\Report\ReportQueryInterface;
use FireflyIII\Http\Requests;
use FireflyIII\Models\Account;
use FireflyIII\Models\Bill;
use FireflyIII\Models\Budget;
@@ -16,11 +12,12 @@ use FireflyIII\Models\PiggyBank;
use FireflyIII\Models\Preference;
use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionJournal;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Bill\BillRepositoryInterface;
use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
use FireflyIII\Repositories\Category\CategoryRepositoryInterface;
use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface;
use Grumpydictator\Gchart\GChart;
use Illuminate\Database\Query\Builder as QueryBuilder;
use Illuminate\Database\Query\JoinClause;
use Illuminate\Support\Collection;
use Navigation;
use Preferences;
@@ -38,12 +35,12 @@ class GoogleChartController extends Controller
/**
* @param GChart $chart
* @param Account $account
* @param string $view
*
* @return \Illuminate\Http\JsonResponse
* @return \Symfony\Component\HttpFoundation\Response
*/
public function accountBalanceChart(Account $account, GChart $chart)
public function accountBalanceChart(GChart $chart, Account $account)
{
$chart->addColumn('Day of month', 'date');
$chart->addColumn('Balance for ' . $account->name, 'number');
@@ -52,9 +49,11 @@ class GoogleChartController extends Controller
$start = Session::get('start', Carbon::now()->startOfMonth());
$end = Session::get('end', Carbon::now()->endOfMonth());
$current = clone $start;
$today = new Carbon;
while ($end >= $current) {
$chart->addRow(clone $current, Steam::balance($account, $current), false);
$certain = $current < $today;
$chart->addRow(clone $current, Steam::balance($account, $current), $certain);
$current->addDay();
}
@@ -65,23 +64,20 @@ class GoogleChartController extends Controller
}
/**
* @param GChart $chart
* @param GChart $chart
* @param AccountRepositoryInterface $repository
*
* @return \Symfony\Component\HttpFoundation\Response
*/
public function allAccountsBalanceChart(GChart $chart)
public function allAccountsBalanceChart(GChart $chart, AccountRepositoryInterface $repository)
{
$chart->addColumn('Day of the month', 'date');
$frontPage = Preferences::get('frontPageAccounts', []);
$start = Session::get('start', Carbon::now()->startOfMonth());
$end = Session::get('end', Carbon::now()->endOfMonth());
$accounts = $repository->getFrontpageAccounts($frontPage);
if ($frontPage->data == []) {
$accounts = Auth::user()->accounts()->orderBy('accounts.name', 'ASC')->accountTypeIn(['Default account', 'Asset account'])->get(['accounts.*']);
} else {
$accounts = Auth::user()->accounts()->whereIn('id', $frontPage->data)->orderBy('accounts.name', 'ASC')->get(['accounts.*']);
}
$index = 1;
/** @var Account $account */
foreach ($accounts as $account) {
@@ -109,28 +105,24 @@ class GoogleChartController extends Controller
}
/**
* @param int $year
* @param GChart $chart
* @param BudgetRepositoryInterface $repository
* @param $year
*
* @return $this|\Illuminate\Http\JsonResponse
* @return \Symfony\Component\HttpFoundation\Response
*/
public function allBudgetsAndSpending($year, GChart $chart, BudgetRepositoryInterface $repository)
public function allBudgetsAndSpending(GChart $chart, BudgetRepositoryInterface $repository, $year)
{
try {
new Carbon('01-01-' . $year);
} catch (Exception $e) {
return view('error')->with('message', 'Invalid year.');
}
$budgets = Auth::user()->budgets()->get();
$budgets->sortBy('name');
$budgets = $repository->getBudgets();
$chart->addColumn('Month', 'date');
foreach ($budgets as $budget) {
$chart->addColumn($budget->name, 'number');
}
$start = Carbon::createFromDate(intval($year), 1, 1);
$end = clone $start;
$end->endOfYear();
while ($start <= $end) {
$row = [clone $start];
foreach ($budgets as $budget) {
@@ -141,7 +133,6 @@ class GoogleChartController extends Controller
$start->addMonth();
}
$chart->generate();
return Response::json($chart->getData());
@@ -149,113 +140,79 @@ class GoogleChartController extends Controller
}
/**
* @param GChart $chart
* @param GChart $chart
* @param BudgetRepositoryInterface $repository
*
* @return \Symfony\Component\HttpFoundation\Response
*/
public function allBudgetsHomeChart(GChart $chart)
public function allBudgetsHomeChart(GChart $chart, BudgetRepositoryInterface $repository)
{
$chart->addColumn('Budget', 'string');
$chart->addColumn('Budgeted', 'number');
$chart->addColumn('Spent', 'number');
$chart->addColumn('Left', 'number');
$chart->addColumn('Overspent', 'number');
$budgets = Auth::user()->budgets()->orderBy('name', 'DESC')->get();
$start = Session::get('start', Carbon::now()->startOfMonth());
$end = Session::get('end', Carbon::now()->endOfMonth());
$budgets = $repository->getBudgets();
$start = Session::get('start', Carbon::now()->startOfMonth());
$end = Session::get('end', Carbon::now()->endOfMonth());
$allEntries = new Collection;
/** @var Budget $budget */
foreach ($budgets as $budget) {
/** @var Collection $repetitions */
$repetitions = LimitRepetition::
leftJoin('budget_limits', 'limit_repetitions.budget_limit_id', '=', 'budget_limits.id')
->where('limit_repetitions.startdate', '<=', $end->format('Y-m-d 00:00:00'))
->where('limit_repetitions.startdate', '>=', $start->format('Y-m-d 00:00:00'))
->where('budget_limits.budget_id', $budget->id)
->get(['limit_repetitions.*']);
// no results? search entire range for expenses and list those.
$repetitions = $repository->getBudgetLimitRepetitions($budget, $start, $end);
if ($repetitions->count() == 0) {
$expenses = floatval($budget->transactionjournals()->before($end)->after($start)->lessThan(0)->sum('amount')) * -1;
if ($expenses > 0) {
$chart->addRow($budget->name, 0, $expenses);
}
} else {
// add with foreach:
/** @var LimitRepetition $repetition */
foreach ($repetitions as $repetition) {
$expenses
=
floatval($budget->transactionjournals()->before($repetition->enddate)->after($repetition->startdate)->lessThan(0)->sum('amount')) * -1;
if ($expenses > 0) {
$chart->addRow($budget->name . ' (' . $repetition->startdate->format('j M Y') . ')', floatval($repetition->amount), $expenses);
}
}
$expenses = $repository->sumBudgetExpensesInPeriod($budget, $start, $end);
$allEntries->push([$budget->name, 0, $expenses]);
continue;
}
/** @var LimitRepetition $repetition */
foreach ($repetitions as $repetition) {
$expenses = $repository->sumBudgetExpensesInPeriod($budget, $repetition->startdate, $repetition->enddate);
$allEntries->push([$budget->name . ' (' . $repetition->startdate->format('j M Y') . ')', floatval($repetition->amount), $expenses]);
}
}
$noBudgetExpenses = $repository->getWithoutBudgetSum($start, $end);
$allEntries->push(['(no budget)', 0, $noBudgetExpenses]);
foreach ($allEntries as $entry) {
if ($entry[2] > 0) {
$left = $entry[1] - $entry[2];
if ($left > 0) {
$chart->addRow($entry[0], $left, null);
} else {
if ($left < 0) {
$chart->addRow($entry[0], null, $left);
}
}
}
}
$noBudgetSet = Auth::user()
->transactionjournals()
->whereNotIn(
'transaction_journals.id', function (QueryBuilder $query) use ($start, $end) {
$query
->select('transaction_journals.id')
->from('transaction_journals')
->leftJoin('budget_transaction_journal', 'budget_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id')
->where('transaction_journals.date', '>=', $start->format('Y-m-d 00:00:00'))
->where('transaction_journals.date', '<=', $end->format('Y-m-d 00:00:00'))
->whereNotNull('budget_transaction_journal.budget_id');
}
)
->before($end)
->after($start)
->lessThan(0)
->transactionTypes(['Withdrawal'])
->get();
$sum = $noBudgetSet->sum('amount') * -1;
$chart->addRow('No budget', 0, $sum);
$chart->generate();
return Response::json($chart->getData());
}
/**
* @param GChart $chart
* @param GChart $chart
* @param CategoryRepositoryInterface $repository
*
* @return \Symfony\Component\HttpFoundation\Response
*/
public function allCategoriesHomeChart(GChart $chart)
public function allCategoriesHomeChart(GChart $chart, CategoryRepositoryInterface $repository)
{
$chart->addColumn('Category', 'string');
$chart->addColumn('Spent', 'number');
// query!
$start = Session::get('start', Carbon::now()->startOfMonth());
$end = Session::get('end', Carbon::now()->endOfMonth());
$set = TransactionJournal::leftJoin(
'transactions',
function (JoinClause $join) {
$join->on('transaction_journals.id', '=', 'transactions.transaction_journal_id')->where('amount', '>', 0);
}
)
->leftJoin(
'category_transaction_journal', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id'
)
->leftJoin('categories', 'categories.id', '=', 'category_transaction_journal.category_id')
->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id')
->before($end)
->after($start)
->where('transaction_types.type', 'Withdrawal')
->groupBy('categories.id')
->orderBy('sum', 'DESC')
->get(['categories.id', 'categories.name', \DB::Raw('SUM(`transactions`.`amount`) AS `sum`')]);
$set = $repository->getCategoriesAndExpenses($start, $end);
foreach ($set as $entry) {
$entry->name = strlen($entry->name) == 0 ? '(no category)' : $entry->name;
$chart->addRow($entry->name, floatval($entry->sum));
$isEncrypted = intval($entry->encrypted) == 1 ? true : false;
$name = strlen($entry->name) == 0 ? '(no category)' : $entry->name;
$name = $isEncrypted ? Crypt::decrypt($name) : $name;
$chart->addRow($name, floatval($entry->sum));
}
$chart->generate();
@@ -265,41 +222,25 @@ class GoogleChartController extends Controller
}
/**
* @param Bill $bill
* @param GChart $chart
* @param BillRepositoryInterface $repository
* @param Bill $bill
*
* @return \Illuminate\Http\JsonResponse
* @return \Symfony\Component\HttpFoundation\Response
*/
public function billOverview(Bill $bill, GChart $chart)
public function billOverview(GChart $chart, BillRepositoryInterface $repository, Bill $bill)
{
$chart->addColumn('Date', 'date');
$chart->addColumn('Max amount', 'number');
$chart->addColumn('Min amount', 'number');
$chart->addColumn('Current entry', 'number');
$chart->addColumn('Recorded bill entry', 'number');
// get first transaction or today for start:
$first = $bill->transactionjournals()->orderBy('date', 'ASC')->first();
if ($first) {
$start = $first->date;
} else {
$start = new Carbon;
}
$end = new Carbon;
while ($start <= $end) {
$result = $bill->transactionjournals()->before($end)->after($start)->first();
if ($result) {
/** @var Transaction $tr */
foreach ($result->transactions()->get() as $tr) {
if (floatval($tr->amount) > 0) {
$amount = floatval($tr->amount);
}
}
} else {
$amount = 0;
}
unset($result);
$chart->addRow(clone $start, $bill->amount_max, $bill->amount_min, $amount);
$start = Navigation::addPeriod($start, $bill->repeat_freq, 0);
$results = $repository->getJournals($bill);
/** @var TransactionJournal $result */
foreach ($results as $result) {
$chart->addRow(clone $result->date, floatval($bill->amount_max), floatval($bill->amount_min), floatval($result->amount));
}
$chart->generate();
@@ -309,22 +250,28 @@ class GoogleChartController extends Controller
}
/**
* @param GChart $chart
* @param GChart $chart
*
* @param BillRepositoryInterface $repository
* @param AccountRepositoryInterface $accounts
*
* @return \Symfony\Component\HttpFoundation\Response
*/
public function billsOverview(GChart $chart, BillRepositoryInterface $repository)
public function billsOverview(GChart $chart, BillRepositoryInterface $repository, AccountRepositoryInterface $accounts)
{
$chart->addColumn('Name', 'string');
$chart->addColumn('Amount', 'number');
$paid = ['items' => [], 'amount' => 0];
$unpaid = ['items' => [], 'amount' => 0];
$start = Session::get('start', Carbon::now()->startOfMonth());
$end = Session::get('end', Carbon::now()->endOfMonth());
$bills = Auth::user()->bills()->where('active', 1)->get();
$bills = $repository->getActiveBills();
$paid = new Collection; // journals.
$unpaid = new Collection; // bills
// loop paid and create single entry:
$paidDescriptions = [];
$paidAmount = 0;
$unpaidDescriptions = [];
$unpaidAmount = 0;
/** @var Bill $bill */
foreach ($bills as $bill) {
@@ -332,41 +279,70 @@ class GoogleChartController extends Controller
foreach ($ranges as $range) {
// paid a bill in this range?
$count = $bill->transactionjournals()->before($range['end'])->after($range['start'])->count();
if ($count == 0) {
$unpaid['items'][] = $bill->name . ' (' . $range['start']->format('jS M Y') . ')';
$unpaid['amount'] += ($bill->amount_max + $bill->amount_min / 2);
$journals = $repository->getJournalsInRange($bill, $range['start'], $range['end']);
if ($journals->count() == 0) {
$unpaid->push([$bill, $range['start']]);
} else {
$journal = $bill->transactionjournals()->with('transactions')->before($range['end'])->after($range['start'])->first();
$paid['items'][] = $journal->description;
$amount = 0;
foreach ($journal->transactions as $t) {
if (floatval($t->amount) > 0) {
$amount = floatval($t->amount);
}
}
$paid['amount'] += $amount;
$paid = $paid->merge($journals);
}
}
}
$chart->addRow('Unpaid: ' . join(', ', $unpaid['items']), $unpaid['amount']);
$chart->addRow('Paid: ' . join(', ', $paid['items']), $paid['amount']);
$creditCards = $accounts->getCreditCards();
foreach ($creditCards as $creditCard) {
$balance = Steam::balance($creditCard, null, true);
$date = new Carbon($creditCard->getMeta('ccMonthlyPaymentDate'));
if ($balance < 0) {
// unpaid! create a fake bill that matches the amount.
$description = $creditCard->name;
$amount = $balance * -1;
$fakeBill = $repository->createFakeBill($description, $date, $amount);
unset($description, $amount);
$unpaid->push([$fakeBill, $date]);
}
if ($balance == 0) {
// find transfer(s) TO the credit card which should account for
// anything paid. If not, the CC is not yet used.
$journals = $accounts->getTransfersInRange($creditCard, $start, $end);
$paid = $paid->merge($journals);
}
}
/** @var TransactionJournal $entry */
foreach ($paid as $entry) {
$paidDescriptions[] = $entry->description;
$paidAmount += floatval($entry->amount);
}
// loop unpaid:
/** @var Bill $entry */
foreach ($unpaid as $entry) {
$description = $entry[0]->name . ' (' . $entry[1]->format('jS M Y') . ')';
$amount = ($entry[0]->amount_max + $entry[0]->amount_min) / 2;
$unpaidDescriptions[] = $description;
$unpaidAmount += $amount;
unset($amount, $description);
}
$chart->addRow('Unpaid: ' . join(', ', $unpaidDescriptions), $unpaidAmount);
$chart->addRow('Paid: ' . join(', ', $paidDescriptions), $paidAmount);
$chart->generate();
return Response::json($chart->getData());
}
/**
* @param GChart $chart
* @param BudgetRepositoryInterface $repository
* @param Budget $budget
* @param LimitRepetition $repetition
*
* @param Budget $budget
* @param LimitRepetition $repetition
*
* @return \Illuminate\Http\JsonResponse
* @return \Symfony\Component\HttpFoundation\Response
*/
public function budgetLimitSpending(Budget $budget, LimitRepetition $repetition, GChart $chart)
public function budgetLimitSpending(GChart $chart, BudgetRepositoryInterface $repository, Budget $budget, LimitRepetition $repetition)
{
$start = clone $repetition->startdate;
$end = $repetition->enddate;
@@ -381,7 +357,7 @@ class GoogleChartController extends Controller
/*
* Sum of expenses on this day:
*/
$sum = floatval($budget->transactionjournals()->lessThan(0)->transactionTypes(['Withdrawal'])->onDate($start)->sum('amount'));
$sum = $repository->expensesOnDay($budget, $start);
$amount += $sum;
$chart->addRow(clone $start, $amount);
$start->addDay();
@@ -393,37 +369,22 @@ class GoogleChartController extends Controller
}
/**
* @param GChart $chart
* @param BudgetRepositoryInterface $repository
* @param Budget $budget
* @param int $year
*
* @param Budget $budget
*
* @param int $year
*
* @return \Illuminate\Http\JsonResponse
* @return \Symfony\Component\HttpFoundation\Response
*/
public function budgetsAndSpending(Budget $budget, $year = 0)
public function budgetsAndSpending(GChart $chart, BudgetRepositoryInterface $repository, Budget $budget, $year = 0)
{
$chart = App::make('Grumpydictator\Gchart\GChart');
$repository = App::make('FireflyIII\Repositories\Budget\BudgetRepository');
$chart->addColumn('Month', 'date');
$chart->addColumn('Budgeted', 'number');
$chart->addColumn('Spent', 'number');
if ($year == 0) {
// grab the first budgetlimit ever:
$firstLimit = $budget->budgetlimits()->orderBy('startdate', 'ASC')->first();
if ($firstLimit) {
$start = new Carbon($firstLimit->startdate);
} else {
$start = Carbon::now()->startOfYear();
}
// grab the last budget limit ever:
$lastLimit = $budget->budgetlimits()->orderBy('startdate', 'DESC')->first();
if ($lastLimit) {
$end = new Carbon($lastLimit->startdate);
} else {
$end = Carbon::now()->endOfYear();
}
if ($year == 0) {
$start = $repository->getFirstBudgetLimitDate($budget);
$end = $repository->getLastBudgetLimitDate($budget);
} else {
$start = Carbon::createFromDate(intval($year), 1, 1);
$end = clone $start;
@@ -431,19 +392,8 @@ class GoogleChartController extends Controller
}
while ($start <= $end) {
$spent = $repository->spentInMonth($budget, $start);
$repetition = LimitRepetition::leftJoin('budget_limits', 'limit_repetitions.budget_limit_id', '=', 'budget_limits.id')
->where('limit_repetitions.startdate', $start->format('Y-m-d 00:00:00'))
->where('budget_limits.budget_id', $budget->id)
->first(['limit_repetitions.*']);
if ($repetition) {
$budgeted = floatval($repetition->amount);
\Log::debug('Found a repetition on ' . $start->format('Y-m-d') . ' for budget ' . $budget->name . '!');
} else {
\Log::debug('No repetition on ' . $start->format('Y-m-d') . ' for budget ' . $budget->name);
$budgeted = null;
}
$spent = $repository->spentInMonth($budget, $start);
$budgeted = $repository->getLimitAmountOnDate($budget, $start);
$chart->addRow(clone $start, $budgeted, $spent);
$start->addMonth();
}
@@ -456,17 +406,17 @@ class GoogleChartController extends Controller
}
/**
* @param GChart $chart
* @param CategoryRepositoryInterface $repository
* @param Category $category
*
* @param Category $category
*
* @return \Illuminate\Http\JsonResponse
* @return \Symfony\Component\HttpFoundation\Response
*/
public function categoryOverviewChart(Category $category, GChart $chart)
public function categoryOverviewChart(GChart $chart, CategoryRepositoryInterface $repository, Category $category)
{
// oldest transaction in category:
/** @var TransactionJournal $first */
$first = $category->transactionjournals()->orderBy('date', 'ASC')->first();
$start = $first->date;
$start = $repository->getFirstActivityDate($category);
/** @var Preference $range */
$range = Preferences::get('viewRange', '1M');
// jump to start of week / month / year / etc (TODO).
@@ -479,13 +429,12 @@ class GoogleChartController extends Controller
while ($start <= $end) {
$currentEnd = Navigation::endOfPeriod($start, $range->data);
$spent = floatval($category->transactionjournals()->before($currentEnd)->after($start)->lessThan(0)->sum('amount')) * -1;
$spent = $repository->spentInPeriodSum($category, $start, $currentEnd);
$chart->addRow(clone $start, $spent);
$start = Navigation::addPeriod($start, $range->data, 0);
}
$chart->generate();
return Response::json($chart->getData());
@@ -494,22 +443,21 @@ class GoogleChartController extends Controller
}
/**
* @param GChart $chart
* @param CategoryRepositoryInterface $repository
* @param Category $category
*
* @param Category $category
*
* @return \Illuminate\Http\JsonResponse
* @return \Symfony\Component\HttpFoundation\Response
*/
public function categoryPeriodChart(Category $category, GChart $chart)
public function categoryPeriodChart(GChart $chart, CategoryRepositoryInterface $repository, Category $category)
{
// oldest transaction in category:
/** @var TransactionJournal $first */
$start = Session::get('start');
$start = clone Session::get('start', Carbon::now()->startOfMonth());
$chart->addColumn('Period', 'date');
$chart->addColumn('Spent', 'number');
$end = Session::get('end');
$end = Session::get('end', Carbon::now()->endOfMonth());
while ($start <= $end) {
$spent = floatval($category->transactionjournals()->onDate($start)->lessThan(0)->sum('amount')) * -1;
$spent = $repository->spentOnDaySum($category, $start);
$chart->addRow(clone $start, $spent);
$start->addDay();
}
@@ -523,19 +471,24 @@ class GoogleChartController extends Controller
/**
* @param PiggyBank $piggyBank
* @param GChart $chart
* @param PiggyBankRepositoryInterface $repository
* @param PiggyBank $piggyBank
*
* @return \Illuminate\Http\JsonResponse
* @return \Symfony\Component\HttpFoundation\Response
*/
public function piggyBankHistory(PiggyBank $piggyBank, GChart $chart)
public function piggyBankHistory(GChart $chart, PiggyBankRepositoryInterface $repository, PiggyBank $piggyBank)
{
$chart->addColumn('Date', 'date');
$chart->addColumn('Balance', 'number');
$set = \DB::table('piggy_bank_events')->where('piggy_bank_id', $piggyBank->id)->groupBy('date')->get(['date', DB::Raw('SUM(`amount`) AS `sum`')]);
/** @var Collection $set */
$set = $repository->getEventSummarySet($piggyBank);
$sum = 0;
foreach ($set as $entry) {
$chart->addRow(new Carbon($entry->date), floatval($entry->sum));
$sum += floatval($entry->sum);
$chart->addRow(new Carbon($entry->date), $sum);
}
$chart->generate();
@@ -545,18 +498,15 @@ class GoogleChartController extends Controller
}
/**
* @param GChart $chart
* @param ReportQueryInterface $query
* @param $year
*
* @param $year
*
* @return \Illuminate\Http\JsonResponse
* @return \Symfony\Component\HttpFoundation\Response
*/
public function yearInExp($year, GChart $chart, ReportQueryInterface $query)
public function yearInExp(GChart $chart, ReportQueryInterface $query, $year)
{
try {
$start = new Carbon('01-01-' . $year);
} catch (Exception $e) {
return view('error')->with('message', 'Invalid year.');
}
$start = new Carbon('01-01-' . $year);
$chart->addColumn('Month', 'date');
$chart->addColumn('Income', 'number');
$chart->addColumn('Expenses', 'number');
@@ -571,19 +521,9 @@ class GoogleChartController extends Controller
while ($start < $end) {
$currentEnd = clone $start;
$currentEnd->endOfMonth();
// total income:
$income = $query->incomeByPeriod($start, $currentEnd, $showSharedReports);
$incomeSum = 0;
foreach ($income as $entry) {
$incomeSum += floatval($entry->amount);
}
// total expenses:
$expense = $query->journalsByExpenseAccount($start, $currentEnd, $showSharedReports);
$expenseSum = 0;
foreach ($expense as $entry) {
$expenseSum += floatval($entry->amount);
}
// total income && total expenses:
$incomeSum = floatval($query->incomeByPeriod($start, $currentEnd, $showSharedReports)->sum('queryAmount'));
$expenseSum = floatval($query->journalsByExpenseAccount($start, $currentEnd, $showSharedReports)->sum('queryAmount'));
$chart->addRow(clone $start, $incomeSum, $expenseSum);
$start->addMonth();
@@ -597,18 +537,15 @@ class GoogleChartController extends Controller
}
/**
* @param GChart $chart
* @param ReportQueryInterface $query
* @param $year
*
* @param $year
*
* @return \Illuminate\Http\JsonResponse
* @return \Symfony\Component\HttpFoundation\Response
*/
public function yearInExpSum($year, GChart $chart, ReportQueryInterface $query)
public function yearInExpSum(GChart $chart, ReportQueryInterface $query, $year)
{
try {
$start = new Carbon('01-01-' . $year);
} catch (Exception $e) {
return view('error')->with('message', 'Invalid year.');
}
$start = new Carbon('01-01-' . $year);
$chart->addColumn('Summary', 'string');
$chart->addColumn('Income', 'number');
$chart->addColumn('Expenses', 'number');
@@ -626,18 +563,9 @@ class GoogleChartController extends Controller
$currentEnd = clone $start;
$currentEnd->endOfMonth();
// total income:
$incomeResult = $query->incomeByPeriod($start, $currentEnd, $showSharedReports);
$incomeSum = 0;
foreach ($incomeResult as $entry) {
$incomeSum += floatval($entry->amount);
}
$incomeSum = floatval($query->incomeByPeriod($start, $currentEnd, $showSharedReports)->sum('queryAmount'));
// total expenses:
$expenseResult = $query->journalsByExpenseAccount($start, $currentEnd, $showSharedReports);
$expenseSum = 0;
foreach ($expenseResult as $entry) {
$expenseSum += floatval($entry->amount);
}
$expenseSum = floatval($query->journalsByExpenseAccount($start, $currentEnd, $showSharedReports)->sum('queryAmount'));
$income += $incomeSum;
$expense += $expenseSum;

View File

@@ -1,11 +1,8 @@
<?php namespace FireflyIII\Http\Controllers;
use Cache;
use ErrorException;
use FireflyIII\Http\Requests;
use League\CommonMark\CommonMarkConverter;
use FireflyIII\Helpers\Help\HelpInterface;
use Log;
use Response;
use Route;
/**
* Class HelpController
@@ -16,77 +13,39 @@ class HelpController extends Controller
{
/**
* @param $route
* @param HelpInterface $help
* @param $route
*
* @return \Illuminate\Http\JsonResponse
*/
public function show($route)
public function show(HelpInterface $help, $route)
{
$content = [
'text' => '<p>There is no help for this route!</p>',
'title' => 'Help',
];
if (!Route::has($route)) {
\Log::error('No such route: ' . $route);
if (!$help->hasRoute($route)) {
Log::error('No such route: ' . $route);
return Response::json($content);
}
if ($this->_inCache($route)) {
if ($help->inCache($route)) {
$content = [
'text' => Cache::get('help.' . $route . '.text'),
'title' => Cache::get('help.' . $route . '.title'),
'text' => $help->getFromCache('help.' . $route . '.text'),
'title' => $help->getFromCache('help.' . $route . '.title'),
];
return Response::json($content);
}
$content = $this->_getFromGithub($route);
$content = $help->getFromGithub($route);
Cache::put('help.' . $route . '.text', $content['text'], 10080); // a week.
Cache::put('help.' . $route . '.title', $content['title'], 10080);
$help->putInCache($route, $content);
return Response::json($content);
}
/**
* @param $route
*
* @return bool
*/
protected function _inCache($route)
{
return Cache::has('help.' . $route . '.title') && Cache::has('help.' . $route . '.text');
}
/**
* @param $route
*
* @return array
*/
protected function _getFromGithub($route)
{
$uri = 'https://raw.githubusercontent.com/JC5/firefly-iii-help/master/' . e($route) . '.md';
$content = [
'text' => '<p>There is no help for this route!</p>',
'title' => $route,
];
try {
$content['text'] = file_get_contents($uri);
} catch (ErrorException $e) {
\Log::error(trim($e->getMessage()));
}
if (strlen(trim($content['text'])) == 0) {
$content['text'] = '<p>There is no help for this route.</p>';
}
$converter = new CommonMarkConverter();
$content['text'] = $converter->convertToHtml($content['text']);
return $content;
}
}

View File

@@ -1,13 +1,13 @@
<?php namespace FireflyIII\Http\Controllers;
use Auth;
use Cache;
use Carbon\Carbon;
use Config;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use Input;
use Preferences;
use Redirect;
use Session;
use Steam;
/**
* Class HomeController
@@ -17,13 +17,6 @@ use Session;
class HomeController extends Controller
{
/**
*
*/
public function __construct()
{
}
public function dateRange()
{
$start = new Carbon(Input::get('start'));
@@ -44,26 +37,47 @@ class HomeController extends Controller
*/
public function flush()
{
Cache::flush();
Session::clear();
return Redirect::route('index');
}
/**
* @param AccountRepositoryInterface $repository
*
* @return \Illuminate\View\View
*/
public function index(AccountRepositoryInterface $repository)
{
$count = $repository->countAssetAccounts();
$title = 'Firefly';
$subTitle = 'What\'s playing?';
$mainTitleIcon = 'fa-fire';
$transactions = [];
$frontPage = Preferences::get('frontPageAccounts', []);
$start = Session::get('start', Carbon::now()->startOfMonth());
$end = Session::get('end', Carbon::now()->endOfMonth());
$accounts = $repository->getFrontpageAccounts($frontPage);
$types = Config::get('firefly.accountTypesByIdentifier.asset');
$count = $repository->countAccounts($types);
$title = 'Firefly';
$subTitle = 'What\'s playing?';
$mainTitleIcon = 'fa-fire';
$transactions = [];
$frontPage = Preferences::get('frontPageAccounts', []);
$start = Session::get('start', Carbon::now()->startOfMonth());
$end = Session::get('end', Carbon::now()->endOfMonth());
$accounts = $repository->getFrontpageAccounts($frontPage);
$savings = $repository->getSavingsAccounts();
$piggyBankAccounts = $repository->getPiggyBankAccounts();
$savingsTotal = 0;
foreach ($savings as $savingAccount) {
$savingsTotal += Steam::balance($savingAccount, $end);
}
// check if all books are correct.
$sum = $repository->sumOfEverything();
if ($sum != 0) {
Session::flash(
'error', 'Your transactions are unbalanced. This means a'
. ' withdrawal, deposit or transfer was not stored properly. '
. 'Please check your accounts and transactions for errors.'
);
}
foreach ($accounts as $account) {
$set = $repository->getFrontpageTransactions($account, $start, $end);
@@ -72,9 +86,7 @@ class HomeController extends Controller
}
}
// var_dump($transactions);
return view('index', compact('count', 'title', 'subTitle', 'mainTitleIcon', 'transactions'));
return view('index', compact('count', 'title', 'savings', 'subTitle', 'mainTitleIcon', 'transactions', 'savingsTotal', 'piggyBankAccounts'));
}

View File

@@ -1,15 +1,21 @@
<?php namespace FireflyIII\Http\Controllers;
use Amount;
use Auth;
use DB;
use FireflyIII\Http\Requests;
use Carbon\Carbon;
use FireflyIII\Helpers\Report\ReportQueryInterface;
use FireflyIII\Models\Account;
use FireflyIII\Models\Bill;
use FireflyIII\Models\Preference;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Bill\BillRepositoryInterface;
use Input;
use FireflyIII\Repositories\Category\CategoryRepositoryInterface;
use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
use FireflyIII\Repositories\Tag\TagRepositoryInterface;
use Illuminate\Support\Collection;
use Preferences;
use Response;
use Session;
use Steam;
/**
* Class JsonController
@@ -21,105 +27,141 @@ class JsonController extends Controller
/**
* @param BillRepositoryInterface $repository
*
* @param AccountRepositoryInterface $accountRepository
*
* @return \Symfony\Component\HttpFoundation\Response
*/
public function box(BillRepositoryInterface $repository)
public function boxBillsPaid(BillRepositoryInterface $repository, AccountRepositoryInterface $accountRepository)
{
$start = Session::get('start', Carbon::now()->startOfMonth());
$end = Session::get('end', Carbon::now()->endOfMonth());
$amount = 0;
$start = Session::get('start');
$end = Session::get('end');
$box = 'empty';
switch (Input::get('box')) {
case 'in':
$box = Input::get('box');
$in = Auth::user()->transactionjournals()
->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id')
->before($end)
->after($start)
->transactionTypes(['Deposit'])
->where('transactions.amount', '>', 0)
->first([DB::Raw('SUM(transactions.amount) as `amount`')]);
if (!is_null($in)) {
$amount = floatval($in->amount);
}
break;
case 'out':
$box = Input::get('box');
$in = Auth::user()->transactionjournals()
->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id')
->before($end)
->after($start)
->transactionTypes(['Withdrawal'])
->where('transactions.amount', '>', 0)
->first([DB::Raw('SUM(transactions.amount) as `amount`')]);
if (!is_null($in)) {
$amount = floatval($in->amount);
}
// these two functions are the same as the chart TODO
$bills = $repository->getActiveBills();
break;
case 'bills-unpaid':
$box = 'bills-unpaid';
$bills = Auth::user()->bills()->where('active', 1)->get();
/** @var Bill $bill */
foreach ($bills as $bill) {
$ranges = $repository->getRanges($bill, $start, $end);
/** @var Bill $bill */
foreach ($bills as $bill) {
$ranges = $repository->getRanges($bill, $start, $end);
foreach ($ranges as $range) {
// paid a bill in this range?
$amount += $repository->getJournalsInRange($bill, $range['start'], $range['end'])->sum('amount');
}
}
unset($ranges, $bill, $range, $bills);
foreach ($ranges as $range) {
// paid a bill in this range?
$count = $bill->transactionjournals()->before($range['end'])->after($range['start'])->count();
if ($count == 0) {
$amount += floatval($bill->amount_max + $bill->amount_min / 2);
}
}
}
break;
case 'bills-paid':
$box = 'bills-paid';
// these two functions are the same as the chart TODO
$bills = Auth::user()->bills()->where('active', 1)->get();
/** @var Bill $bill */
foreach ($bills as $bill) {
$ranges = $repository->getRanges($bill, $start, $end);
foreach ($ranges as $range) {
// paid a bill in this range?
$count = $bill->transactionjournals()->before($range['end'])->after($range['start'])->count();
if ($count != 0) {
$journal = $bill->transactionjournals()->with('transactions')->before($range['end'])->after($range['start'])->first();
$paid['items'][] = $journal->description;
$currentAmount = 0;
foreach ($journal->transactions as $t) {
if (floatval($t->amount) > 0) {
$currentAmount = floatval($t->amount);
}
}
$amount += $currentAmount;
}
}
}
/**
* Find credit card accounts and possibly unpaid credit card bills.
*/
$creditCards = $accountRepository->getCreditCards();
// if the balance is not zero, the monthly payment is still underway.
/** @var Account $creditCard */
foreach ($creditCards as $creditCard) {
$balance = Steam::balance($creditCard, null, true);
if ($balance == 0) {
// find a transfer TO the credit card which should account for
// anything paid. If not, the CC is not yet used.
$amount += $accountRepository->getTransfersInRange($creditCard, $start, $end)->sum('amount');
}
}
return Response::json(['box' => $box, 'amount' => Amount::format($amount, false), 'amount_raw' => $amount]);
return Response::json(['box' => 'bills-paid', 'amount' => Amount::format($amount, false), 'amount_raw' => $amount]);
}
/**
* @param BillRepositoryInterface $repository
* @param AccountRepositoryInterface $accountRepository
*
* @return \Symfony\Component\HttpFoundation\Response
*/
public function boxBillsUnpaid(BillRepositoryInterface $repository, AccountRepositoryInterface $accountRepository)
{
$amount = 0;
$start = Session::get('start', Carbon::now()->startOfMonth());
$end = Session::get('end', Carbon::now()->endOfMonth());
$bills = $repository->getActiveBills();
$unpaid = new Collection; // bills
/** @var Bill $bill */
foreach ($bills as $bill) {
$ranges = $repository->getRanges($bill, $start, $end);
foreach ($ranges as $range) {
$journals = $repository->getJournalsInRange($bill, $range['start'], $range['end']);
if ($journals->count() == 0) {
$unpaid->push([$bill, $range['start']]);
}
}
}
unset($bill, $bills, $range, $ranges);
$creditCards = $accountRepository->getCreditCards();
foreach ($creditCards as $creditCard) {
$balance = Steam::balance($creditCard, null, true);
$date = new Carbon($creditCard->getMeta('ccMonthlyPaymentDate'));
if ($balance < 0) {
// unpaid! create a fake bill that matches the amount.
$description = $creditCard->name;
$fakeAmount = $balance * -1;
$fakeBill = $repository->createFakeBill($description, $date, $fakeAmount);
$unpaid->push([$fakeBill, $date]);
}
}
/** @var Bill $entry */
foreach ($unpaid as $entry) {
$current = ($entry[0]->amount_max + $entry[0]->amount_min) / 2;
$amount += $current;
}
return Response::json(['box' => 'bills-unpaid', 'amount' => Amount::format($amount, false), 'amount_raw' => $amount]);
}
/**
* @param ReportQueryInterface $reportQuery
*
* @return \Symfony\Component\HttpFoundation\Response
*/
public function boxIn(ReportQueryInterface $reportQuery)
{
$start = Session::get('start', Carbon::now()->startOfMonth());
$end = Session::get('end', Carbon::now()->endOfMonth());
$amount = $reportQuery->incomeByPeriod($start, $end, true)->sum('queryAmount');
return Response::json(['box' => 'in', 'amount' => Amount::format($amount, false), 'amount_raw' => $amount]);
}
/**
* @param ReportQueryInterface $reportQuery
*
* @return \Symfony\Component\HttpFoundation\Response
*/
public function boxOut(ReportQueryInterface $reportQuery)
{
$start = Session::get('start', Carbon::now()->startOfMonth());
$end = Session::get('end', Carbon::now()->endOfMonth());
$amount = $reportQuery->journalsByExpenseAccount($start, $end, true)->sum('queryAmount');
return Response::json(['box' => 'out', 'amount' => Amount::format($amount, false), 'amount_raw' => $amount]);
}
/**
* Returns a list of categories.
*
* @param CategoryRepositoryInterface $repository
*
* @return \Illuminate\Http\JsonResponse
*/
public function categories()
public function categories(CategoryRepositoryInterface $repository)
{
$list = Auth::user()->categories()->orderBy('name', 'ASC')->get();
$list = $repository->getCategories();
$return = [];
foreach ($list as $entry) {
$return[] = $entry->name;
}
sort($return);
return Response::json($return);
}
@@ -127,11 +169,13 @@ class JsonController extends Controller
/**
* Returns a JSON list of all beneficiaries.
*
* @param AccountRepositoryInterface $accountRepository
*
* @return \Illuminate\Http\JsonResponse
*/
public function expenseAccounts()
public function expenseAccounts(AccountRepositoryInterface $accountRepository)
{
$list = Auth::user()->accounts()->orderBy('accounts.name', 'ASC')->accountTypeIn(['Expense account', 'Beneficiary account'])->get();
$list = $accountRepository->getAccounts(['Expense account', 'Beneficiary account']);
$return = [];
foreach ($list as $entry) {
$return[] = $entry->name;
@@ -142,11 +186,13 @@ class JsonController extends Controller
}
/**
* @param AccountRepositoryInterface $accountRepository
*
* @return \Illuminate\Http\JsonResponse
*/
public function revenueAccounts()
public function revenueAccounts(AccountRepositoryInterface $accountRepository)
{
$list = Auth::user()->accounts()->accountTypeIn(['Revenue account'])->orderBy('accounts.name', 'ASC')->get(['accounts.*']);
$list = $accountRepository->getAccounts(['Revenue account']);
$return = [];
foreach ($list as $entry) {
$return[] = $entry->name;
@@ -156,6 +202,20 @@ class JsonController extends Controller
}
/**
* @return \Symfony\Component\HttpFoundation\Response
*/
public function setSharedReports()
{
/** @var Preference $pref */
$pref = Preferences::get('showSharedReports', false);
$new = !$pref->data;
Preferences::set('showSharedReports', $new);
return Response::json(['value' => $new]);
}
/**
* @return \Symfony\Component\HttpFoundation\Response
*/
@@ -167,16 +227,46 @@ class JsonController extends Controller
}
/**
* Returns a JSON list of all beneficiaries.
*
* @param TagRepositoryInterface $tagRepository
*
* @return \Illuminate\Http\JsonResponse
*/
public function tags(TagRepositoryInterface $tagRepository)
{
$list = $tagRepository->get();
$return = [];
foreach ($list as $entry) {
$return[] = $entry->tag;
}
return Response::json($return);
}
/**
* @param JournalRepositoryInterface $repository
* @param $what
*
* @return \Symfony\Component\HttpFoundation\Response
*/
public function setSharedReports()
public function transactionJournals(JournalRepositoryInterface $repository, $what)
{
$pref = Preferences::get('showSharedReports', false);
$new = !$pref->data;
Preferences::set('showSharedReports', $new);
$descriptions = [];
$dbType = $repository->getTransactionType($what);
$journals = $repository->getJournalsOfType($dbType);
foreach ($journals as $j) {
$descriptions[] = $j->description;
}
$descriptions = array_unique($descriptions);
sort($descriptions);
return Response::json($descriptions);
return Response::json(['value' => $new]);
}
}

View File

@@ -1,15 +1,12 @@
<?php namespace FireflyIII\Http\Controllers;
use Amount;
use Auth;
use Carbon\Carbon;
use Config;
use ExpandedForm;
use FireflyIII\Http\Requests;
use FireflyIII\Http\Requests\PiggyBankFormRequest;
use FireflyIII\Models\Account;
use FireflyIII\Models\PiggyBank;
use FireflyIII\Models\PiggyBankEvent;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface;
use Illuminate\Support\Collection;
@@ -17,6 +14,7 @@ use Input;
use Redirect;
use Session;
use Steam;
use URL;
use View;
/**
@@ -32,6 +30,7 @@ class PiggyBankController extends Controller
*/
public function __construct()
{
parent::__construct();
View::share('title', 'Piggy banks');
View::share('mainTitleIcon', 'fa-sort-amount-asc');
}
@@ -39,36 +38,40 @@ class PiggyBankController extends Controller
/**
* Add money to piggy bank
*
* @param PiggyBank $piggyBank
* @param AccountRepositoryInterface $repository
* @param PiggyBank $piggyBank
*
* @return $this
*/
public function add(PiggyBank $piggyBank, AccountRepositoryInterface $repository)
public function add(AccountRepositoryInterface $repository, PiggyBank $piggyBank)
{
$leftOnAccount = $repository->leftOnAccount($piggyBank->account);
$savedSoFar = $piggyBank->currentRelevantRep()->currentamount;
$leftToSave = $piggyBank->targetamount - $savedSoFar;
$maxAmount = min($leftOnAccount, $leftToSave);
\Log::debug('Now going to view for piggy bank #' . $piggyBank->id . ' (' . $piggyBank->name . ')');
return view('piggy-banks.add', compact('piggyBank', 'maxAmount'));
}
/**
* @param AccountRepositoryInterface $repository
*
* @return mixed
*/
public function create()
public function create(AccountRepositoryInterface $repository)
{
$periods = Config::get('firefly.piggy_bank_periods');
$accounts = ExpandedForm::makeSelectList(
Auth::user()->accounts()->orderBy('accounts.name', 'ASC')->accountTypeIn(['Default account', 'Asset account'])->get(['accounts.*'])
);
$accounts = ExpandedForm::makeSelectList($repository->getAccounts(['Default account', 'Asset account']));
$subTitle = 'Create new piggy bank';
$subTitleIcon = 'fa-plus';
// put previous url in session if not redirect from store (not "create another").
if (Session::get('piggy-banks.create.fromStore') !== true) {
Session::put('piggy-banks.create.url', URL::previous());
}
Session::forget('piggy-banks.create.fromStore');
return view('piggy-banks.create', compact('accounts', 'periods', 'subTitle', 'subTitleIcon'));
}
@@ -81,37 +84,39 @@ class PiggyBankController extends Controller
{
$subTitle = 'Delete "' . e($piggyBank->name) . '"';
// put previous url in session
Session::put('piggy-banks.delete.url', URL::previous());
return view('piggy-banks.delete', compact('piggyBank', 'subTitle'));
}
/**
* @param PiggyBank $piggyBank
* @param PiggyBankRepositoryInterface $repository
* @param PiggyBank $piggyBank
*
* @return \Illuminate\Http\RedirectResponse
*/
public function destroy(PiggyBank $piggyBank)
public function destroy(PiggyBankRepositoryInterface $repository, PiggyBank $piggyBank)
{
Session::flash('success', 'Piggy bank "' . e($piggyBank->name) . '" deleted.');
$piggyBank->delete();
return Redirect::route('piggy-banks.index');
Session::flash('success', 'Piggy bank "' . e($piggyBank->name) . '" deleted.');
$repository->destroy($piggyBank);
return Redirect::to(Session::get('piggy-banks.delete.url'));
}
/**
* @SuppressWarnings("CyclomaticComplexity") // It's exactly 5. So I don't mind.
* @param AccountRepositoryInterface $repository
* @param PiggyBank $piggyBank
*
* @param PiggyBank $piggyBank
*
* @return $this
* @return View
*/
public function edit(PiggyBank $piggyBank)
public function edit(AccountRepositoryInterface $repository, PiggyBank $piggyBank)
{
$periods = Config::get('firefly.piggy_bank_periods');
$accounts = ExpandedForm::makeSelectList(
Auth::user()->accounts()->orderBy('accounts.name', 'ASC')->accountTypeIn(['Default account', 'Asset account'])->get(['accounts.*'])
);
$accounts = ExpandedForm::makeSelectList($repository->getAccounts(['Default account', 'Asset account']));
$subTitle = 'Edit piggy bank "' . e($piggyBank->name) . '"';
$subTitleIcon = 'fa-pencil';
@@ -133,23 +138,31 @@ class PiggyBankController extends Controller
];
Session::flash('preFilled', $preFilled);
// put previous url in session if not redirect from store (not "return_to_edit").
if (Session::get('piggy-banks.edit.fromUpdate') !== true) {
Session::put('piggy-banks.edit.url', URL::previous());
}
Session::forget('piggy-banks.edit.fromUpdate');
return view('piggy-banks.edit', compact('subTitle', 'subTitleIcon', 'piggyBank', 'accounts', 'periods', 'preFilled'));
}
/**
* @return $this
* @param AccountRepositoryInterface $repository
* @param PiggyBankRepositoryInterface $piggyRepository
*
* @return View
*/
public function index(AccountRepositoryInterface $repository)
public function index(AccountRepositoryInterface $repository, PiggyBankRepositoryInterface $piggyRepository)
{
/** @var Collection $piggyBanks */
$piggyBanks = Auth::user()->piggyBanks()->where('repeats', 0)->get();
$piggyBanks = $piggyRepository->getPiggyBanks();
$accounts = [];
/** @var PiggyBank $piggyBank */
foreach ($piggyBanks as $piggyBank) {
$piggyBank->savedSoFar = floatval($piggyBank->currentRelevantRep()->currentamount);
$piggyBank->percentage = intval($piggyBank->savedSoFar / $piggyBank->targetamount * 100);
$piggyBank->percentage = $piggyBank->savedSoFar != 0 ? intval($piggyBank->savedSoFar / $piggyBank->targetamount * 100) : 0;
$piggyBank->leftToSave = $piggyBank->targetamount - $piggyBank->savedSoFar;
/*
@@ -159,7 +172,7 @@ class PiggyBankController extends Controller
if (!isset($accounts[$account->id])) {
$accounts[$account->id] = [
'name' => $account->name,
'balance' => Steam::balance($account),
'balance' => Steam::balance($account, null, true),
'leftForPiggyBanks' => $repository->leftOnAccount($account),
'sumOfSaved' => $piggyBank->savedSoFar,
'sumOfTargets' => floatval($piggyBank->targetamount),
@@ -175,15 +188,31 @@ class PiggyBankController extends Controller
return view('piggy-banks.index', compact('piggyBanks', 'accounts'));
}
/**
* @param PiggyBankRepositoryInterface $repository
*/
public function order(PiggyBankRepositoryInterface $repository)
{
$data = Input::get('order');
// set all users piggy banks to zero:
$repository->reset();
if (is_array($data)) {
foreach ($data as $order => $id) {
$repository->setOrder(intval($id), (intval($order) + 1));
}
}
}
/**
* POST add money to piggy bank
*
* @param PiggyBank $piggyBank
* @param PiggyBankRepositoryInterface $repository
* @param AccountRepositoryInterface $accounts
* @param PiggyBank $piggyBank
*
* @return \Illuminate\Http\RedirectResponse
*/
public function postAdd(PiggyBank $piggyBank, PiggyBankRepositoryInterface $repository, AccountRepositoryInterface $accounts)
public function postAdd(PiggyBankRepositoryInterface $repository, AccountRepositoryInterface $accounts, PiggyBank $piggyBank)
{
$amount = round(floatval(Input::get('amount')), 2);
$leftOnAccount = $accounts->leftOnAccount($piggyBank->account);
@@ -196,8 +225,8 @@ class PiggyBankController extends Controller
$repetition->currentamount += $amount;
$repetition->save();
// create event.
PiggyBankEvent::create(['date' => Carbon::now(), 'amount' => $amount, 'piggy_bank_id' => $piggyBank->id]);
// create event
$repository->createEvent($piggyBank, $amount);
/*
* Create event!
@@ -213,11 +242,12 @@ class PiggyBankController extends Controller
}
/**
* @param PiggyBank $piggyBank
* @param PiggyBankRepositoryInterface $repository
* @param PiggyBank $piggyBank
*
* @return \Illuminate\Http\RedirectResponse
*/
public function postRemove(PiggyBank $piggyBank)
public function postRemove(PiggyBankRepositoryInterface $repository, PiggyBank $piggyBank)
{
$amount = floatval(Input::get('amount'));
@@ -228,12 +258,8 @@ class PiggyBankController extends Controller
$repetition->currentamount -= $amount;
$repetition->save();
PiggyBankEvent::create(['date' => Carbon::now(), 'amount' => $amount * -1, 'piggy_bank_id' => $piggyBank->id]);
/*
* Create event!
*/
//Event::fire('piggy_bank.removeMoney', [$piggyBank, $amount]); // new and used.
// create event
$repository->createEvent($piggyBank, $amount * -1);
Session::flash('success', 'Removed ' . Amount::format($amount, false) . ' from "' . e($piggyBank->name) . '".');
} else {
@@ -246,7 +272,6 @@ class PiggyBankController extends Controller
/**
* @param PiggyBank $piggyBank
*
* @SuppressWarnings("Unused")
*
* @return \Illuminate\View\View
*/
@@ -256,14 +281,14 @@ class PiggyBankController extends Controller
}
/**
* @param PiggyBank $piggyBank
* @param PiggyBankRepositoryInterface $repository
* @param PiggyBank $piggyBank
*
* @return $this
* @return View
*/
public function show(PiggyBank $piggyBank)
public function show(PiggyBankRepositoryInterface $repository, PiggyBank $piggyBank)
{
$events = $piggyBank->piggyBankEvents()->orderBy('date', 'DESC')->orderBy('id', 'DESC')->get();
$events = $repository->getEvents($piggyBank);
/*
* Number of reminders:
@@ -276,12 +301,15 @@ class PiggyBankController extends Controller
}
/**
* @param PiggyBankFormRequest $request
* @param PiggyBankRepositoryInterface $repository
*
* @return $this|\Illuminate\Http\RedirectResponse
*/
public function store(PiggyBankFormRequest $request, PiggyBankRepositoryInterface $repository)
{
$piggyBankData = [
'repeats' => false,
'name' => $request->get('name'),
'startdate' => new Carbon,
'account_id' => intval($request->get('account_id')),
@@ -296,24 +324,26 @@ class PiggyBankController extends Controller
Session::flash('success', 'Stored piggy bank "' . e($piggyBank->name) . '".');
if (intval(Input::get('create_another')) === 1) {
Session::put('piggy-banks.create.fromStore', true);
return Redirect::route('piggy-banks.create')->withInput();
}
return Redirect::route('piggy-banks.index');
// redirect to previous URL.
return Redirect::to(Session::get('piggy-banks.create.url'));
}
/**
* @param PiggyBank $piggyBank
*
* @SuppressWarnings("CyclomaticComplexity") // It's exactly 5. So I don't mind.
* @param PiggyBankRepositoryInterface $repository
* @param PiggyBankFormRequest $request
* @param PiggyBank $piggyBank
*
* @return $this
*/
public function update(PiggyBank $piggyBank, PiggyBankRepositoryInterface $repository, PiggyBankFormRequest $request)
public function update(PiggyBankRepositoryInterface $repository, PiggyBankFormRequest $request, PiggyBank $piggyBank)
{
$piggyBankData = [
'repeats' => false,
'name' => $request->get('name'),
'startdate' => is_null($piggyBank->startdate) ? $piggyBank->created_at : $piggyBank->startdate,
'account_id' => intval($request->get('account_id')),
@@ -323,17 +353,19 @@ class PiggyBankController extends Controller
'remind_me' => $request->get('remind_me')
];
$piggyBank = $repository->update($piggyBank, $piggyBankData);
Session::flash('success', 'Updated piggy bank "' . e($piggyBank->name) . '".');
if (intval(Input::get('return_to_edit')) === 1) {
Session::put('piggy-banks.edit.fromUpdate', true);
return Redirect::route('piggy-banks.edit', $piggyBank->id);
}
return Redirect::route('piggy-banks.index');
// redirect to previous URL.
return Redirect::to(Session::get('piggy-banks.edit.url'));
}

View File

@@ -1,7 +1,6 @@
<?php namespace FireflyIII\Http\Controllers;
use Auth;
use FireflyIII\Http\Requests;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use Input;
use Preferences;
use Redirect;
@@ -21,26 +20,26 @@ class PreferencesController extends Controller
*/
public function __construct()
{
parent::__construct();
View::share('title', 'Preferences');
View::share('mainTitleIcon', 'fa-gear');
}
/**
* @param AccountRepositoryInterface $repository
*
* @return $this|\Illuminate\View\View
*/
public function index()
public function index(AccountRepositoryInterface $repository)
{
$accounts = Auth::user()->accounts()->accountTypeIn(['Default account', 'Asset account'])->orderBy('accounts.name', 'ASC')->get(['accounts.*']);
$viewRange = Preferences::get('viewRange', '1M');
$viewRangeValue = $viewRange->data;
$frontPage = Preferences::get('frontPageAccounts', []);
$budgetMax = Preferences::get('budgetMaximum', 1000);
$budgetMaximum = $budgetMax->data;
$accounts = $repository->getAccounts(['Default account', 'Asset account']);
$viewRangePref = Preferences::get('viewRange', '1M');
$viewRange = $viewRangePref->data;
$frontPageAccounts = Preferences::get('frontPageAccounts', []);
$budgetMax = Preferences::get('budgetMaximum', 1000);
$budgetMaximum = $budgetMax->data;
return view('preferences.index', compact('budgetMaximum'))->with('accounts', $accounts)->with('frontPageAccounts', $frontPage)->with(
'viewRange', $viewRangeValue
);
return view('preferences.index', compact('budgetMaximum', 'accounts', 'frontPageAccounts', 'viewRange'));
}
/**

View File

@@ -2,6 +2,7 @@
use Auth;
use FireflyIII\Http\Requests;
use FireflyIII\Http\Requests\DeleteAccountFormRequest;
use FireflyIII\Http\Requests\ProfileFormRequest;
use Hash;
use Redirect;
@@ -25,6 +26,16 @@ class ProfileController extends Controller
);
}
/**
* @return \Illuminate\View\View
*/
public function deleteAccount()
{
return view('profile.delete-account')->with('title', Auth::user()->email)->with('subTitle', 'Delete account')->with(
'mainTitleIcon', 'fa-user'
);
}
/**
* @return \Illuminate\View\View
*
@@ -35,6 +46,8 @@ class ProfileController extends Controller
}
/**
* @param ProfileFormRequest $request
*
* @return \Illuminate\Http\RedirectResponse|\Illuminate\View\View
*/
public function postChangePassword(ProfileFormRequest $request)
@@ -45,7 +58,7 @@ class ProfileController extends Controller
return Redirect::route('change-password');
}
$result = $this->_validatePassword($request->get('current_password'), $request->get('new_password'), $request->get('new_password_confirmation'));
$result = $this->validatePassword($request->get('current_password'), $request->get('new_password'));
if (!($result === true)) {
Session::flash('error', $result);
@@ -62,29 +75,43 @@ class ProfileController extends Controller
}
/**
* @SuppressWarnings("CyclomaticComplexity") // It's exactly 5. So I don't mind.
*
* @param string $old
* @param string $new1
* @param string $new2
*
* @return string|bool
*/
protected function _validatePassword($old, $new1, $new2)
protected function validatePassword($old, $new1)
{
if (strlen($new1) == 0 || strlen($new2) == 0) {
return 'Do fill in a password!';
}
if ($new1 == $old) {
return 'The idea is to change your password.';
}
if ($new1 !== $new2) {
return 'New passwords do not match!';
}
return true;
}
/**
* @param DeleteAccountFormRequest $request
*
* @return \Illuminate\Http\RedirectResponse
* @throws \Exception
*/
public function postDeleteAccount(DeleteAccountFormRequest $request)
{
// old, new1, new2
if (!Hash::check($request->get('password'), Auth::user()->password)) {
Session::flash('error', 'Invalid password!');
return Redirect::route('delete-account');
}
// DELETE!
Auth::user()->delete();
Session::flush();
return Redirect::route('index');
}
}

View File

@@ -1,177 +0,0 @@
<?php namespace FireflyIII\Http\Controllers;
use Auth;
use FireflyIII\Http\Requests;
use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionGroup;
use FireflyIII\Models\TransactionJournal;
use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
use Illuminate\Support\Collection;
use Input;
use Redirect;
use Response;
use URL;
/**
* Class RelatedController
*
* @package FireflyIII\Http\Controllers
*/
class RelatedController extends Controller
{
/**
*
* @param TransactionJournal $journal
*
* @return \Illuminate\Http\JsonResponse
*/
public function alreadyRelated(TransactionJournal $journal)
{
$ids = [];
/** @var TransactionGroup $group */
foreach ($journal->transactiongroups()->get() as $group) {
/** @var TransactionJournal $loopJournal */
foreach ($group->transactionjournals()->get() as $loopJournal) {
if ($loopJournal->id != $journal->id) {
$ids[] = $loopJournal->id;
}
}
}
$unique = array_unique($ids);
$journals = new Collection;
if (count($unique) > 0) {
$journals = Auth::user()->transactionjournals()->whereIn('id', $unique)->get();
$journals->each(
function (TransactionJournal $journal) {
/** @var Transaction $t */
foreach ($journal->transactions()->get() as $t) {
if ($t->amount > 0) {
$journal->amount = $t->amount;
}
}
}
);
}
$parent = $journal;
return view('related.alreadyRelated', compact('parent', 'journals'));
}
/**
* @SuppressWarnings("CyclomaticComplexity") // It's exactly 5. So I don't mind.
*
* @param TransactionJournal $parentJournal
* @param TransactionJournal $childJournal
*
* @return \Illuminate\Http\JsonResponse
* @throws Exception
*/
public function getRemoveRelation(TransactionJournal $parentJournal, TransactionJournal $childJournal)
{
$groups = $parentJournal->transactiongroups()->get();
/** @var TransactionGroup $group */
foreach ($groups as $group) {
foreach ($group->transactionjournals()->get() as $loopJournal) {
if ($loopJournal->id == $childJournal->id) {
// remove from group:
$group->transactionjournals()->detach($childJournal);
}
}
if ($group->transactionjournals()->count() == 1) {
$group->delete();
}
}
return Redirect::to(URL::previous());
}
/**
* @param TransactionJournal $parentJournal
* @param TransactionJournal $childJournal
*
* @return \Illuminate\Http\JsonResponse
*/
public function relate(TransactionJournal $parentJournal, TransactionJournal $childJournal)
{
$group = new TransactionGroup;
$group->relation = 'balance';
$group->user_id = Auth::user()->id;
$group->save();
$group->transactionjournals()->save($parentJournal);
$group->transactionjournals()->save($childJournal);
return Response::json(true);
}
/**
* @param TransactionJournal $journal
*
* @return \Illuminate\View\View
*/
public function related(TransactionJournal $journal)
{
$groups = $journal->transactiongroups()->get();
$members = new Collection;
/** @var TransactionGroup $group */
foreach ($groups as $group) {
/** @var TransactionJournal $loopJournal */
foreach ($group->transactionjournals()->get() as $loopJournal) {
if ($loopJournal->id != $journal->id) {
$members->push($loopJournal);
}
}
}
return view('related.relate', compact('journal', 'members'));
}
/**
* @SuppressWarnings("CyclomaticComplexity") // It's exactly 5. So I don't mind.
*
* @param TransactionJournal $parentJournal
* @param TransactionJournal $childJournal
*
* @return \Illuminate\Http\JsonResponse
* @throws Exception
*/
public function removeRelation(TransactionJournal $parentJournal, TransactionJournal $childJournal)
{
$groups = $parentJournal->transactiongroups()->get();
/** @var TransactionGroup $group */
foreach ($groups as $group) {
foreach ($group->transactionjournals()->get() as $loopJournal) {
if ($loopJournal->id == $childJournal->id) {
// remove from group:
$group->transactionjournals()->detach($childJournal);
}
}
if ($group->transactionjournals()->count() == 1) {
$group->delete();
}
}
return Response::json(true);
}
/**
* @param TransactionJournal $journal
*
* @return \Illuminate\Http\JsonResponse
*/
public function search(TransactionJournal $journal, JournalRepositoryInterface $repository)
{
$search = e(trim(Input::get('searchValue')));
$parent = $journal;
$journals = $repository->searchRelated($search, $journal);
return view('related.searchResult', compact('journals', 'search', 'parent'));
}
}

View File

@@ -1,10 +1,7 @@
<?php namespace FireflyIII\Http\Controllers;
use Auth;
use Carbon\Carbon;
use FireflyIII\Helpers\Reminders\ReminderHelperInterface;
use FireflyIII\Http\Requests;
use FireflyIII\Models\Reminder;
use FireflyIII\Repositories\Reminder\ReminderRepositoryInterface;
use Redirect;
use Session;
use URL;
@@ -20,6 +17,8 @@ class ReminderController extends Controller
/**
* @param Reminder $reminder
*
* @return \Illuminate\Http\RedirectResponse
*/
public function act(Reminder $reminder)
{
@@ -37,6 +36,8 @@ class ReminderController extends Controller
/**
* @param Reminder $reminder
*
* @return \Illuminate\Http\RedirectResponse
*/
public function dismiss(Reminder $reminder)
{
@@ -49,55 +50,18 @@ class ReminderController extends Controller
}
/**
* @param ReminderRepositoryInterface $repository
*
* @return \Illuminate\View\View
*/
public function index(ReminderHelperInterface $helper)
public function index(ReminderRepositoryInterface $repository)
{
$reminders = Auth::user()->reminders()->get();
$reminders->each(
function (Reminder $reminder) use ($helper) {
$reminder->description = $helper->getReminderText($reminder);
}
);
$today = new Carbon;
// active reminders:
$active = $reminders->filter(
function (Reminder $reminder) use ($today) {
if ($reminder->notnow === false && $reminder->active === true && $reminder->startdate <= $today && $reminder->enddate >= $today) {
return $reminder;
}
}
);
// expired reminders:
$expired = $reminders->filter(
function (Reminder $reminder) use ($today) {
if ($reminder->notnow === false && $reminder->active === true && $reminder->startdate > $today || $reminder->enddate < $today) {
return $reminder;
}
}
);
// inactive reminders
$inactive = $reminders->filter(
function (Reminder $reminder) use ($today) {
if ($reminder->active === false) {
return $reminder;
}
}
);
// dismissed reminders
$dismissed = $reminders->filter(
function (Reminder $reminder) use ($today) {
if ($reminder->notnow === true) {
return $reminder;
}
}
);
$active = $repository->getActiveReminders();
$expired = $repository->getExpiredReminders();
$inactive = $repository->getInactiveReminders();
$dismissed = $repository->getDismissedReminders();
$title = 'Reminders';
$mainTitleIcon = 'fa-clock-o';
@@ -107,6 +71,8 @@ class ReminderController extends Controller
/**
* @param Reminder $reminder
*
* @return \Illuminate\View\View
*/
public function show(Reminder $reminder)
{

View File

@@ -1,203 +0,0 @@
<?php namespace FireflyIII\Http\Controllers;
use Auth;
use Carbon\Carbon;
use Config;
use ExpandedForm;
use FireflyIII\Http\Requests;
use FireflyIII\Http\Requests\PiggyBankFormRequest;
use FireflyIII\Models\PiggyBank;
use FireflyIII\Models\PiggyBankRepetition;
use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface;
use Redirect;
use Session;
use View;
/**
* Class RepeatedExpenseController
*
* @package FireflyIII\Http\Controllers
*/
class RepeatedExpenseController extends Controller
{
/**
*
*/
public function __construct()
{
View::share('title', 'Repeated expenses');
View::share('mainTitleIcon', 'fa-rotate-left');
}
/**
* @return $this
*/
public function create()
{
$periods = Config::get('firefly.piggy_bank_periods');
$accounts = ExpandedForm::makeSelectList(
Auth::user()->accounts()->orderBy('accounts.name', 'ASC')->accountTypeIn(['Default account', 'Asset account'])->get(['accounts.*'])
);
return view('repeatedExpense.create', compact('accounts', 'periods'))->with('subTitle', 'Create new repeated expense')->with(
'subTitleIcon', 'fa-plus'
);
}
/**
* @param PiggyBank $repeatedExpense
*
* @return $this
*/
public function delete(PiggyBank $repeatedExpense)
{
$subTitle = 'Delete "' . e($repeatedExpense->name) . '"';
return view('repeatedExpense.delete', compact('repeatedExpense', 'subTitle'));
}
/**
* @param PiggyBank $repeatedExpense
*
* @return \Illuminate\Http\RedirectResponse
*/
public function destroy(PiggyBank $repeatedExpense)
{
Session::flash('success', 'Repeated expense "' . e($repeatedExpense->name) . '" deleted.');
$repeatedExpense->delete();
return Redirect::route('repeated.index');
}
/**
* @param PiggyBank $repeatedExpense
*
* @return $this
*/
public function edit(PiggyBank $repeatedExpense)
{
$periods = Config::get('firefly.piggy_bank_periods');
$accounts = ExpandedForm::makeSelectList(
Auth::user()->accounts()->orderBy('accounts.name', 'ASC')->accountTypeIn(['Default account', 'Asset account'])->get(['accounts.*'])
);
$subTitle = 'Edit repeated expense "' . e($repeatedExpense->name) . '"';
$subTitleIcon = 'fa-pencil';
/*
* Flash some data to fill the form.
*/
$preFilled = ['name' => $repeatedExpense->name,
'account_id' => $repeatedExpense->account_id,
'targetamount' => $repeatedExpense->targetamount,
'reminder_skip' => $repeatedExpense->reminder_skip,
'rep_every' => $repeatedExpense->rep_every,
'rep_times' => $repeatedExpense->rep_times,
'targetdate' => $repeatedExpense->targetdate->format('Y-m-d'),
'reminder' => $repeatedExpense->reminder,
'remind_me' => intval($repeatedExpense->remind_me) == 1 || !is_null($repeatedExpense->reminder) ? true : false
];
Session::flash('preFilled', $preFilled);
return view('repeatedExpense.edit', compact('subTitle', 'subTitleIcon', 'repeatedExpense', 'accounts', 'periods', 'preFilled'));
}
/**
* @return \Illuminate\View\View
*/
public function index()
{
$subTitle = 'Overview';
$expenses = Auth::user()->piggyBanks()->where('repeats', 1)->get();
$expenses->each(
function (PiggyBank $piggyBank) {
$piggyBank->currentRelevantRep();
}
);
return view('repeatedExpense.index', compact('expenses', 'subTitle'));
}
/**
* @param PiggyBank $repeatedExpense
*
* @return \Illuminate\View\View
*/
public function show(PiggyBank $repeatedExpense, PiggyBankRepositoryInterface $repository)
{
$subTitle = $repeatedExpense->name;
$today = Carbon::now();
$repetitions = $repeatedExpense->piggyBankRepetitions()->get();
$repetitions->each(
function (PiggyBankRepetition $repetition) use ($repository) {
$repetition->bars = $repository->calculateParts($repetition);
}
);
return view('repeatedExpense.show', compact('repetitions', 'repeatedExpense', 'today', 'subTitle'));
}
/**
* @SuppressWarnings("CyclomaticComplexity") // It's exactly 5. So I don't mind.
*/
public function store(PiggyBankFormRequest $request, PiggyBankRepositoryInterface $repository)
{
$piggyBankData = [
'repeats' => true,
'name' => $request->get('name'),
'startdate' => new Carbon,
'account_id' => intval($request->get('account_id')),
'targetamount' => floatval($request->get('targetamount')),
'targetdate' => new Carbon($request->get('targetdate')),
'reminder' => $request->get('reminder'),
'skip' => intval($request->get('skip')),
'rep_every' => intval($request->get('rep_every')),
'rep_times' => intval($request->get('rep_times')),
];
$piggyBank = $repository->store($piggyBankData);
Session::flash('success', 'Stored repeated expense "' . e($piggyBank->name) . '".');
return Redirect::route('repeated.index');
}
/**
* @SuppressWarnings("CyclomaticComplexity") // It's exactly 5. So I don't mind.
*
* @param PiggyBank $repeatedExpense
*
* @return $this
*/
public function update(PiggyBank $repeatedExpense, PiggyBankFormRequest $request, PiggyBankRepositoryInterface $repository)
{
$piggyBankData = [
'repeats' => false,
'name' => $request->get('name'),
'account_id' => intval($request->get('account_id')),
'targetamount' => floatval($request->get('targetamount')),
'targetdate' => strlen($request->get('targetdate')) > 0 ? new Carbon($request->get('targetdate')) : null,
'rep_length' => $request->get('rep_length'),
'rep_every' => intval($request->get('rep_every')),
'rep_times' => intval($request->get('rep_times')),
'remind_me' => intval($request->get('remind_me')) == 1 ? true : false,
'reminder' => $request->get('reminder'),
];
$piggyBank = $repository->update($repeatedExpense, $piggyBankData);
Session::flash('success', 'Updated repeated expense "' . e($piggyBank->name) . '".');
return Redirect::route('repeated.index');
}
}

View File

@@ -1,14 +1,11 @@
<?php namespace FireflyIII\Http\Controllers;
use Auth;
use Carbon\Carbon;
use Exception;
use FireflyIII\Helpers\Report\ReportHelperInterface;
use FireflyIII\Helpers\Report\ReportQueryInterface;
use FireflyIII\Http\Requests;
use FireflyIII\Models\Account;
use FireflyIII\Models\Preference;
use FireflyIII\Models\TransactionJournal;
use Illuminate\Database\Query\JoinClause;
use Preferences;
use Session;
use Steam;
@@ -22,11 +19,20 @@ use View;
class ReportController extends Controller
{
/** @var ReportHelperInterface */
protected $helper;
/** @var ReportQueryInterface */
protected $query;
/**
*
* @param ReportHelperInterface $helper
* @param ReportQueryInterface $query
*/
public function __construct()
public function __construct(ReportHelperInterface $helper, ReportQueryInterface $query)
{
$this->query = $query;
$this->helper = $helper;
View::share('title', 'Reports');
View::share('mainTitleIcon', 'fa-line-chart');
@@ -38,97 +44,78 @@ class ReportController extends Controller
*
* @return \Illuminate\View\View
*/
public function budget($year = '2014', $month = '1', ReportQueryInterface $query)
public function budget($year = '2014', $month = '1')
{
try {
new Carbon($year . '-' . $month . '-01');
} catch (Exception $e) {
return view('error')->with('message', 'Invalid date');
}
$date = new Carbon($year . '-' . $month . '-01');
$start = clone $date;
$date = new Carbon($year . '-' . $month . '-01');
$subTitle = 'Budget report for ' . $date->format('F Y');
$subTitleIcon = 'fa-calendar';
$start = clone $date;
$start->startOfMonth();
$end = clone $date;
$end->endOfMonth();
$start->subDay();
// shared accounts preference:
// should show shared reports?
/** @var Preference $pref */
$pref = Preferences::get('showSharedReports', false);
$showSharedReports = $pref->data;
$accountAmounts = []; // array with sums of spent amounts on each account.
$accounts = $this->query->getAllAccounts($start, $end, $showSharedReports); // all accounts and some data.
foreach ($accounts as $account) {
$dayEarly = clone $date;
$subTitle = 'Budget report for ' . $date->format('F Y');
$subTitleIcon = 'fa-calendar';
$dayEarly = $dayEarly->subDay();
$accounts = $query->getAllAccounts($start, $end, $showSharedReports);
$start->addDay();
$budgets = $this->query->getBudgetSummary($account, $start, $end);// get budget summary for this account:
$balancedAmount = $this->query->balancedTransactionsSum($account, $start, $end);
$accountAmounts[$account->id] = $balancedAmount;
// balance out the transactions (see transaction groups & tags) ^^
$accounts->each(
function (Account $account) use ($start, $end, $query) {
$budgets = $query->getBudgetSummary($account, $start, $end);
$balancedAmount = $query->balancedTransactionsSum($account, $start, $end);
$array = [];
foreach ($budgets as $budget) {
$id = intval($budget->id);
$data = $budget->toArray();
$array[$id] = $data;
// array with budget information for each account:
$array = [];
// should always hide account
$hide = true;
// loop all budgets
/** @var \FireflyIII\Models\Budget $budget */
foreach ($budgets as $budget) {
$id = intval($budget->id);
$data = $budget->toArray();
$array[$id] = $data;
// no longer hide account if any budget has money in it.
if (floatval($data['queryAmount']) != 0) {
$hide = false;
}
$account->budgetInformation = $array;
$account->balancedAmount = $balancedAmount;
$accountAmounts[$account->id] += $data['queryAmount'];
}
);
$account->hide = $hide;
$account->budgetInformation = $array;
$account->balancedAmount = $balancedAmount;
$start = clone $date;
$start->startOfMonth();
}
/**
* Start getBudgetsForMonth DONE
*/
$set = Auth::user()->budgets()->orderBy('budgets.name', 'ASC')
->leftJoin(
'budget_limits', function (JoinClause $join) use ($date) {
$join->on('budget_limits.budget_id', '=', 'budgets.id')->where('budget_limits.startdate', '=', $date->format('Y-m-d'));
}
)
->get(['budgets.*', 'budget_limits.amount as amount']);
$budgets = Steam::makeArray($set);
$amountSet = $query->journalsByBudget($start, $end, $showSharedReports);
$amounts = Steam::makeArray($amountSet);
$budgets = Steam::mergeArrays($budgets, $amounts);
$budgets[0]['spent'] = isset($budgets[0]['spent']) ? $budgets[0]['spent'] : 0.0;
$budgets[0]['amount'] = isset($budgets[0]['amount']) ? $budgets[0]['amount'] : 0.0;
$budgets[0]['name'] = 'No budget';
// find transactions to shared asset accounts, which are without a budget by default:
// which is only relevant when shared asset accounts are hidden.
if ($showSharedReports === false) {
$transfers = $query->sharedExpenses($start, $end);
foreach ($transfers as $transfer) {
$budgets[0]['spent'] += floatval($transfer->amount) * -1;
}
}
$budgets = $this->helper->getBudgetsForMonth($date, $showSharedReports);
/**
* End getBudgetsForMonth DONE
*/
return view('reports.budget', compact('subTitle', 'year', 'month', 'subTitleIcon', 'date', 'accounts', 'budgets', 'dayEarly'));
return view('reports.budget', compact('subTitle', 'accountAmounts', 'year', 'month', 'subTitleIcon', 'date', 'accounts', 'budgets'));
}
/**
* @param ReportHelperInterface $helper
*
* @return View
* @internal param ReportHelperInterface $helper
*
*/
public function index(ReportHelperInterface $helper)
public function index()
{
$start = Session::get('first');
$months = $helper->listOfMonths($start);
$years = $helper->listOfYears($start);
$months = $this->helper->listOfMonths($start);
$years = $this->helper->listOfYears($start);
$title = 'Reports';
$mainTitleIcon = 'fa-line-chart';
@@ -142,19 +129,14 @@ class ReportController extends Controller
*
* @return \Illuminate\View\View
*/
public function modalBalancedTransfers(Account $account, $year = '2014', $month = '1', ReportQueryInterface $query)
public function modalBalancedTransfers(Account $account, $year = '2014', $month = '1')
{
try {
new Carbon($year . '-' . $month . '-01');
} catch (Exception $e) {
return view('error')->with('message', 'Invalid date');
}
$start = new Carbon($year . '-' . $month . '-01');
$end = clone $start;
$end->endOfMonth();
$journals = $query->balancedTransactionsList($account, $start, $end);
$journals = $this->query->balancedTransactionsList($account, $start, $end);
return view('reports.modal-journal-list', compact('journals'));
@@ -162,24 +144,20 @@ class ReportController extends Controller
}
/**
* @param Account $account
* @param string $year
* @param string $month
* @param ReportQueryInterface $query
* @param Account $account
* @param string $year
* @param string $month
*
* @return View
* @internal param ReportQueryInterface $query
*
*/
public function modalLeftUnbalanced(Account $account, $year = '2014', $month = '1', ReportQueryInterface $query)
public function modalLeftUnbalanced(Account $account, $year = '2014', $month = '1')
{
try {
new Carbon($year . '-' . $month . '-01');
} catch (Exception $e) {
return view('error')->with('message', 'Invalid date');
}
$start = new Carbon($year . '-' . $month . '-01');
$end = clone $start;
$end->endOfMonth();
$set = $query->getTransactionsWithoutBudget($account, $start, $end);
$set = $this->query->getTransactionsWithoutBudget($account, $start, $end);
$journals = $set->filter(
function (TransactionJournal $journal) {
@@ -187,6 +165,8 @@ class ReportController extends Controller
if ($count == 0) {
return $journal;
}
return null;
}
);
@@ -200,17 +180,12 @@ class ReportController extends Controller
*
* @return \Illuminate\View\View
*/
public function modalNoBudget(Account $account, $year = '2014', $month = '1', ReportQueryInterface $query)
public function modalNoBudget(Account $account, $year = '2014', $month = '1')
{
try {
new Carbon($year . '-' . $month . '-01');
} catch (Exception $e) {
return view('error')->with('message', 'Invalid date');
}
$start = new Carbon($year . '-' . $month . '-01');
$end = clone $start;
$end->endOfMonth();
$journals = $query->getTransactionsWithoutBudget($account, $start, $end);
$journals = $this->query->getTransactionsWithoutBudget($account, $start, $end);
return view('reports.modal-journal-list', compact('journals'));
@@ -222,18 +197,13 @@ class ReportController extends Controller
*
* @return \Illuminate\View\View
*/
public function month($year = '2014', $month = '1', ReportQueryInterface $query)
public function month($year = '2014', $month = '1')
{
try {
new Carbon($year . '-' . $month . '-01');
} catch (Exception $e) {
return view('error')->with('message', 'Invalid date.');
}
$date = new Carbon($year . '-' . $month . '-01');
$subTitle = 'Report for ' . $date->format('F Y');
$subTitleIcon = 'fa-calendar';
$displaySum = true; // to show sums in report.
/** @var Preference $pref */
$pref = Preferences::get('showSharedReports', false);
$showSharedReports = $pref->data;
@@ -252,14 +222,15 @@ class ReportController extends Controller
/**
* Start getIncomeForMonth DONE
*/
$income = $query->incomeByPeriod($start, $end, $showSharedReports);
$income = $this->query->incomeByPeriod($start, $end, $showSharedReports);
/**
* End getIncomeForMonth DONE
*/
/**
* Start getExpenseGroupedForMonth DONE
*/
$set = $query->journalsByExpenseAccount($start, $end, $showSharedReports);
$set = $this->query->journalsByExpenseAccount($start, $end, $showSharedReports);
$expenses = Steam::makeArray($set);
$expenses = Steam::sortArray($expenses);
$expenses = Steam::limitArray($expenses, 10);
@@ -269,28 +240,7 @@ class ReportController extends Controller
/**
* Start getBudgetsForMonth DONE
*/
$set = Auth::user()->budgets()
->leftJoin(
'budget_limits', function (JoinClause $join) use ($date) {
$join->on('budget_limits.budget_id', '=', 'budgets.id')->where('budget_limits.startdate', '=', $date->format('Y-m-d'));
}
)
->get(['budgets.*', 'budget_limits.amount as amount']);
$budgets = Steam::makeArray($set);
$amountSet = $query->journalsByBudget($start, $end, $showSharedReports);
$amounts = Steam::makeArray($amountSet);
$budgets = Steam::mergeArrays($budgets, $amounts);
$budgets[0]['spent'] = isset($budgets[0]['spent']) ? $budgets[0]['spent'] : 0.0;
$budgets[0]['amount'] = isset($budgets[0]['amount']) ? $budgets[0]['amount'] : 0.0;
$budgets[0]['name'] = 'No budget';
// find transactions to shared expense accounts, which are without a budget by default:
if ($showSharedReports === false) {
$transfers = $query->sharedExpenses($start, $end);
foreach ($transfers as $transfer) {
$budgets[0]['spent'] += floatval($transfer->amount) * -1;
}
}
$budgets = $this->helper->getBudgetsForMonth($date, $showSharedReports);
/**
* End getBudgetsForMonth DONE
@@ -299,18 +249,20 @@ class ReportController extends Controller
* Start getCategoriesForMonth DONE
*/
// all categories.
$result = $query->journalsByCategory($start, $end);
$result = $this->query->journalsByCategory($start, $end);
$categories = Steam::makeArray($result);
// all transfers
if ($showSharedReports === false) {
$result = $query->sharedExpensesByCategory($start, $end);
$result = $this->query->sharedExpensesByCategory($start, $end);
$transfers = Steam::makeArray($result);
$merged = Steam::mergeArrays($categories, $transfers);
} else {
$merged = $categories;
}
// sort.
$sorted = Steam::sortNegativeArray($merged);
@@ -322,7 +274,7 @@ class ReportController extends Controller
/**
* Start getAccountsForMonth
*/
$list = $query->accountList($showSharedReports);
$list = $this->query->accountList($showSharedReports);
$accounts = [];
/** @var Account $account */
foreach ($list as $account) {
@@ -356,14 +308,9 @@ class ReportController extends Controller
*
* @return $this
*/
public function year($year, ReportHelperInterface $helper, ReportQueryInterface $query)
public function year($year)
{
try {
new Carbon('01-01-' . $year);
} catch (Exception $e) {
return view('error')->with('message', 'Invalid date.');
}
/** @var Preference $pref */
$pref = Preferences::get('showSharedReports', false);
$showSharedReports = $pref->data;
$date = new Carbon('01-01-' . $year);
@@ -373,11 +320,9 @@ class ReportController extends Controller
$subTitle = $year;
$subTitleIcon = 'fa-bar-chart';
$mainTitleIcon = 'fa-line-chart';
$balances = $helper->yearBalanceReport($date, $showSharedReports);
$groupedIncomes = $query->journalsByRevenueAccount($date, $end, $showSharedReports);
$groupedExpenses = $query->journalsByExpenseAccount($date, $end, $showSharedReports);
//$groupedExpenses = $helper-> expensesGroupedByAccount($date, $end, 15);
$balances = $this->helper->yearBalanceReport($date, $showSharedReports);
$groupedIncomes = $this->query->journalsByRevenueAccount($date, $end, $showSharedReports);
$groupedExpenses = $this->query->journalsByExpenseAccount($date, $end, $showSharedReports);
return view(
'reports.year', compact('date', 'groupedIncomes', 'groupedExpenses', 'year', 'balances', 'title', 'subTitle', 'subTitleIcon', 'mainTitleIcon')

View File

@@ -1,6 +1,5 @@
<?php namespace FireflyIII\Http\Controllers;
use FireflyIII\Http\Requests;
use FireflyIII\Support\Search\SearchInterface;
use Input;
@@ -13,6 +12,10 @@ class SearchController extends Controller
{
/**
* Results always come in the form of an array [results, count, fullCount]
*
* @param SearchInterface $searcher
*
* @return $this
*/
public function index(SearchInterface $searcher)
{

View File

@@ -0,0 +1,325 @@
<?php
namespace FireflyIII\Http\Controllers;
use Auth;
use Carbon\Carbon;
use FireflyIII\Http\Requests\TagFormRequest;
use FireflyIII\Models\Preference;
use FireflyIII\Models\Tag;
use FireflyIII\Repositories\Tag\TagRepositoryInterface;
use Input;
use Preferences;
use Redirect;
use Response;
use Session;
use URL;
use View;
/**
* Class TagController
*
* Remember: a balancingAct takes at most one expense and one transfer.
* an advancePayment takes at most one expense, infinite deposits and NO transfers.
*
* transaction can only have one advancePayment OR balancingAct.
* Other attempts to put in such a tag are blocked.
* also show an error when editing a tag and it becomes either
* of these two types. Or rather, block editing of the tag.
*
* @package FireflyIII\Http\Controllers
*/
class TagController extends Controller
{
/**
*
*/
public function __construct()
{
parent::__construct();
View::share('title', 'Tags');
View::share('mainTitleIcon', 'fa-tags');
View::share('hideTags', true);
$tagOptions = [
'nothing' => 'Just a regular tag.',
'balancingAct' => 'The tag takes at most two transactions; an expense and a transfer. They\'ll balance each other out.',
'advancePayment' => 'The tag accepts one expense and any number of deposits aimed to repay the original expense.',
];
View::share('tagOptions', $tagOptions);
}
/**
* @return \Illuminate\View\View
*/
public function create()
{
$subTitle = 'New tag';
$subTitleIcon = 'fa-tag';
$preFilled = [
'tagMode' => 'nothing'
];
if (!Input::old('tagMode')) {
Session::flash('preFilled', $preFilled);
}
// put previous url in session if not redirect from store (not "create another").
if (Session::get('tags.create.fromStore') !== true) {
Session::put('tags.create.url', URL::previous());
}
Session::forget('tags.create.fromStore');
return view('tags.create', compact('subTitle', 'subTitleIcon'));
}
/**
* @param Tag $tag
*
* @return \Illuminate\View\View
*/
public function delete(Tag $tag)
{
$subTitle = 'Delete "' . e($tag->tag) . '"';
// put previous url in session
Session::put('tags.delete.url', URL::previous());
return view('tags.delete', compact('tag', 'subTitle'));
}
/**
* @param TagRepositoryInterface $repository
* @param Tag $tag
*
* @return \Illuminate\Http\RedirectResponse
*/
public function destroy(TagRepositoryInterface $repository, Tag $tag)
{
$tagName = $tag->tag;
$repository->destroy($tag);
Session::flash('success', 'Tag "' . e($tagName) . '" was deleted.');
return Redirect::to(route('tags.index'));
}
/**
* @param Tag $tag
*
* @return View
*/
public function edit(Tag $tag)
{
$subTitle = 'Edit tag "' . e($tag->tag) . '"';
$subTitleIcon = 'fa-tag';
/*
* Default tag options (again)
*/
$tagOptions = [
'nothing' => 'Just a regular tag.',
'balancingAct' => 'The tag takes at most two transactions; an expense and a transfer. They\'ll balance each other out.',
'advancePayment' => 'The tag accepts one expense and any number of deposits aimed to repay the original expense.',
];
/*
* Can this tag become another type?
*/
$allowToAdvancePayment = true;
$allowToBalancingAct = true;
/*
* If this tag is a balancing act, and it contains transfers, it cannot be
* changes to an advancePayment.
*/
if ($tag->tagMode == 'balancingAct') {
foreach ($tag->transactionjournals as $journal) {
if ($journal->transactionType->type == 'Transfer') {
$allowToAdvancePayment = false;
}
}
}
/*
* If this tag contains more than one expenses, it cannot become an advance payment.
*/
$count = 0;
foreach ($tag->transactionjournals as $journal) {
if ($journal->transactionType->type == 'Withdrawal') {
$count++;
}
}
if ($count > 1) {
$allowToAdvancePayment = false;
}
/*
* If has more than two transactions already, cannot become a balancing act:
*/
if ($tag->transactionjournals->count() > 2) {
$allowToBalancingAct = false;
}
/*
* If any transaction is a deposit, cannot become a balancing act.
*/
$count = 0;
foreach ($tag->transactionjournals as $journal) {
if ($journal->transactionType->type == 'Deposit') {
$count++;
}
}
if ($count > 0) {
$allowToBalancingAct = false;
}
// edit tag options:
if ($allowToAdvancePayment === false) {
unset($tagOptions['advancePayment']);
}
if ($allowToBalancingAct === false) {
unset($tagOptions['balancingAct']);
}
// put previous url in session if not redirect from store (not "return_to_edit").
if (Session::get('tags.edit.fromUpdate') !== true) {
Session::put('tags.edit.url', URL::previous());
}
Session::forget('tags.edit.fromUpdate');
return view('tags.edit', compact('tag', 'subTitle', 'subTitleIcon', 'tagOptions'));
}
/**
* @param $state
*
* @return \Symfony\Component\HttpFoundation\Response
*/
public function hideTagHelp($state)
{
$state = $state == 'true' ? true : false;
Preferences::set('hideTagHelp', $state);
return Response::json(true);
}
/**
*
*/
public function index()
{
/** @var Preference $helpHiddenPref */
$helpHiddenPref = Preferences::get('hideTagHelp', false);
$title = 'Tags';
$mainTitleIcon = 'fa-tags';
$helpHidden = $helpHiddenPref->data;
$tags = Auth::user()->tags()->get();
return view('tags.index', compact('title', 'mainTitleIcon', 'helpHidden', 'tags'));
}
/**
* @param Tag $tag
*
* @return \Illuminate\View\View
*/
public function show(Tag $tag)
{
$subTitle = $tag->tag;
$subTitleIcon = 'fa-tag';
return view('tags.show', compact('tag', 'subTitle', 'subTitleIcon'));
}
/**
* @param TagFormRequest $request
*
* @param TagRepositoryInterface $repository
*
* @return $this|\Illuminate\Http\RedirectResponse
*/
public function store(TagFormRequest $request, TagRepositoryInterface $repository)
{
if (Input::get('setTag') == 'true') {
$latitude = strlen($request->get('latitude')) > 0 ? $request->get('latitude') : null;
$longitude = strlen($request->get('longitude')) > 0 ? $request->get('longitude') : null;
$zoomLevel = strlen($request->get('zoomLevel')) > 0 ? $request->get('zoomLevel') : null;
} else {
$latitude = null;
$longitude = null;
$zoomLevel = null;
}
$data = [
'tag' => $request->get('tag'),
'date' => strlen($request->get('date')) > 0 ? new Carbon($request->get('date')) : null,
'description' => strlen($request->get('description')) > 0 ? $request->get('description') : '',
'latitude' => $latitude,
'longitude' => $longitude,
'zoomLevel' => $zoomLevel,
'tagMode' => $request->get('tagMode'),
];
$repository->store($data);
Session::flash('success', 'The tag has been created!');
if (intval(Input::get('create_another')) === 1) {
// set value so create routine will not overwrite URL:
Session::put('tags.create.fromStore', true);
return Redirect::route('tags.create')->withInput();
}
// redirect to previous URL.
return Redirect::to(Session::get('tags.create.url'));
}
/**
* @param TagFormRequest $request
* @param TagRepositoryInterface $repository
* @param Tag $tag
*
* @return $this|\Illuminate\Http\RedirectResponse
*/
public function update(TagFormRequest $request, TagRepositoryInterface $repository, Tag $tag)
{
if (Input::get('setTag') == 'true') {
$latitude = strlen($request->get('latitude')) > 0 ? $request->get('latitude') : null;
$longitude = strlen($request->get('longitude')) > 0 ? $request->get('longitude') : null;
$zoomLevel = strlen($request->get('zoomLevel')) > 0 ? $request->get('zoomLevel') : null;
} else {
$latitude = null;
$longitude = null;
$zoomLevel = null;
}
$data = [
'tag' => $request->get('tag'),
'date' => strlen($request->get('date')) > 0 ? new Carbon($request->get('date')) : null,
'description' => strlen($request->get('description')) > 0 ? $request->get('description') : '',
'latitude' => $latitude,
'longitude' => $longitude,
'zoomLevel' => $zoomLevel,
'tagMode' => $request->get('tagMode'),
];
$repository->update($tag, $data);
Session::flash('success', 'Tag "' . e($data['tag']) . '" updated.');
if (intval(Input::get('return_to_edit')) === 1) {
// set value so edit routine will not overwrite URL:
Session::put('tags.edit.fromUpdate', true);
return Redirect::route('tags.edit', $tag->id)->withInput(['return_to_edit' => 1]);
}
// redirect to previous URL.
return Redirect::to(Session::get('tags.edit.url'));
}
}

View File

@@ -9,14 +9,15 @@ use FireflyIII\Http\Requests;
use FireflyIII\Http\Requests\JournalFormRequest;
use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionJournal;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
use Illuminate\Pagination\LengthAwarePaginator;
use Input;
use Redirect;
use Response;
use Session;
use URL;
use View;
/**
* Class TransactionController
*
@@ -28,24 +29,20 @@ class TransactionController extends Controller
*/
public function __construct()
{
parent::__construct();
View::share('title', 'Transactions');
View::share('mainTitleIcon', 'fa-repeat');
}
/**
* Shows the view helping the user to create a new transaction journal.
* @param AccountRepositoryInterface $repository
* @param string $what
*
* @param string $what
*
* @return \Illuminate\View\View
* @return View
*/
public function create($what = 'deposit')
public function create(AccountRepositoryInterface $repository, $what = 'deposit')
{
$accounts = ExpandedForm::makeSelectList(
Auth::user()->accounts()->accountTypeIn(['Default account', 'Asset account'])->orderBy('accounts.name', 'ASC')->orderBy('name', 'ASC')->where(
'active', 1
)->orderBy('name', 'DESC')->get(['accounts.*'])
);
$accounts = ExpandedForm::makeSelectList($repository->getAccounts(['Default account', 'Asset account']));
$budgets = ExpandedForm::makeSelectList(Auth::user()->budgets()->get());
$budgets[0] = '(no budget)';
$piggies = ExpandedForm::makeSelectList(Auth::user()->piggyBanks()->get());
@@ -61,6 +58,12 @@ class TransactionController extends Controller
}
Session::put('preFilled', $preFilled);
// put previous url in session if not redirect from store (not "create another").
if (Session::get('transactions.create.fromStore') !== true) {
Session::put('transactions.create.url', URL::previous());
}
Session::forget('transactions.create.fromStore');
asort($piggies);
@@ -79,52 +82,42 @@ class TransactionController extends Controller
$type = strtolower($journal->transactionType->type);
$subTitle = 'Delete ' . e($type) . ' "' . e($journal->description) . '"';
return View::make('transactions.delete', compact('journal', 'subTitle'));
// put previous url in session
Session::put('transactions.delete.url', URL::previous());
return view('transactions.delete', compact('journal', 'subTitle'));
}
/**
* @param TransactionJournal $transactionJournal
* @param JournalRepositoryInterface $repository
* @param TransactionJournal $transactionJournal
*
* @return \Illuminate\Http\RedirectResponse
*/
public function destroy(TransactionJournal $transactionJournal)
public function destroy(JournalRepositoryInterface $repository, TransactionJournal $transactionJournal)
{
$type = $transactionJournal->transactionType->type;
$return = 'withdrawal';
Session::flash('success', 'Transaction "' . e($transactionJournal->description) . '" destroyed.');
$transactionJournal->delete();
$repository->delete($transactionJournal);
switch ($type) {
case 'Deposit':
$return = 'deposit';
break;
case 'Transfer':
$return = 'transfers';
break;
}
return Redirect::route('transactions.index', $return);
// redirect to previous URL:
return Redirect::to(Session::get('transactions.delete.url'));
}
/**
* Shows the view to edit a transaction.
*
* @param TransactionJournal $journal
* @param AccountRepositoryInterface $repository
* @param TransactionJournal $journal
*
* @return $this
*/
public function edit(TransactionJournal $journal, JournalRepositoryInterface $repository)
public function edit(AccountRepositoryInterface $repository, TransactionJournal $journal)
{
$what = strtolower($journal->transactiontype->type);
$accounts = ExpandedForm::makeSelectList(
Auth::user()->accounts()->accountTypeIn(['Default account', 'Asset account'])->orderBy('accounts.name', 'ASC')->where('active', 1)->orderBy(
'name', 'DESC'
)->get(['accounts.*'])
);
$accounts = ExpandedForm::makeSelectList($repository->getAccounts(['Default account', 'Asset account']));
$budgets = ExpandedForm::makeSelectList(Auth::user()->budgets()->get());
$budgets[0] = '(no budget)';
$transactions = $journal->transactions()->orderBy('amount', 'DESC')->get();
@@ -136,6 +129,12 @@ class TransactionController extends Controller
'budget_id' => 0,
'piggy_bank_id' => 0
];
// get tags:
$tags = [];
foreach ($journal->tags as $tag) {
$tags[] = $tag->tag;
}
$preFilled['tags'] = join(',', $tags);
$category = $journal->categories()->first();
if (!is_null($category)) {
@@ -151,62 +150,59 @@ class TransactionController extends Controller
$preFilled['piggy_bank_id'] = $journal->piggyBankEvents()->orderBy('date', 'DESC')->first()->piggy_bank_id;
}
$preFilled['amount'] = 0;
/** @var Transaction $t */
foreach ($transactions as $t) {
if (floatval($t->amount) > 0) {
$preFilled['amount'] = floatval($t->amount);
}
}
$preFilled['account_id'] = $repository->getAssetAccount($journal);
$preFilled['amount'] = $journal->amount;
$preFilled['account_id'] = $journal->assetAccount->id;
$preFilled['expense_account'] = $transactions[0]->account->name;
$preFilled['revenue_account'] = $transactions[1]->account->name;
$preFilled['account_from_id'] = $transactions[1]->account->id;
$preFilled['account_to_id'] = $transactions[0]->account->id;
Session::flash('preFilled', $preFilled);
// put previous url in session if not redirect from store (not "return_to_edit").
if (Session::get('transactions.edit.fromUpdate') !== true) {
Session::put('transactions.edit.url', URL::previous());
}
Session::forget('transactions.edit.fromUpdate');
return View::make('transactions.edit', compact('journal', 'accounts', 'what', 'budgets', 'piggies', 'subTitle'))->with('data', $preFilled);
}
/**
* @param $what
* @param JournalRepositoryInterface $repository
* @param $what
*
* @return $this
* @return View
*/
public function index($what)
public function index(JournalRepositoryInterface $repository, $what)
{
$types = [];
switch ($what) {
case 'expenses':
case 'withdrawal':
$subTitleIcon = 'fa-long-arrow-left';
$subTitle = 'Expenses';
//$journals = $this->_repository->getWithdrawalsPaginated(50);
$types = ['Withdrawal'];
$types = ['Withdrawal'];
break;
case 'revenue':
case 'deposit':
$subTitleIcon = 'fa-long-arrow-right';
$subTitle = 'Revenue, income and deposits';
// $journals = $this->_repository->getDepositsPaginated(50);
$types = ['Deposit'];
$types = ['Deposit'];
break;
case 'transfer':
case 'transfers':
$subTitleIcon = 'fa-arrows-h';
$subTitleIcon = 'fa-exchange';
$subTitle = 'Transfers';
//$journals = $this->_repository->getTransfersPaginated(50);
$types = ['Transfer'];
$types = ['Transfer'];
break;
}
$page = intval(\Input::get('page'));
$offset = $page > 0 ? ($page - 1) * 50 : 0;
$page = intval(Input::get('page'));
$offset = $page > 0 ? ($page - 1) * 50 : 0;
$journals = $repository->getJournalsOfTypes($types, $offset, $page);
$set = Auth::user()->transactionJournals()->transactionTypes($types)->withRelevantData()->take(50)->offset($offset)->orderBy('date', 'DESC')->get(
['transaction_journals.*']
);
$count = Auth::user()->transactionJournals()->transactionTypes($types)->count();
$journals = new LengthAwarePaginator($set, $count, 50, $page);
$journals->setPath('transactions/' . $what);
return view('transactions.index', compact('subTitle', 'what', 'subTitleIcon', 'journals'));
@@ -214,98 +210,95 @@ class TransactionController extends Controller
}
/**
* @param TransactionJournal $journal
* @param JournalRepositoryInterface $repository
*
* @return $this
* @return \Symfony\Component\HttpFoundation\Response
*/
public function show(TransactionJournal $journal)
public function reorder(JournalRepositoryInterface $repository)
{
$journal->transactions->each(
function (Transaction $t) use ($journal) {
$t->before = floatval(
$t->account->transactions()->leftJoin(
'transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id'
)->where('transaction_journals.date', '<=', $journal->date->format('Y-m-d'))->where(
'transaction_journals.created_at', '<=', $journal->created_at->format('Y-m-d H:i:s')
)->where('transaction_journals.id', '!=', $journal->id)->sum('transactions.amount')
);
$t->after = $t->before + $t->amount;
$ids = Input::get('items');
$date = new Carbon(Input::get('date'));
if (count($ids) > 0) {
$order = 0;
foreach ($ids as $id) {
$journal = $repository->getWithDate($id, $date);
if ($journal) {
$journal->order = $order;
$order++;
$journal->save();
}
}
);
return view('transactions.show', compact('journal'))->with(
'subTitle', e($journal->transactiontype->type) . ' "' . e($journal->description) . '"'
);
}
public function store(JournalFormRequest $request, JournalRepositoryInterface $repository)
{
$journalData = [
'what' => $request->get('what'),
'description' => $request->get('description'),
'account_id' => intval($request->get('account_id')),
'account_from_id' => intval($request->get('account_from_id')),
'account_to_id' => intval($request->get('account_to_id')),
'expense_account' => $request->get('expense_account'),
'revenue_account' => $request->get('revenue_account'),
'amount' => floatval($request->get('amount')),
'user' => Auth::user()->id,
'amount_currency_id' => intval($request->get('amount_currency_id')),
'date' => new Carbon($request->get('date')),
'budget_id' => intval($request->get('budget_id')),
'category' => $request->get('category'),
];
$journal = $repository->store($journalData);
event(new JournalSaved($journal));
event(new JournalCreated($journal, intval($request->get('piggy_bank_id'))));
if (intval($request->get('reminder_id')) > 0) {
$reminder = Auth::user()->reminders()->find($request->get('reminder_id'));
$reminder->active = 0;
$reminder->save();
}
Session::flash('success', 'New transaction "' . $journal->description . '" stored!');
if (intval(Input::get('create_another')) === 1) {
return Redirect::route('transactions.create', $request->input('what'))->withInput();
}
return Redirect::route('transactions.index', $request->input('what'));
return Response::json(true);
}
/**
* @param TransactionJournal $journal
*
* @SuppressWarnings("CyclomaticComplexity") // It's exactly 5. So I don't mind.
* @param JournalRepositoryInterface $repository
* @param TransactionJournal $journal
*
* @return $this
* @throws FireflyException
*/
public function update(TransactionJournal $journal, JournalFormRequest $request, JournalRepositoryInterface $repository)
public function show(JournalRepositoryInterface $repository, TransactionJournal $journal)
{
$journal->transactions->each(
function (Transaction $t) use ($journal, $repository) {
$t->before = $repository->getAmountBefore($journal, $t);
$t->after = $t->before + $t->amount;
}
);
$subTitle = e($journal->transactiontype->type) . ' "' . e($journal->description) . '"';
return view('transactions.show', compact('journal', 'subTitle'));
}
/**
* @param JournalFormRequest $request
* @param JournalRepositoryInterface $repository
*
* @return $this|\Illuminate\Http\RedirectResponse
*/
public function store(JournalFormRequest $request, JournalRepositoryInterface $repository)
{
$journalData = $request->getJournalData();
$journal = $repository->store($journalData);
$journalData = [
'what' => $request->get('what'),
'description' => $request->get('description'),
'account_id' => intval($request->get('account_id')),
'account_from_id' => intval($request->get('account_from_id')),
'account_to_id' => intval($request->get('account_to_id')),
'expense_account' => $request->get('expense_account'),
'revenue_account' => $request->get('revenue_account'),
'amount' => floatval($request->get('amount')),
'user' => Auth::user()->id,
'amount_currency_id' => intval($request->get('amount_currency_id')),
'date' => new Carbon($request->get('date')),
'budget_id' => intval($request->get('budget_id')),
'category' => $request->get('category'),
];
// rescan journal, UpdateJournalConnection
event(new JournalSaved($journal));
// ConnectJournalToPiggyBank
event(new JournalCreated($journal, intval($request->get('piggy_bank_id'))));
$repository->deactivateReminder($request->get('reminder_id'));
Session::flash('success', 'New transaction "' . $journal->description . '" stored!');
if (intval(Input::get('create_another')) === 1) {
// set value so create routine will not overwrite URL:
Session::put('transactions.create.fromStore', true);
return Redirect::route('transactions.create', $request->input('what'))->withInput();
}
// redirect to previous URL.
return Redirect::to(Session::get('transactions.create.url'));
}
/**
* @param JournalFormRequest $request
* @param JournalRepositoryInterface $repository
* @param TransactionJournal $journal
*
* @return $this|\Illuminate\Http\RedirectResponse
*/
public function update(JournalFormRequest $request, JournalRepositoryInterface $repository, TransactionJournal $journal)
{
$journalData = $request->getJournalData();
$repository->update($journal, $journalData);
event(new JournalSaved($journal));
@@ -314,10 +307,14 @@ class TransactionController extends Controller
Session::flash('success', 'Transaction "' . e($journalData['description']) . '" updated.');
if (intval(Input::get('return_to_edit')) === 1) {
return Redirect::route('transactions.edit', $journal->id);
// set value so edit routine will not overwrite URL:
Session::put('transactions.edit.fromUpdate', true);
return Redirect::route('transactions.edit', $journal->id)->withInput(['return_to_edit' => 1]);
}
return Redirect::route('transactions.index', $journalData['what']);
// redirect to previous URL.
return Redirect::to(Session::get('transactions.edit.url'));
}

View File

@@ -22,6 +22,7 @@ class Kernel extends HttpKernel
'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
'Illuminate\Session\Middleware\StartSession',
'Illuminate\View\Middleware\ShareErrorsFromSession',
'FireflyIII\Http\Middleware\ReplaceTestVars',
'FireflyIII\Http\Middleware\VerifyCsrfToken',
];
@@ -37,6 +38,8 @@ class Kernel extends HttpKernel
'guest' => 'FireflyIII\Http\Middleware\RedirectIfAuthenticated',
'range' => 'FireflyIII\Http\Middleware\Range',
'reminders' => 'FireflyIII\Http\Middleware\Reminders',
'piggybanks' => 'FireflyIII\Http\Middleware\PiggyBanks',
];
}

View File

@@ -2,6 +2,7 @@
use Closure;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\Request;
/**
* Class Authenticate
@@ -37,7 +38,7 @@ class Authenticate
*
* @return mixed
*/
public function handle($request, Closure $next)
public function handle(Request $request, Closure $next)
{
if ($this->auth->guest()) {
if ($request->ajax()) {

View File

@@ -0,0 +1,72 @@
<?php
namespace FireflyIII\Http\Middleware;
use App;
use Closure;
use FireflyIII\Models\PiggyBank;
use FireflyIII\Models\PiggyBankRepetition;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
/**
* Class PiggyBanks
*
* @package FireflyIII\Http\Middleware
*/
class PiggyBanks
{
/**
* The Guard implementation.
*
* @var Guard
*/
protected $auth;
/**
* Create a new filter instance.
*
* @param Guard $auth
*
*/
public function __construct(Guard $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
if ($this->auth->check() && !$request->isXmlHttpRequest() && App::environment() != 'testing') {
// get piggy banks without a repetition:
/** @var Collection $set */
$set = $this->auth->user()->piggybanks()
->leftJoin('piggy_bank_repetitions', 'piggy_banks.id', '=', 'piggy_bank_repetitions.piggy_bank_id')
->whereNull('piggy_bank_repetitions.id')
->get(['piggy_banks.id', 'piggy_banks.startdate', 'piggy_banks.targetdate']);
if ($set->count() > 0) {
/** @var PiggyBank $partialPiggy */
foreach ($set as $partialPiggy) {
$repetition = new PiggyBankRepetition;
$repetition->piggyBank()->associate($partialPiggy);
$repetition->startdate = is_null($partialPiggy->startdate) ? null : $partialPiggy->startdate;
$repetition->targetdate = is_null($partialPiggy->targetdate) ? null : $partialPiggy->targetdate;
$repetition->currentamount = 0;
$repetition->save();
}
}
unset($partialPiggy, $set, $repetition);
}
return $next($request);
}
}

View File

@@ -3,9 +3,11 @@
namespace FireflyIII\Http\Middleware;
use App;
use Carbon\Carbon;
use Closure;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\Request;
use Navigation;
use Preferences;
use Session;
@@ -44,16 +46,16 @@ class Range
*
* @return mixed
*/
public function handle($request, Closure $theNext)
public function handle(Request $request, Closure $theNext)
{
if ($this->auth->check()) {
if ($this->auth->check() && App::environment() != 'testing') {
// ignore preference. set the range to be the current month:
if (!Session::has('start') && !Session::has('end')) {
/** @var \FireflyIII\Models\Preference $viewRange */
$viewRange = Preferences::get('viewRange', '1M');
$start = Session::has('start') ? Session::get('start') : new Carbon;
$start = new Carbon;
$start = Navigation::updateStartDate($viewRange->data, $start);
$end = Navigation::updateEndDate($viewRange->data, $start);
@@ -61,11 +63,16 @@ class Range
Session::put('end', $end);
}
if (!Session::has('first')) {
$journal = $this->auth->user()->transactionjournals()->orderBy('date', 'ASC')->first(['transaction_journals.*']);
/**
* Get helper thing.
*/
/** @var \FireflyIII\Repositories\Journal\JournalRepositoryInterface $repository */
$repository = App::make('FireflyIII\Repositories\Journal\JournalRepositoryInterface');
$journal = $repository->first();
if ($journal) {
Session::put('first', $journal->date);
} else {
Session::put('first', Carbon::now());
Session::put('first', Carbon::now()->startOfYear());
}
}
@@ -84,4 +91,4 @@ class Range
}
}
}

View File

@@ -3,6 +3,7 @@
use Closure;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
/**
* Class RedirectIfAuthenticated
@@ -38,7 +39,7 @@ class RedirectIfAuthenticated
*
* @return mixed
*/
public function handle($request, Closure $next)
public function handle(Request $request, Closure $next)
{
if ($this->auth->check()) {
return new RedirectResponse(url('/'));

View File

@@ -8,6 +8,7 @@ use Closure;
use FireflyIII\Models\PiggyBank;
use FireflyIII\Models\Reminder;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\Request;
use View;
/**
@@ -43,9 +44,9 @@ class Reminders
*
* @return mixed
*/
public function handle($request, Closure $next)
public function handle(Request $request, Closure $next)
{
if ($this->auth->check()) {
if ($this->auth->check() && !$request->isXmlHttpRequest() && App::environment() != 'testing') {
// do reminders stuff.
$piggyBanks = $this->auth->user()->piggyBanks()->where('remind_me', 1)->get();
$today = new Carbon;
@@ -67,15 +68,14 @@ class Reminders
}
}
// delete invalid reminders
$reminders = $this->auth->user()->reminders()->get();
foreach($reminders as $reminder) {
if(is_null($reminder->remindersable)) {
$reminder->delete();
}
$set = $this->auth->user()->reminders()->leftJoin('piggy_banks', 'piggy_banks.id', '=', 'remindersable_id')->whereNull('piggy_banks.id')->get(
['reminders.id']
);
foreach ($set as $reminder) {
$reminder->delete();
}
// get and list active reminders:
$reminders = $this->auth->user()->reminders()->today()->get();
$reminders->each(
@@ -88,4 +88,4 @@ class Reminders
return $next($request);
}
}
}

View File

@@ -0,0 +1,56 @@
<?php
namespace FireflyIII\Http\Middleware;
use Closure;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Http\Request;
use Log;
/**
* Class ReplaceTestVars
*
* @package FireflyIII\Http\Middleware
*/
class ReplaceTestVars
{
/**
* The application implementation.
*
* @var Application
*/
protected $app;
/**
* Create a new filter instance.
*
* @param Application $app
*
*/
public function __construct(Application $app)
{
$this->app = $app;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
if ('testing' === $this->app->environment() && $request->has('_token')) {
$input = $request->all();
$input['_token'] = $request->session()->token();
// we need to update _token value to make sure we get the POST / PUT tests passed.
Log::debug('Input token replaced (' . $input['_token'] . ').');
$request->replace($input);
}
return $next($request);
}
}

View File

@@ -28,22 +28,29 @@ class AccountFormRequest extends Request
*/
public function rules()
{
$accountRoles = join(',', array_keys(Config::get('firefly.accountRoles')));
$types = join(',', array_keys(Config::get('firefly.subTitlesByIdentifier')));
$accountRoles = join(',', array_keys(Config::get('firefly.accountRoles')));
$types = join(',', array_keys(Config::get('firefly.subTitlesByIdentifier')));
$ccPaymentTypes = join(',', array_keys(Config::get('firefly.ccTypes')));
$nameRule = 'required|between:1,100|uniqueForUser:accounts,name';
$nameRule = 'required|min:1|uniqueAccountForUser';
$idRule = '';
if (Account::find(Input::get('id'))) {
$nameRule = 'required|between:1,100';
$idRule = 'belongsToUser:accounts';
$nameRule = 'required|min:1|uniqueAccountForUser:' . Input::get('id');
}
return [
'name' => $nameRule,
'openingBalance' => 'numeric',
'openingBalanceDate' => 'date',
'accountRole' => 'in:' . $accountRoles,
'active' => 'boolean',
'balance_currency_id' => 'exists:transaction_currencies,id',
'what' => 'in:' . $types
'id' => $idRule,
'name' => $nameRule,
'openingBalance' => 'numeric',
'virtualBalance' => 'numeric',
'openingBalanceDate' => 'date',
'accountRole' => 'in:' . $accountRoles,
'active' => 'boolean',
'ccType' => 'in:' . $ccPaymentTypes,
'ccMonthlyPaymentDate' => 'date',
'balance_currency_id' => 'exists:transaction_currencies,id',
'what' => 'in:' . $types
];
}
}
}

View File

@@ -3,6 +3,7 @@
namespace FireflyIII\Http\Requests;
use Auth;
use Carbon\Carbon;
use Input;
/**
@@ -21,19 +22,41 @@ class BillFormRequest extends Request
return Auth::check();
}
/**
* @return array
*/
public function getBillData()
{
return [
'name' => $this->get('name'),
'match' => $this->get('match'),
'amount_min' => floatval($this->get('amount_min')),
'amount_currency_id' => floatval($this->get('amount_currency_id')),
'amount_max' => floatval($this->get('amount_max')),
'date' => new Carbon($this->get('date')),
'user' => Auth::user()->id,
'repeat_freq' => $this->get('repeat_freq'),
'skip' => intval($this->get('skip')),
'automatch' => intval($this->get('automatch')) === 1,
'active' => intval($this->get('active')) === 1,
];
}
/**
* @return array
*/
public function rules()
{
$nameRule = 'required|between:1,255|uniqueForUser:bills,name';
$nameRule = 'required|between:1,255|uniqueObjectForUser:bills,name,name_encrypted';
$matchRule = 'required|between:1,255|uniqueObjectForUser:bills,match,match_encrypted';
if (intval(Input::get('id')) > 0) {
$nameRule = 'required|between:1,255';
$nameRule .= ',' . intval(Input::get('id'));
$matchRule .= ',' . intval(Input::get('id'));
}
$rules = [
'name' => $nameRule,
'match' => 'required|between:1,255',
'match' => $matchRule,
'amount_min' => 'required|numeric|min:0.01',
'amount_max' => 'required|numeric|min:0.01',
'amount_currency_id' => 'required|exists:transaction_currencies,id',
@@ -46,4 +69,4 @@ class BillFormRequest extends Request
return $rules;
}
}
}

View File

@@ -28,13 +28,14 @@ class BudgetFormRequest extends Request
public function rules()
{
$nameRule = 'required|between:1,100|uniqueForUser:budgets,name';
$nameRule = 'required|between:1,100|uniqueObjectForUser:budgets,name,encrypted';
if (Budget::find(Input::get('id'))) {
$nameRule = 'required|between:1,100';
$nameRule = 'required|between:1,100|uniqueObjectForUser:budgets,name,encrypted,' . intval(Input::get('id'));
}
return [
'name' => $nameRule,
'name' => $nameRule,
'active' => 'numeric|between:0,1'
];
}
}
}

View File

@@ -28,13 +28,13 @@ class CategoryFormRequest extends Request
public function rules()
{
$nameRule = 'required|between:1,100|uniqueForUser:categories,name';
$nameRule = 'required|between:1,100|uniqueObjectForUser:categories,name,encrypted';
if (Category::find(Input::get('id'))) {
$nameRule = 'required|between:1,100';
$nameRule = 'required|between:1,100|uniqueObjectForUser:categories,name,encrypted,' . intval(Input::get('id'));
}
return [
'name' => $nameRule,
];
}
}
}

View File

@@ -21,6 +21,18 @@ class CurrencyFormRequest extends Request
return Auth::check();
}
/**
* @return array
*/
public function getCurrencyData()
{
return [
'name' => $this->get('name'),
'code' => $this->get('code'),
'symbol' => $this->get('symbol'),
];
}
/**
* @return array
*/
@@ -42,4 +54,4 @@ class CurrencyFormRequest extends Request
return $rules;
}
}
}

View File

@@ -0,0 +1,32 @@
<?php
namespace FireflyIII\Http\Requests;
use Auth;
/**
* Class DeleteAccountFormRequest
*
* @package FireflyIII\Http\Requests
*/
class DeleteAccountFormRequest extends Request
{
/**
* @return bool
*/
public function authorize()
{
// Only allow logged in users
return Auth::check();
}
/**
* @return array
*/
public function rules()
{
return [
'password' => 'required',
];
}
}

View File

@@ -3,7 +3,8 @@
namespace FireflyIII\Http\Requests;
use Auth;
use FireflyIII\Models\Account;
use Carbon\Carbon;
use Exception;
use Input;
/**
@@ -25,6 +26,30 @@ class JournalFormRequest extends Request
/**
* @return array
*/
public function getJournalData()
{
return [
'what' => $this->get('what'),
'description' => $this->get('description'),
'account_id' => intval($this->get('account_id')),
'account_from_id' => intval($this->get('account_from_id')),
'account_to_id' => intval($this->get('account_to_id')),
'expense_account' => $this->get('expense_account'),
'revenue_account' => $this->get('revenue_account'),
'amount' => floatval($this->get('amount')),
'user' => Auth::user()->id,
'amount_currency_id' => intval($this->get('amount_currency_id')),
'date' => new Carbon($this->get('date')),
'budget_id' => intval($this->get('budget_id')),
'category' => $this->get('category'),
'tags' => explode(',', $this->get('tags')),
];
}
/**
* @return array
* @throws Exception
*/
public function rules()
{
// can we switch on the "what"?
@@ -32,7 +57,7 @@ class JournalFormRequest extends Request
$rules = [
'description' => 'required|min:1,max:255',
'what' => 'required|in:withdrawal,deposit,transfer|exists:transaction_types,type',
'what' => 'required|in:withdrawal,deposit,transfer',
'amount' => 'numeric|required|min:0.01',
'date' => 'required|date',
'reminder_id' => 'numeric|exists:reminders,id',
@@ -62,7 +87,7 @@ class JournalFormRequest extends Request
$rules['category'] = 'between:1,255';
break;
default:
die('Cannot handle ' . $what);
throw new Exception('Cannot handle ' . $what);
break;
}
@@ -70,4 +95,4 @@ class JournalFormRequest extends Request
}
}
}

View File

@@ -3,7 +3,6 @@
namespace FireflyIII\Http\Requests;
use Auth;
use FireflyIII\Models\Account;
use Input;
/**
@@ -28,27 +27,20 @@ class PiggyBankFormRequest extends Request
public function rules()
{
$nameRule = 'required|between:1,255|uniqueForUser:piggy_banks,name';
$nameRule = 'required|between:1,255|uniquePiggyBankForUser';
$targetDateRule = 'date';
if (intval(Input::get('id'))) {
$nameRule = 'required|between:1,255';
$nameRule = 'required|between:1,255|uniquePiggyBankForUser:' . intval(Input::get('id'));
}
if (intval(Input::get('repeats')) == 1) {
$targetDateRule = 'required|date|after:' . date('Y-m-d');
}
$rules = [
'repeats' => 'required|boolean',
'name' => $nameRule,
'account_id' => 'required|belongsToUser:accounts',
'targetamount' => 'required|min:0.01',
'amount_currency_id' => 'exists:transaction_currencies,id',
'startdate' => 'date',
'targetdate' => $targetDateRule,
'rep_length' => 'in:day,week,quarter,month,year',
'rep_every' => 'integer|min:0|max:31',
'rep_times' => 'integer|min:0|max:99',
'reminder' => 'in:day,week,quarter,month,year',
'reminder_skip' => 'integer|min:0|max:99',
'remind_me' => 'boolean|piggyBankReminder',
@@ -58,4 +50,4 @@ class PiggyBankFormRequest extends Request
return $rules;
}
}
}

View File

@@ -3,7 +3,6 @@
namespace FireflyIII\Http\Requests;
use Auth;
use FireflyIII\Models\Account;
/**
* Class ProfileFormRequest
@@ -27,9 +26,9 @@ class ProfileFormRequest extends Request
public function rules()
{
return [
'current_password' => 'required',
'current_password' => 'required',
'new_password' => 'required|confirmed',
'new_password_confirmation' => 'required',
];
}
}
}

View File

@@ -0,0 +1,53 @@
<?php
/**
* Created by PhpStorm.
* User: sander
* Date: 27/04/15
* Time: 12:50
*/
namespace FireflyIII\Http\Requests;
use Auth;
use FireflyIII\Models\Tag;
use Input;
/**
* Class TagFormRequest
*
* @package FireflyIII\Http\Requests
*/
class TagFormRequest extends Request
{
/**
* @return bool
*/
public function authorize()
{
// Only allow logged in users
return Auth::check();
}
/**
* @return array
*/
public function rules()
{
$idRule = '';
$tagRule = 'required|min:1|uniqueObjectForUser:tags,tag,TRUE';
if (Tag::find(Input::get('id'))) {
$idRule = 'belongsToUser:tags';
$tagRule = 'required|min:1|uniqueObjectForUser:tags,tag,TRUE,' . Input::get('id');
}
return [
'tag' => $tagRule,
'id' => $idRule,
'description' => 'min:1',
'date' => 'date',
'latitude' => 'numeric|min:-90|max:90',
'longitude' => 'numeric|min:-90|max:90',
'tagMode' => 'required|in:nothing,balancingAct,advancePayment'
];
}
}

View File

@@ -3,13 +3,15 @@ use Carbon\Carbon;
use DaveJamesMiller\Breadcrumbs\Generator;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\Account;
use FireflyIII\Models\Budget;
use FireflyIII\Models\TransactionJournal;
use FireflyIII\Models\Bill;
use FireflyIII\Models\Budget;
use FireflyIII\Models\Category;
use FireflyIII\Models\Reminder;
use FireflyIII\Models\LimitRepetition;
use FireflyIII\Models\PiggyBank;
use FireflyIII\Models\Reminder;
use FireflyIII\Models\Tag;
use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Models\TransactionJournal;
/*
* Back home.
@@ -22,6 +24,14 @@ Breadcrumbs::register(
}
);
Breadcrumbs::register(
'index',
function (Generator $breadcrumbs) {
$breadcrumbs->push('Home', route('index'));
}
);
// accounts
Breadcrumbs::register(
'accounts.index', function (Generator $breadcrumbs, $what) {
@@ -95,6 +105,13 @@ Breadcrumbs::register(
}
);
Breadcrumbs::register(
'budgets.noBudget', function (Generator $breadcrumbs, $subTitle) {
$breadcrumbs->parent('budgets.index');
$breadcrumbs->push($subTitle, route('budgets.noBudget'));
}
);
Breadcrumbs::register(
'budgets.show', function (Generator $breadcrumbs, Budget $budget, LimitRepetition $repetition = null) {
$breadcrumbs->parent('budgets.index');
@@ -142,6 +159,34 @@ Breadcrumbs::register(
}
);
Breadcrumbs::register(
'categories.noCategory', function (Generator $breadcrumbs, $subTitle) {
$breadcrumbs->parent('categories.index');
$breadcrumbs->push($subTitle, route('categories.noCategory'));
}
);
// currencies.
Breadcrumbs::register(
'currency.index', function (Generator $breadcrumbs) {
$breadcrumbs->parent('home');
$breadcrumbs->push('Currencies', route('currency.index'));
}
);
Breadcrumbs::register(
'currency.edit', function (Generator $breadcrumbs, TransactionCurrency $currency) {
$breadcrumbs->parent('currency.index');
$breadcrumbs->push('Edit ' . $currency->name, route('currency.edit', $currency->id));
}
);
Breadcrumbs::register(
'currency.delete', function (Generator $breadcrumbs, TransactionCurrency $currency) {
$breadcrumbs->parent('currency.index');
$breadcrumbs->push('Delete ' . $currency->name, route('currency.delete', $currency->id));
}
);
// piggy banks
Breadcrumbs::register(
@@ -256,40 +301,6 @@ Breadcrumbs::register(
}
);
// repeated expenses
Breadcrumbs::register(
'repeated.index', function (Generator $breadcrumbs) {
$breadcrumbs->parent('home');
$breadcrumbs->push('Repeated expenses', route('repeated.index'));
}
);
Breadcrumbs::register(
'repeated.create', function (Generator $breadcrumbs) {
$breadcrumbs->parent('repeated.index');
$breadcrumbs->push('Create new repeated expense', route('repeated.create'));
}
);
Breadcrumbs::register(
'repeated.edit', function (Generator $breadcrumbs, PiggyBank $piggyBank) {
$breadcrumbs->parent('repeated.show', $piggyBank);
$breadcrumbs->push('Edit ' . e($piggyBank->name), route('repeated.edit', $piggyBank->id));
}
);
Breadcrumbs::register(
'repeated.delete', function (Generator $breadcrumbs, PiggyBank $piggyBank) {
$breadcrumbs->parent('repeated.show', $piggyBank);
$breadcrumbs->push('Delete ' . e($piggyBank->name), route('repeated.delete', $piggyBank->id));
}
);
Breadcrumbs::register(
'repeated.show', function (Generator $breadcrumbs, PiggyBank $piggyBank) {
$breadcrumbs->parent('repeated.index');
$breadcrumbs->push(e($piggyBank->name), route('repeated.show', $piggyBank->id));
}
);
// reports
Breadcrumbs::register(
@@ -302,21 +313,21 @@ Breadcrumbs::register(
Breadcrumbs::register(
'reports.year', function (Generator $breadcrumbs, Carbon $date) {
$breadcrumbs->parent('reports.index');
$breadcrumbs->push($date->format('Y'), route('reports.year', $date->format('Y')));
$breadcrumbs->push($date->year, route('reports.year', $date->year));
}
);
Breadcrumbs::register(
'reports.month', function (Generator $breadcrumbs, Carbon $date) {
$breadcrumbs->parent('reports.index');
$breadcrumbs->push('Monthly report for ' . $date->format('F Y'), route('reports.month', $date));
$breadcrumbs->push('Monthly report for ' . $date->format('F Y'), route('reports.month', [$date->year, $date->month]));
}
);
Breadcrumbs::register(
'reports.budget', function (Generator $breadcrumbs, Carbon $date) {
$breadcrumbs->parent('reports.index');
$breadcrumbs->push('Budget report for ' . $date->format('F Y'), route('reports.budget', $date));
$breadcrumbs->push('Budget report for ' . $date->format('F Y'), route('reports.budget', [$date->year, $date->month]));
}
);
@@ -384,3 +395,24 @@ Breadcrumbs::register(
}
);
// tags
Breadcrumbs::register(
'tags.index', function (Generator $breadcrumbs) {
$breadcrumbs->parent('home');
$breadcrumbs->push('Tags', route('tags.index'));
}
);
Breadcrumbs::register(
'tags.create', function (Generator $breadcrumbs) {
$breadcrumbs->parent('tags.index');
$breadcrumbs->push('Create tag', route('tags.create'));
}
);
Breadcrumbs::register(
'tags.show', function (Generator $breadcrumbs, Tag $tag) {
$breadcrumbs->parent('tags.index');
$breadcrumbs->push(e($tag->tag), route('tags.show', $tag->id));
}
);

View File

@@ -6,135 +6,177 @@ use FireflyIII\Models\Category;
use FireflyIII\Models\LimitRepetition;
use FireflyIII\Models\PiggyBank;
use FireflyIII\Models\Reminder;
use FireflyIII\Models\Tag;
use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Models\TransactionJournal;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
// models
/** @noinspection PhpUnusedParameterInspection */
Route::bind(
'account',
function ($value, $route) {
if (Auth::check()) {
$account = Account::leftJoin('account_types', 'account_types.id', '=', 'accounts.account_type_id')
->where('account_types.editable', 1)
->where('accounts.id', $value)
->where('user_id', Auth::user()->id)
->first(['accounts.*']);
if ($account) {
return $account;
$object = Account::leftJoin('account_types', 'account_types.id', '=', 'accounts.account_type_id')
->where('account_types.editable', 1)
->where('accounts.id', $value)
->where('user_id', Auth::user()->id)
->first(['accounts.*']);
if ($object) {
return $object;
}
}
App::abort(404);
throw new NotFoundHttpException;
}
);
Route::bind(
'repeatedExpense', function ($value, $route) {
if (Auth::check()) {
return PiggyBank::
where('piggy_banks.id', $value)
->leftJoin('accounts', 'accounts.id', '=', 'piggy_banks.account_id')
->where('accounts.user_id', Auth::user()->id)
->where('repeats', 1)->first(['piggy_banks.*']);
}
return null;
}
);
Route::bind(
'tjSecond', function ($value, $route) {
if (Auth::check()) {
return TransactionJournal::
where('id', $value)->where('user_id', Auth::user()->id)->first();
}
return null;
}
);
/** @noinspection PhpUnusedParameterInspection */
Route::bind(
'tj', function ($value, $route) {
if (Auth::check()) {
return TransactionJournal::
where('id', $value)->where('user_id', Auth::user()->id)->first();
$object = TransactionJournal::where('id', $value)->where('user_id', Auth::user()->id)->first();
if ($object) {
return $object;
}
}
return null;
throw new NotFoundHttpException;
}
);
/** @noinspection PhpUnusedParameterInspection */
Route::bind(
'currency', function ($value, $route) {
return TransactionCurrency::find($value);
if (Auth::check()) {
$object = TransactionCurrency::find($value);
if ($object) {
return $object;
}
}
throw new NotFoundHttpException;
}
);
/** @noinspection PhpUnusedParameterInspection */
Route::bind(
'bill', function ($value, $route) {
if (Auth::check()) {
return Bill::where('id', $value)->where('user_id', Auth::user()->id)->first();
$object = Bill::where('id', $value)->where('user_id', Auth::user()->id)->first();
if ($object) {
return $object;
}
}
return null;
throw new NotFoundHttpException;
}
);
/** @noinspection PhpUnusedParameterInspection */
Route::bind(
'budget', function ($value, $route) {
if (Auth::check()) {
return Budget::where('id', $value)->where('user_id', Auth::user()->id)->first();
$object = Budget::where('id', $value)->where('user_id', Auth::user()->id)->first();
if ($object) {
return $object;
}
}
return null;
throw new NotFoundHttpException;
}
);
/** @noinspection PhpUnusedParameterInspection */
Route::bind(
'reminder', function ($value, $route) {
if (Auth::check()) {
return Reminder::where('id', $value)->where('user_id', Auth::user()->id)->first();
$object = Reminder::where('id', $value)->where('user_id', Auth::user()->id)->first();
if ($object) {
return $object;
}
}
return null;
throw new NotFoundHttpException;
}
);
/** @noinspection PhpUnusedParameterInspection */
Route::bind(
'limitrepetition', function ($value, $route) {
if (Auth::check()) {
return LimitRepetition::where('limit_repetitions.id', $value)
->leftjoin('budget_limits', 'budget_limits.id', '=', 'limit_repetitions.budget_limit_id')
->leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id')
->where('budgets.user_id', Auth::user()->id)
->first(['limit_repetitions.*']);
$object = LimitRepetition::where('limit_repetitions.id', $value)
->leftjoin('budget_limits', 'budget_limits.id', '=', 'limit_repetitions.budget_limit_id')
->leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id')
->where('budgets.user_id', Auth::user()->id)
->first(['limit_repetitions.*']);
if ($object) {
return $object;
}
}
return null;
throw new NotFoundHttpException;
}
);
/** @noinspection PhpUnusedParameterInspection */
Route::bind(
'piggyBank', function ($value, $route) {
if (Auth::check()) {
return PiggyBank::
where('piggy_banks.id', $value)
->leftJoin('accounts', 'accounts.id', '=', 'piggy_banks.account_id')
->where('accounts.user_id', Auth::user()->id)
->where('repeats', 0)->first(['piggy_banks.*']);
$object = PiggyBank::where('piggy_banks.id', $value)
->leftJoin('accounts', 'accounts.id', '=', 'piggy_banks.account_id')
->where('accounts.user_id', Auth::user()->id)
->first(['piggy_banks.*']);
if ($object) {
return $object;
}
}
return null;
throw new NotFoundHttpException;
}
);
/** @noinspection PhpUnusedParameterInspection */
Route::bind(
'category', function ($value, $route) {
if (Auth::check()) {
return Category::where('id', $value)->where('user_id', Auth::user()->id)->first();
$object = Category::where('id', $value)->where('user_id', Auth::user()->id)->first();
if ($object) {
return $object;
}
}
return null;
throw new NotFoundHttpException;
}
);
/** @noinspection PhpUnusedParameterInspection */
Route::bind(
'reminder', function ($value, $route) {
if (Auth::check()) {
/** @var \FireflyIII\Models\Reminder $object */
$object = Reminder::find($value);
if ($object) {
if ($object->remindersable->account->user_id == Auth::user()->id) {
return $object;
}
}
}
throw new NotFoundHttpException;
}
);
/** @noinspection PhpUnusedParameterInspection */
Route::bind(
'tag', function ($value, $route) {
if (Auth::check()) {
$object = Tag::where('id', $value)->where('user_id', Auth::user()->id)->first();
if ($object) {
return $object;
}
}
throw new NotFoundHttpException;
}
);
@@ -146,7 +188,7 @@ Route::get('/register', ['uses' => 'Auth\AuthController@getRegister', 'as' => 'r
Route::controllers(
[
'auth' => 'Auth\AuthController',
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]
);
@@ -156,7 +198,7 @@ Route::controllers(
* Home Controller
*/
Route::group(
['middleware' => ['auth', 'range', 'reminders']], function () {
['middleware' => ['auth', 'range', 'reminders', 'piggybanks']], function () {
Route::get('/', ['uses' => 'HomeController@index', 'as' => 'index']);
Route::get('/home', ['uses' => 'HomeController@index', 'as' => 'home']);
Route::post('/daterange', ['uses' => 'HomeController@dateRange', 'as' => 'daterange']);
@@ -181,9 +223,9 @@ Route::group(
Route::get('/bills/rescan/{bill}', ['uses' => 'BillController@rescan', 'as' => 'bills.rescan']); # rescan for matching.
Route::get('/bills/create', ['uses' => 'BillController@create', 'as' => 'bills.create']);
Route::get('/bills/edit/{bill}', ['uses' => 'BillController@edit', 'as' => 'bills.edit']);
Route::get('/bills/add/{bill}', ['uses' => 'BillController@add', 'as' => 'bills.add']);
Route::get('/bills/delete/{bill}', ['uses' => 'BillController@delete', 'as' => 'bills.delete']);
Route::get('/bills/show/{bill}', ['uses' => 'BillController@show', 'as' => 'bills.show']);
Route::post('/bills/store', ['uses' => 'BillController@store', 'as' => 'bills.store']);
Route::post('/bills/update/{bill}', ['uses' => 'BillController@update', 'as' => 'bills.update']);
Route::post('/bills/destroy/{bill}', ['uses' => 'BillController@destroy', 'as' => 'bills.destroy']);
@@ -239,7 +281,7 @@ Route::group(
Route::get('/chart/home/bills', ['uses' => 'GoogleChartController@billsOverview']);
Route::get('/chart/account/{account}/{view?}', ['uses' => 'GoogleChartController@accountBalanceChart']);
Route::get('/chart/budget/{budget}/spending/{year?}', ['uses' => 'GoogleChartController@budgetsAndSpending']);
Route::get('/chart/budgets/spending/{year?}', ['uses' => 'GoogleChartController@allBudgetsAndSpending']);
Route::get('/chart/budgets/spending/{year?}', ['uses' => 'GoogleChartController@allBudgetsAndSpending'])->where(['year' => '[0-9]+']);
Route::get('/chart/budget/{budget}/{limitrepetition}', ['uses' => 'GoogleChartController@budgetLimitSpending']);
Route::get('/chart/reports/income-expenses/{year}', ['uses' => 'GoogleChartController@yearInExp']);
Route::get('/chart/reports/income-expenses-sum/{year}', ['uses' => 'GoogleChartController@yearInExpSum']);
@@ -259,8 +301,13 @@ Route::group(
Route::get('/json/expense-accounts', ['uses' => 'JsonController@expenseAccounts', 'as' => 'json.expense-accounts']);
Route::get('/json/revenue-accounts', ['uses' => 'JsonController@revenueAccounts', 'as' => 'json.revenue-accounts']);
Route::get('/json/categories', ['uses' => 'JsonController@categories', 'as' => 'json.categories']);
Route::get('/json/box', ['uses' => 'JsonController@box', 'as' => 'json.box']);
Route::get('/json/tags', ['uses' => 'JsonController@tags', 'as' => 'json.tags']);
Route::get('/json/box/in', ['uses' => 'JsonController@boxIn', 'as' => 'json.box.in']);
Route::get('/json/box/out', ['uses' => 'JsonController@boxOut', 'as' => 'json.box.out']);
Route::get('/json/box/bills-unpaid', ['uses' => 'JsonController@boxBillsUnpaid', 'as' => 'json.box.paid']);
Route::get('/json/box/bills-paid', ['uses' => 'JsonController@boxBillsPaid', 'as' => 'json.box.unpaid']);
Route::get('/json/show-shared-reports', 'JsonController@showSharedReports');
Route::get('/json/transaction-journals/{what}', 'JsonController@transactionJournals');
Route::get('/json/show-shared-reports/set', 'JsonController@setSharedReports');
@@ -279,6 +326,7 @@ Route::group(
Route::post('/piggy-banks/destroy/{piggyBank}', ['uses' => 'PiggyBankController@destroy', 'as' => 'piggy-banks.destroy']);
Route::post('/piggy-banks/add/{piggyBank}', ['uses' => 'PiggyBankController@postAdd', 'as' => 'piggy-banks.add']); # add money
Route::post('/piggy-banks/remove/{piggyBank}', ['uses' => 'PiggyBankController@postRemove', 'as' => 'piggy-banks.remove']); # remove money.
Route::post('/piggy-banks/sort', ['uses' => 'PiggyBankController@order', 'as' => 'piggy-banks.order']);
/**
* Preferences Controller
@@ -291,18 +339,10 @@ Route::group(
*/
Route::get('/profile', ['uses' => 'ProfileController@index', 'as' => 'profile']);
Route::get('/profile/change-password', ['uses' => 'ProfileController@changePassword', 'as' => 'change-password']);
Route::get('/profile/delete-account', ['uses' => 'ProfileController@deleteAccount', 'as' => 'delete-account']);
Route::post('/profile/delete-account', ['uses' => 'ProfileController@postDeleteAccount', 'as' => 'delete-account-post']);
Route::post('/profile/change-password', ['uses' => 'ProfileController@postChangePassword', 'as' => 'change-password-post']);
/**
* Related transactions controller
*/
Route::get('/related/alreadyRelated/{tj}', ['uses' => 'RelatedController@alreadyRelated', 'as' => 'related.alreadyRelated']);
Route::post('/related/relate/{tj}/{tjSecond}', ['uses' => 'RelatedController@relate', 'as' => 'related.relate']);
Route::post('/related/removeRelation/{tj}/{tjSecond}', ['uses' => 'RelatedController@removeRelation', 'as' => 'related.removeRelation']);
Route::get('/related/remove/{tj}/{tjSecond}', ['uses' => 'RelatedController@getRemoveRelation', 'as' => 'related.getRemoveRelation']);
Route::get('/related/related/{tj}', ['uses' => 'RelatedController@related', 'as' => 'related.related']);
Route::post('/related/search/{tj}', ['uses' => 'RelatedController@search', 'as' => 'related.search']);
/**
* Reminder Controller
*/
@@ -311,19 +351,6 @@ Route::group(
Route::get('/reminder/act/{reminder}', ['uses' => 'ReminderController@act', 'as' => 'reminders.act']);
Route::get('/reminder/{reminder}', ['uses' => 'ReminderController@show', 'as' => 'reminders.show']);
/**
* Repeated Expenses Controller
*/
Route::get('/repeated-expenses', ['uses' => 'RepeatedExpenseController@index', 'as' => 'repeated.index']);
Route::get('/repeated-expenses/create', ['uses' => 'RepeatedExpenseController@create', 'as' => 'repeated.create']);
Route::get('/repeated-expenses/edit/{repeatedExpense}', ['uses' => 'RepeatedExpenseController@edit', 'as' => 'repeated.edit']);
Route::get('/repeated-expenses/delete/{repeatedExpense}', ['uses' => 'RepeatedExpenseController@delete', 'as' => 'repeated.delete']);
Route::get('/repeated-expenses/show/{repeatedExpense}', ['uses' => 'RepeatedExpenseController@show', 'as' => 'repeated.show']);
Route::post('/repeated-expense/store', ['uses' => 'RepeatedExpenseController@store', 'as' => 'repeated.store']);
Route::post('/repeated-expense/update/{repeatedExpense}', ['uses' => 'RepeatedExpenseController@update', 'as' => 'repeated.update']);
Route::post('/repeated-expense/destroy/{repeatedExpense}', ['uses' => 'RepeatedExpenseController@destroy', 'as' => 'repeated.destroy']);
/**
* Report Controller
*/
@@ -347,6 +374,22 @@ Route::group(
*/
Route::get('/search', ['uses' => 'SearchController@index', 'as' => 'search']);
/**
* Tag Controller
*/
Route::get('/tags', ['uses' => 'TagController@index', 'as' => 'tags.index']);
Route::get('/tags/create', ['uses' => 'TagController@create', 'as' => 'tags.create']);
Route::get('/tags/show/{tag}', ['uses' => 'TagController@show', 'as' => 'tags.show']);
Route::get('/tags/edit/{tag}', ['uses' => 'TagController@edit', 'as' => 'tags.edit']);
Route::get('/tags/delete/{tag}', ['uses' => 'TagController@delete', 'as' => 'tags.delete']);
Route::post('/tags/store', ['uses' => 'TagController@store', 'as' => 'tags.store']);
Route::post('/tags/update/{tag}', ['uses' => 'TagController@update', 'as' => 'tags.update']);
Route::post('/tags/destroy/{tag}', ['uses' => 'TagController@destroy', 'as' => 'tags.destroy']);
Route::post('/tags/hideTagHelp/{state}', ['uses' => 'TagController@hideTagHelp', 'as' => 'tags.hideTagHelp']);
/**
* Transaction Controller
*/
@@ -365,6 +408,7 @@ Route::group(
);
Route::post('/transaction/update/{tj}', ['uses' => 'TransactionController@update', 'as' => 'transactions.update']);
Route::post('/transaction/destroy/{tj}', ['uses' => 'TransactionController@destroy', 'as' => 'transactions.destroy']);
Route::post('/transaction/reorder', ['uses' => 'TransactionController@reorder', 'as' => 'transactions.reorder']);
/**
* Auth\Auth Controller

View File

@@ -1,10 +1,13 @@
<?php namespace FireflyIII\Models;
use App;
use Crypt;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Query\JoinClause;
use Watson\Validating\ValidatingTrait;
use Crypt;
/**
* Class Account
*
@@ -14,47 +17,72 @@ class Account extends Model
{
use SoftDeletes, ValidatingTrait;
protected $fillable = ['user_id', 'account_type_id', 'name', 'active', 'virtual_balance'];
protected $rules
= [
= [
'user_id' => 'required|exists:users,id',
'account_type_id' => 'required|exists:account_types,id',
'name' => 'required|between:1,1024|uniqueForUser:accounts,name',
'name' => 'required|between:1,1024|uniqueAccountForUser',
'active' => 'required|boolean'
];
protected $fillable = ['user_id', 'account_type_id', 'name', 'active'];
/**
* @param $fieldName
* @param array $fields
*
* @return string|null
* @return Account|null
*/
public function getMeta($fieldName)
public static function firstOrCreateEncrypted(array $fields)
{
foreach ($this->accountMeta as $meta) {
if ($meta->name == $fieldName) {
return $meta->data;
// everything but the name:
$query = Account::orderBy('id');
foreach ($fields as $name => $value) {
if ($name != 'name') {
$query->where($name, $value);
}
}
$set = $query->get(['accounts.*']);
/** @var Account $account */
foreach ($set as $account) {
if ($account->name == $fields['name']) {
return $account;
}
}
// create it!
$account = Account::create($fields);
if (is_null($account->id)) {
// could not create account:
App::abort(500, 'Could not create new account with data: ' . json_encode($fields) . ' because ' . json_encode($account->getErrors()));
return null;
}
return $account;
}
/**
* @param $value
* @param array $fields
*
* @return string
* @return Account|null
*/
public function getNameAttribute($value)
public static function firstOrNullEncrypted(array $fields)
{
if ($this->encrypted) {
return Crypt::decrypt($value);
// everything but the name:
$query = Account::orderBy('id');
foreach ($fields as $name => $value) {
if ($name != 'name') {
$query->where($name, $value);
}
}
$set = $query->get(['accounts.*']);
/** @var Account $account */
foreach ($set as $account) {
if ($account->name == $fields['name']) {
return $account;
}
}
// @codeCoverageIgnoreStart
return $value;
// @codeCoverageIgnoreEnd
return null;
}
/**
@@ -81,6 +109,48 @@ class Account extends Model
return ['created_at', 'updated_at', 'deleted_at'];
}
/**
* @param $fieldName
*
* @return string|null
*/
public function getMeta($fieldName)
{
foreach ($this->accountMeta as $meta) {
if ($meta->name == $fieldName) {
return $meta->data;
}
}
return null;
}
/**
* @param $value
*
* @return string
*/
public function getNameAttribute($value)
{
if (intval($this->encrypted) == 1) {
return Crypt::decrypt($value);
}
// @codeCoverageIgnoreStart
return $value;
// @codeCoverageIgnoreEnd
}
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function piggyBanks()
{
return $this->hasMany('FireflyIII\Models\PiggyBank');
}
/**
* @param EloquentBuilder $query
* @param array $types
@@ -94,6 +164,31 @@ class Account extends Model
$query->whereIn('account_types.type', $types);
}
/**
* @param EloquentBuilder $query
* @param string $name
* @param string $value
*/
public function scopeHasMetaValue(EloquentBuilder $query, $name, $value)
{
$joinName = str_replace('.', '_', $name);
$query->leftJoin(
'account_meta as ' . $joinName, function (JoinClause $join) use ($joinName, $name) {
$join->on($joinName . '.account_id', '=', 'accounts.id')->where($joinName . '.name', '=', $name);
}
);
$query->where($joinName . '.data', json_encode($value));
}
/**
* @param $value
*/
public function setNameAttribute($value)
{
$this->attributes['name'] = Crypt::encrypt($value);
$this->attributes['encrypted'] = true;
}
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
@@ -110,12 +205,4 @@ class Account extends Model
return $this->belongsTo('FireflyIII\User');
}
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function piggyBanks()
{
return $this->hasMany('FireflyIII\Models\PiggyBank');
}
}

View File

@@ -14,12 +14,12 @@ class AccountMeta extends Model
use ValidatingTrait;
protected $fillable = ['account_id', 'name', 'data'];
protected $rules
= [
= [
'account_id' => 'required|exists:accounts,id',
'name' => 'required|between:1,100',
'data' => 'required'
];
protected $table = 'account_meta';
protected $table = 'account_meta';
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo

View File

@@ -1,5 +1,6 @@
<?php namespace FireflyIII\Models;
use Crypt;
use Illuminate\Database\Eloquent\Model;
/**
@@ -10,7 +11,8 @@ use Illuminate\Database\Eloquent\Model;
class Bill extends Model
{
protected $fillable = ['name', 'match', 'amount_min','user_id', 'amount_max', 'date', 'repeat_freq', 'skip', 'automatch', 'active',];
protected $fillable
= ['name', 'match', 'amount_min', 'match_encrypted', 'name_encrypted', 'user_id', 'amount_max', 'date', 'repeat_freq', 'skip', 'automatch', 'active',];
/**
* @return array
@@ -20,6 +22,58 @@ class Bill extends Model
return ['created_at', 'updated_at', 'date'];
}
/**
* @param $value
*
* @return string
*/
public function getMatchAttribute($value)
{
if (intval($this->match_encrypted) == 1) {
return Crypt::decrypt($value);
}
// @codeCoverageIgnoreStart
return $value;
// @codeCoverageIgnoreEnd
}
/**
* @param $value
*
* @return string
*/
public function getNameAttribute($value)
{
if (intval($this->name_encrypted) == 1) {
return Crypt::decrypt($value);
}
// @codeCoverageIgnoreStart
return $value;
// @codeCoverageIgnoreEnd
}
/**
* @param $value
*/
public function setMatchAttribute($value)
{
$this->attributes['match'] = Crypt::encrypt($value);
$this->attributes['match_encrypted'] = true;
}
/**
* @param $value
*/
public function setNameAttribute($value)
{
$this->attributes['name'] = Crypt::encrypt($value);
$this->attributes['name_encrypted'] = true;
}
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/

View File

@@ -1,5 +1,6 @@
<?php namespace FireflyIII\Models;
use Crypt;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
@@ -31,6 +32,23 @@ class Budget extends Model
return ['created_at', 'updated_at', 'deleted_at'];
}
/**
* @param $value
*
* @return string
*/
public function getNameAttribute($value)
{
if (intval($this->encrypted) == 1) {
return Crypt::decrypt($value);
}
// @codeCoverageIgnoreStart
return $value;
// @codeCoverageIgnoreEnd
}
/**
* @return \Illuminate\Database\Eloquent\Relations\HasManyThrough
*/
@@ -39,6 +57,15 @@ class Budget extends Model
return $this->hasManyThrough('FireflyIII\Models\LimitRepetition', 'FireflyIII\Models\BudgetLimit', 'budget_id');
}
/**
* @param $value
*/
public function setNameAttribute($value)
{
$this->attributes['name'] = Crypt::encrypt($value);
$this->attributes['encrypted'] = true;
}
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/

View File

@@ -1,5 +1,7 @@
<?php namespace FireflyIII\Models;
use App;
use Crypt;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
@@ -30,6 +32,39 @@ class Category extends Model
return $this->belongsToMany('FireflyIII\Models\TransactionJournal', 'category_transaction_journal', 'category_id');
}
/**
* @param array $fields
*
* @return Account|null
*/
public static function firstOrCreateEncrypted(array $fields)
{
// everything but the name:
$query = Category::orderBy('id');
foreach ($fields as $name => $value) {
if ($name != 'name') {
$query->where($name, $value);
}
}
$set = $query->get(['categories.*']);
/** @var Category $category */
foreach ($set as $category) {
if ($category->name == $fields['name']) {
return $category;
}
}
// create it!
$category = Category::create($fields);
if (is_null($category->id)) {
// could not create account:
App::abort(500, 'Could not create new category with data: ' . json_encode($fields));
}
return $category;
}
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
@@ -38,4 +73,30 @@ class Category extends Model
return $this->belongsTo('FireflyIII\User');
}
/**
* @param $value
*/
public function setNameAttribute($value)
{
$this->attributes['name'] = Crypt::encrypt($value);
$this->attributes['encrypted'] = true;
}
/**
* @param $value
*
* @return string
*/
public function getNameAttribute($value)
{
if (intval($this->encrypted) == 1) {
return Crypt::decrypt($value);
}
// @codeCoverageIgnoreStart
return $value;
// @codeCoverageIgnoreEnd
}
}

View File

@@ -12,6 +12,8 @@ class Component extends Model
{
use SoftDeletes;
protected $fillable = ['user_id', 'name', 'class'];
/**
* @return array
*/

View File

@@ -1,5 +1,7 @@
<?php namespace FireflyIII\Models;
use Auth;
use DB;
use Illuminate\Database\Eloquent\Model;
/**
@@ -26,18 +28,23 @@ class LimitRepetition extends Model
return ['created_at', 'updated_at', 'startdate', 'enddate'];
}
/**
* @return float
*/
public function spentInRepetition()
{
$sum = \DB::table('transactions')
->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
->leftJoin('budget_transaction_journal', 'budget_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id')
->leftJoin('budget_limits', 'budget_limits.budget_id', '=', 'budget_transaction_journal.budget_id')
->leftJoin('limit_repetitions', 'limit_repetitions.budget_limit_id', '=', 'budget_limits.id')
->where('transaction_journals.date', '>=', $this->startdate->format('Y-m-d'))
->where('transaction_journals.date', '<=', $this->enddate->format('Y-m-d'))
->where('transactions.amount', '>', 0)
->where('limit_repetitions.id', '=', $this->id)
->sum('transactions.amount');
$sum = DB::table('transactions')
->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
->leftJoin('budget_transaction_journal', 'budget_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id')
->leftJoin('budget_limits', 'budget_limits.budget_id', '=', 'budget_transaction_journal.budget_id')
->leftJoin('limit_repetitions', 'limit_repetitions.budget_limit_id', '=', 'budget_limits.id')
->where('transaction_journals.date', '>=', $this->startdate->format('Y-m-d'))
->where('transaction_journals.date', '<=', $this->enddate->format('Y-m-d'))
->where('transaction_journals.user_id', Auth::user()->id)
->whereNull('transactions.deleted_at')
->where('transactions.amount', '>', 0)
->where('limit_repetitions.id', '=', $this->id)
->sum('transactions.amount');
return floatval($sum);
}

View File

@@ -1,7 +1,6 @@
<?php namespace FireflyIII\Models;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Crypt;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
@@ -14,7 +13,8 @@ class PiggyBank extends Model
{
use SoftDeletes;
protected $fillable = ['repeats', 'name', 'account_id','rep_every', 'rep_times', 'reminder_skip', 'targetamount', 'startdate', 'targetdate', 'reminder','remind_me'];
protected $fillable
= ['name', 'account_id', 'order', 'reminder_skip', 'targetamount', 'startdate', 'targetdate', 'reminder', 'remind_me'];
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
@@ -24,15 +24,6 @@ class PiggyBank extends Model
return $this->belongsTo('FireflyIII\Models\Account');
}
/**
* @param $value
*
* @return int
*/
public function getRemindMeAttribute($value) {
return intval($value) == 1;
}
/**
* Grabs the PiggyBankRepetition that's currently relevant / active
*
@@ -40,50 +31,14 @@ class PiggyBank extends Model
*/
public function currentRelevantRep()
{
if ($this->currentRep) {
if (!is_null($this->currentRep)) {
return $this->currentRep;
}
if ($this->repeats == 0) {
$rep = $this->piggyBankRepetitions()->first(['piggy_bank_repetitions.*']);
$this->currentRep = $rep;
// repeating piggy banks are no longer supported.
$rep = $this->piggyBankRepetitions()->first(['piggy_bank_repetitions.*']);
$this->currentRep = $rep;
return $rep;
} else {
$query = $this->piggyBankRepetitions()->where(
function (EloquentBuilder $q) {
$q->where(
function (EloquentBuilder $q) {
$q->where(
function (EloquentBuilder $q) {
$today = new Carbon;
$q->whereNull('startdate');
$q->orWhere('startdate', '<=', $today->format('Y-m-d 00:00:00'));
}
)->where(
function (EloquentBuilder $q) {
$today = new Carbon;
$q->whereNull('targetdate');
$q->orWhere('targetdate', '>=', $today->format('Y-m-d 00:00:00'));
}
);
}
)->orWhere(
function (EloquentBuilder $q) {
$today = new Carbon;
$q->where('startdate', '>=', $today->format('Y-m-d 00:00:00'));
$q->where('targetdate', '>=', $today->format('Y-m-d 00:00:00'));
}
);
}
)->orderBy('startdate', 'ASC');
$result = $query->first(['piggy_bank_repetitions.*']);
$this->currentRep = $result;
return $result;
}
return $rep;
}
@@ -104,6 +59,16 @@ class PiggyBank extends Model
return ['created_at', 'updated_at', 'deleted_at', 'startdate', 'targetdate'];
}
/**
* @param $value
*
* @return int
*/
public function getRemindMeAttribute($value)
{
return intval($value) == 1;
}
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
@@ -119,4 +84,30 @@ class PiggyBank extends Model
{
return $this->morphMany('FireflyIII\Models\Reminder', 'remindersable');
}
/**
* @param $value
*/
public function setNameAttribute($value)
{
$this->attributes['name'] = Crypt::encrypt($value);
$this->attributes['encrypted'] = true;
}
/**
* @param $value
*
* @return string
*/
public function getNameAttribute($value)
{
if (intval($this->encrypted) == 1) {
return Crypt::decrypt($value);
}
// @codeCoverageIgnoreStart
return $value;
// @codeCoverageIgnoreEnd
}
}

View File

@@ -1,8 +1,9 @@
<?php namespace FireflyIII\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Eloquent\Model;
/**
* Class PiggyBankRepetition
*
@@ -11,6 +12,8 @@ use Carbon\Carbon;
class PiggyBankRepetition extends Model
{
protected $fillable = ['piggy_bank_id', 'startdate', 'targetdate', 'currentamount'];
/**
* @return array
*/
@@ -27,6 +30,18 @@ class PiggyBankRepetition extends Model
return $this->belongsTo('FireflyIII\Models\PiggyBank');
}
/**
* @param EloquentBuilder $query
* @param Carbon $start
* @param Carbon $target
*
* @return $this
*/
public function scopeOnDates(EloquentBuilder $query, Carbon $start, Carbon $target)
{
return $query->where('startdate', $start->format('Y-m-d'))->where('targetdate', $target->format('Y-m-d'));
}
/**
* @param EloquentBuilder $query
* @param Carbon $date
@@ -36,16 +51,18 @@ class PiggyBankRepetition extends Model
public function scopeRelevantOnDate(EloquentBuilder $query, Carbon $date)
{
return $query->where(
function($q) use ($date) {
$q->where('startdate', '>=', $date->format('Y-m-d 00:00:00'));
function (EloquentBuilder $q) use ($date) {
$q->where('startdate', '<=', $date->format('Y-m-d 00:00:00'));
$q->orWhereNull('startdate');
})
}
)
->where(
function (EloquentBuilder $q) use ($date) {
->where(function($q) use ($date) {
$q->where('targetdate', '<=', $date->format('Y-m-d 00:00:00'));
$q->orWhereNull('targetdate');
});
$q->where('targetdate', '>=', $date->format('Y-m-d 00:00:00'));
$q->orWhereNull('targetdate');
}
);
}
}

View File

@@ -1,6 +1,7 @@
<?php namespace FireflyIII\Models;
use Carbon\Carbon;
use Crypt;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Eloquent\Model;
@@ -40,6 +41,10 @@ class Reminder extends Model
*/
public function getMetadataAttribute($value)
{
if (intval($this->encrypted) == 1) {
return json_decode(Crypt::decrypt($value));
}
return json_decode($value);
}
@@ -73,6 +78,11 @@ class Reminder extends Model
return $query->where('reminders.startdate', '=', $start->format('Y-m-d 00:00:00'))->where('reminders.enddate', '=', $end->format('Y-m-d 00:00:00'));
}
/**
* @param EloquentBuilder $query
*
* @return $this
*/
public function scopeToday(EloquentBuilder $query)
{
$today = new Carbon;
@@ -86,7 +96,8 @@ class Reminder extends Model
*/
public function setMetadataAttribute($value)
{
$this->attributes['metadata'] = json_encode($value);
$this->attributes['encrypted'] = true;
$this->attributes['metadata'] = Crypt::encrypt(json_encode($value));
}
/**

128
app/Models/Tag.php Normal file
View File

@@ -0,0 +1,128 @@
<?php
namespace FireflyIII\Models;
use App;
use Crypt;
use Illuminate\Database\Eloquent\Model;
use Watson\Validating\ValidatingTrait;
/**
* Class Tag
*
* @package FireflyIII\Models
*/
class Tag extends Model
{
use ValidatingTrait;
protected $fillable = ['user_id', 'tag', 'date', 'description', 'longitude', 'latitude', 'zoomLevel', 'tagMode'];
protected $rules
= [
'tag' => 'required|min:1|uniqueObjectForUser:tags,tag,TRUE',
'description' => 'min:1',
'date' => 'date',
'latitude' => 'numeric|min:-90|max:90',
'longitude' => 'numeric|min:-90|max:90',
'tagMode' => 'required|in:nothing,balancingAct,advancePayment'
];
/**
* @param array $fields
*
* @return Tag|null
*/
public static function firstOrCreateEncrypted(array $fields)
{
// everything but the tag:
if (isset($fields['tagMode'])) {
unset($fields['tagMode']);
}
$query = Tag::orderBy('id');
foreach ($fields as $name => $value) {
if ($name != 'tag') {
$query->where($name, $value);
}
}
$set = $query->get(['tags.*']);
/** @var Tag $tag */
foreach ($set as $tag) {
if ($tag->tag == $fields['tag']) {
return $tag;
}
}
// create it!
$fields['tagMode'] = 'nothing';
$fields['description'] = isset($fields['description']) && !is_null($fields['description']) ? $fields['description'] : '';
$tag = Tag::create($fields);
if (is_null($tag->id)) {
// could not create account:
App::abort(500, 'Could not create new tag with data: ' . json_encode($fields) . ' because ' . json_encode($tag->getErrors()));
}
return $tag;
}
/**
* @return array
*/
public function getDates()
{
return ['created_at', 'updated_at', 'date'];
}
/**
* @param $value
*
* @return string
*/
public function getDescriptionAttribute($value)
{
return Crypt::decrypt($value);
}
/**
* @param $value
*
* @return string
*/
public function getTagAttribute($value)
{
return Crypt::decrypt($value);
}
/**
* @param $value
*/
public function setDescriptionAttribute($value)
{
$this->attributes['description'] = Crypt::encrypt($value);
}
/**
* @param $value
*/
public function setTagAttribute($value)
{
$this->attributes['tag'] = Crypt::encrypt($value);
}
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function transactionjournals()
{
return $this->belongsToMany('FireflyIII\Models\TransactionJournal');
}
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function user()
{
return $this->belongsTo('FireflyIII\User');
}
}

View File

@@ -1,5 +1,7 @@
<?php namespace FireflyIII\Models;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Watson\Validating\ValidatingTrait;
@@ -30,6 +32,28 @@ class Transaction extends Model
return $this->belongsTo('FireflyIII\Models\Account');
}
/**
* @param EloquentBuilder $query
* @param Carbon $date
*
* @return mixed
*/
public function scopeAfter(EloquentBuilder $query, Carbon $date)
{
return $query->where('transaction_journals.date', '>=', $date->format('Y-m-d 00:00:00'));
}
/**
* @param EloquentBuilder $query
* @param Carbon $date
*
* @return mixed
*/
public function scopeBefore(EloquentBuilder $query, Carbon $date)
{
return $query->where('transaction_journals.date', '<=', $date->format('Y-m-d 00:00:00'));
}
/**
* @return array
*/

View File

@@ -55,6 +55,52 @@ class TransactionJournal extends Model
return $this->belongsToMany('FireflyIII\Models\Category');
}
/**
* @return float
*/
public function getAmountAttribute()
{
/** @var Transaction $t */
foreach ($this->transactions as $t) {
if ($t->amount > 0) {
return floatval($t->amount);
}
}
return 0;
}
/**
* @return Account|mixed
*/
public function getAssetAccountAttribute()
{
$positive = true; // the asset account is in the transaction with the positive amount.
if ($this->transactionType->type === 'Withdrawal') {
$positive = false;
}
/** @var Transaction $transaction */
foreach ($this->transactions()->get() as $transaction) {
if (floatval($transaction->amount) > 0 && $positive === true) {
return $transaction->account;
}
if (floatval($transaction->amount) < 0 && $positive === false) {
return $transaction->account;
}
}
return $this->transactions()->first();
}
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function transactions()
{
return $this->hasMany('FireflyIII\Models\Transaction');
}
/**
* @return array
*/
@@ -188,6 +234,14 @@ class TransactionJournal extends Model
$this->attributes['encrypted'] = true;
}
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function tags()
{
return $this->belongsToMany('FireflyIII\Models\Tag');
}
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
@@ -212,14 +266,6 @@ class TransactionJournal extends Model
return $this->belongsToMany('FireflyIII\Models\TransactionGroup');
}
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function transactions()
{
return $this->hasMany('FireflyIII\Models\Transaction');
}
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/

View File

@@ -35,6 +35,7 @@ class AppServiceProvider extends ServiceProvider
'Illuminate\Contracts\Auth\Registrar',
'FireflyIII\Services\Registrar'
);
}
}

View File

@@ -23,7 +23,227 @@ class ConfigServiceProvider extends ServiceProvider
{
config(
[
//
'twigbridge' => [
'twig' => [
/*
|--------------------------------------------------------------------------
| Extension
|--------------------------------------------------------------------------
|
| File extension for Twig view files.
|
*/
'extension' => 'twig',
/*
|--------------------------------------------------------------------------
| Accepts all Twig environment configuration options
|--------------------------------------------------------------------------
|
| http://twig.sensiolabs.org/doc/api.html#environment-options
|
*/
'environment' => [
// When set to true, the generated templates have a __toString() method
// that you can use to display the generated nodes.
// default: false
'debug' => config('app.debug', false),
// The charset used by the templates.
// default: utf-8
'charset' => 'utf-8',
// The base template class to use for generated templates.
// default: TwigBridge\Twig\Template
'base_template_class' => 'TwigBridge\Twig\Template',
// An absolute path where to store the compiled templates, or false to disable caching. If null
// then the cache file path is used.
// default: cache file storage path
'cache' => null,
// When developing with Twig, it's useful to recompile the template
// whenever the source code changes. If you don't provide a value
// for the auto_reload option, it will be determined automatically based on the debug value.
'auto_reload' => true,
// If set to false, Twig will silently ignore invalid variables
// (variables and or attributes/methods that do not exist) and
// replace them with a null value. When set to true, Twig throws an exception instead.
// default: false
'strict_variables' => false,
// If set to true, auto-escaping will be enabled by default for all templates.
// default: true
'autoescape' => true,
// A flag that indicates which optimizations to apply
// (default to -1 -- all optimizations are enabled; set it to 0 to disable)
'optimizations' => -1,
],
/*
|--------------------------------------------------------------------------
| Global variables
|--------------------------------------------------------------------------
|
| These will always be passed in and can be accessed as Twig variables.
| NOTE: these will be overwritten if you pass data into the view with the same key.
|
*/
'globals' => [],
],
'extensions' => [
/*
|--------------------------------------------------------------------------
| Extensions
|--------------------------------------------------------------------------
|
| Enabled extensions.
|
| `Twig_Extension_Debug` is enabled automatically if twig.debug is TRUE.
|
*/
'enabled' => [
'TwigBridge\Extension\Loader\Facades',
'TwigBridge\Extension\Loader\Filters',
'TwigBridge\Extension\Loader\Functions',
'TwigBridge\Extension\Laravel\Auth',
'TwigBridge\Extension\Laravel\Config',
'TwigBridge\Extension\Laravel\Dump',
'TwigBridge\Extension\Laravel\Input',
'TwigBridge\Extension\Laravel\Session',
'TwigBridge\Extension\Laravel\String',
'TwigBridge\Extension\Laravel\Translator',
'TwigBridge\Extension\Laravel\Url',
// 'TwigBridge\Extension\Laravel\Form',
// 'TwigBridge\Extension\Laravel\Html',
// 'TwigBridge\Extension\Laravel\Legacy\Facades',
],
/*
|--------------------------------------------------------------------------
| Facades
|--------------------------------------------------------------------------
|
| Available facades. Access like `{{ Config.get('foo.bar') }}`.
|
| Each facade can take an optional array of options. To mark the whole facade
| as safe you can set the option `'is_safe' => true`. Setting the facade as
| safe means that any HTML returned will not be escaped.
|
| It is advisable to not set the whole facade as safe and instead mark the
| each appropriate method as safe for security reasons. You can do that with
| the following syntax:
|
| <code>
| 'Form' => [
| 'is_safe' => [
| 'open'
| ]
| ]
| </code>
|
| The values of the `is_safe` array must match the called method on the facade
| in order to be marked as safe.
|
*/
'facades' => [
'Breadcrumbs' => [
'is_safe' => [
'renderIfExists'
]
],
'Session',
'Route',
'Auth',
'URL',
'Config',
'ExpandedForm' => [
'is_safe' => [
'date', 'text', 'select', 'balance', 'optionsList', 'checkbox', 'amount', 'tags', 'integer', 'textarea', 'location',
'multiRadio'
]
],
'Form' => [
'is_safe' => [
'input', 'select', 'checkbox', 'model', 'open', 'radio', 'textarea'
]
],
],
/*
|--------------------------------------------------------------------------
| Functions
|--------------------------------------------------------------------------
|
| Available functions. Access like `{{ secure_url(...) }}`.
|
| Each function can take an optional array of options. These options are
| passed directly to `Twig_SimpleFunction`.
|
| So for example, to mark a function as safe you can do the following:
|
| <code>
| 'link_to' => [
| 'is_safe' => ['html']
| ]
| </code>
|
| The options array also takes a `callback` that allows you to name the
| function differently in your Twig templates than what it's actually called.
|
| <code>
| 'link' => [
| 'callback' => 'link_to'
| ]
| </code>
|
*/
'functions' => [
'elixir',
'head',
'last',
'old'
],
/*
|--------------------------------------------------------------------------
| Filters
|--------------------------------------------------------------------------
|
| Available filters. Access like `{{ variable|filter }}`.
|
| Each filter can take an optional array of options. These options are
| passed directly to `Twig_SimpleFilter`.
|
| So for example, to mark a filter as safe you can do the following:
|
| <code>
| 'studly_case' => [
| 'is_safe' => ['html']
| ]
| </code>
|
| The options array also takes a `callback` that allows you to name the
| filter differently in your Twig templates than what is actually called.
|
| <code>
| 'snake' => [
| 'callback' => 'snake_case'
| ]
| </code>
|
*/
'filters' => [],
],
]
]
);
}

View File

@@ -1,12 +1,11 @@
<?php namespace FireflyIII\Providers;
use App;
use FireflyIII\Models\Account;
use FireflyIII\Models\Bill;
use FireflyIII\Models\BudgetLimit;
use FireflyIII\Models\LimitRepetition;
use FireflyIII\Models\PiggyBank;
use FireflyIII\Models\PiggyBankRepetition;
use FireflyIII\Models\Reminder;
use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionJournal;
use FireflyIII\Support\Facades\Navigation;
@@ -30,7 +29,7 @@ class EventServiceProvider extends ServiceProvider
*/
protected $listen
= [
'FireflyIII\Events\JournalSaved' => [
'FireflyIII\Events\JournalSaved' => [
'FireflyIII\Handlers\Events\RescanJournal',
'FireflyIII\Handlers\Events\UpdateJournalConnection',
@@ -62,6 +61,15 @@ class EventServiceProvider extends ServiceProvider
);
PiggyBank::deleting(
function (PiggyBank $piggyBank) {
$reminders = $piggyBank->reminders()->get();
/** @var Reminder $reminder */
foreach ($reminders as $reminder) {
$reminder->delete();
}
}
);
Account::deleted(
function (Account $account) {
@@ -74,6 +82,8 @@ class EventServiceProvider extends ServiceProvider
}
);
// move this routine to a filter
// in case of repeated piggy banks and/or other problems.
PiggyBank::created(
function (PiggyBank $piggyBank) {
$repetition = new PiggyBankRepetition;

View File

@@ -2,13 +2,20 @@
namespace FireflyIII\Providers;
use App;
use FireflyIII\Support\Amount;
use FireflyIII\Support\ExpandedForm;
use FireflyIII\Support\Navigation;
use FireflyIII\Support\Preferences;
use FireflyIII\Support\Steam;
use FireflyIII\Support\Twig\Budget;
use FireflyIII\Support\Twig\General;
use FireflyIII\Support\Twig\Journal;
use FireflyIII\Support\Twig\PiggyBank;
use FireflyIII\Validation\FireflyValidator;
use Illuminate\Support\ServiceProvider;
use Twig;
use TwigBridge\Extension\Loader\Functions;
use Validator;
/**
@@ -25,10 +32,22 @@ class FireflyServiceProvider extends ServiceProvider
return new FireflyValidator($translator, $data, $rules, $messages);
}
);
/*
* Default Twig configuration:
*/
$config = App::make('config');
Twig::addExtension(new Functions($config));
Twig::addExtension(new PiggyBank);
Twig::addExtension(new General);
Twig::addExtension(new Journal);
Twig::addExtension(new Budget);
}
public function register()
{
$this->app->bind(
'preferences', function () {
return new Preferences;
@@ -62,13 +81,18 @@ class FireflyServiceProvider extends ServiceProvider
$this->app->bind('FireflyIII\Repositories\Journal\JournalRepositoryInterface', 'FireflyIII\Repositories\Journal\JournalRepository');
$this->app->bind('FireflyIII\Repositories\Bill\BillRepositoryInterface', 'FireflyIII\Repositories\Bill\BillRepository');
$this->app->bind('FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface', 'FireflyIII\Repositories\PiggyBank\PiggyBankRepository');
$this->app->bind('FireflyIII\Repositories\Currency\CurrencyRepositoryInterface', 'FireflyIII\Repositories\Currency\CurrencyRepository');
$this->app->bind('FireflyIII\Repositories\Tag\TagRepositoryInterface', 'FireflyIII\Repositories\Tag\TagRepository');
$this->app->bind('FireflyIII\Repositories\Reminder\ReminderRepositoryInterface', 'FireflyIII\Repositories\Reminder\ReminderRepository');
$this->app->bind('FireflyIII\Support\Search\SearchInterface', 'FireflyIII\Support\Search\Search');
$this->app->bind('FireflyIII\Helpers\Help\HelpInterface', 'FireflyIII\Helpers\Help\Help');
$this->app->bind('FireflyIII\Helpers\Reminders\ReminderHelperInterface', 'FireflyIII\Helpers\Reminders\ReminderHelper');
$this->app->bind('FireflyIII\Helpers\Report\ReportHelperInterface', 'FireflyIII\Helpers\Report\ReportHelper');
$this->app->bind('FireflyIII\Helpers\Report\ReportQueryInterface', 'FireflyIII\Helpers\Report\ReportQuery');
}
}
}

View File

@@ -1,7 +1,6 @@
<?php namespace FireflyIII\Providers;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Routing\Router;
/**
@@ -32,22 +31,6 @@ class RouteServiceProvider extends ServiceProvider
{
parent::boot($router);
$router->before(
function (Request $request) {
// put IP in session if not already there.
$reminders = [];
if ($request->user()) {
//Filter::setSessionDateRange();
//Reminders::updateReminders();
//Steam::removeEmptyBudgetLimits();
//$reminders = Reminders::getReminders();
}
// View::share('reminders', $reminders);
}
);
}
/**

View File

@@ -25,4 +25,4 @@ class TestingServiceProvider extends ServiceProvider
}
}
}
}

View File

@@ -6,6 +6,7 @@ use App;
use Auth;
use Carbon\Carbon;
use Config;
use DB;
use FireflyIII\Models\Account;
use FireflyIII\Models\AccountMeta;
use FireflyIII\Models\AccountType;
@@ -14,10 +15,14 @@ use FireflyIII\Models\Preference;
use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionJournal;
use FireflyIII\Models\TransactionType;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Query\Builder;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
use Log;
use Session;
use Steam;
/**
* Class AccountRepository
@@ -28,11 +33,13 @@ class AccountRepository implements AccountRepositoryInterface
{
/**
* @param array $types
*
* @return int
*/
public function countAssetAccounts()
public function countAccounts(array $types)
{
return Auth::user()->accounts()->accountTypeIn(['Asset account', 'Default account'])->count();
return Auth::user()->accounts()->accountTypeIn($types)->count();
}
/**
@@ -47,6 +54,52 @@ class AccountRepository implements AccountRepositoryInterface
return true;
}
/**
* @param array $types
*
* @return Collection
*/
public function getAccounts(array $types)
{
$result = Auth::user()->accounts()->with(
['accountmeta' => function (HasMany $query) {
$query->where('name', 'accountRole');
}]
)->accountTypeIn($types)->orderBy('accounts.name', 'ASC')->get(['accounts.*'])->sortBy('name');
return $result;
}
/**
* @return Collection
*/
public function getCreditCards()
{
return Auth::user()->accounts()
->hasMetaValue('accountRole', 'ccAsset')
->hasMetaValue('ccType', 'monthlyFull')
->get(
[
'accounts.*',
'ccType.data as ccType',
'accountRole.data as accountRole'
]
);
}
/**
* @param TransactionJournal $journal
* @param Account $account
*
* @return Transaction
*/
public function getFirstTransaction(TransactionJournal $journal, Account $account)
{
return $journal->transactions()->where('account_id', $account->id)->first();
}
/**
* @param Preference $preference
*
@@ -64,6 +117,10 @@ class AccountRepository implements AccountRepositoryInterface
}
/**
* This method is used on the front page where (in turn) its viewed journals-tiny.php which (in turn)
* is almost the only place where formatJournal is used. Aka, we can use some custom querying to get some specific.
* fields using left joins.
*
* @param Account $account
* @param Carbon $start
* @param Carbon $end
@@ -74,22 +131,24 @@ class AccountRepository implements AccountRepositoryInterface
{
return Auth::user()
->transactionjournals()
->with(['transactions', 'transactioncurrency', 'transactiontype'])
->with(['transactions'])
->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id')
->leftJoin('accounts', 'accounts.id', '=', 'transactions.account_id')->where('accounts.id', $account->id)
->leftJoin('transaction_currencies', 'transaction_currencies.id', '=', 'transaction_journals.transaction_currency_id')
->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id')
->before($end)
->after($start)
->orderBy('transaction_journals.date', 'DESC')
->orderBy('transaction_journals.id', 'DESC')
->take(10)
->get(['transaction_journals.*']);
->get(['transaction_journals.*', 'transaction_currencies.symbol', 'transaction_types.type']);
}
/**
* @param Account $account
* @param int $page
*
* @return mixed
* @return LengthAwarePaginator
*/
public function getJournals(Account $account, $page)
{
@@ -99,7 +158,9 @@ class AccountRepository implements AccountRepositoryInterface
->withRelevantData()
->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id')
->where('transactions.account_id', $account->id)
->orderBy('date', 'DESC');
->orderBy('transaction_journals.date', 'DESC')
->orderBy('transaction_journals.order', 'ASC')
->orderBy('transaction_journals.id', 'DESC');
$query->before(Session::get('end', Carbon::now()->endOfMonth()));
$query->after(Session::get('start', Carbon::now()->startOfMonth()));
@@ -109,9 +170,140 @@ class AccountRepository implements AccountRepositoryInterface
return $paginator;
//return Paginator::make($items, $count, 50);
}
/**
* @param Account $account
*
* @return Carbon|null
*/
public function getLastActivity(Account $account)
{
$lastTransaction = $account->transactions()->leftJoin(
'transaction_journals', 'transactions.transaction_journal_id', '=', 'transaction_journals.id'
)->orderBy('transaction_journals.date', 'DESC')->first(['transactions.*', 'transaction_journals.date']);
if ($lastTransaction) {
return $lastTransaction->transactionjournal->date;
}
return null;
}
/**
* Get the accounts of a user that have piggy banks connected to them.
*
* @return Collection
*/
public function getPiggyBankAccounts()
{
$ids = [];
$start = clone Session::get('start', new Carbon);
$end = clone Session::get('end', new Carbon);
$accountIds = DB::table('piggy_banks')->distinct()->get(['piggy_banks.account_id']);
$accounts = new Collection;
foreach ($accountIds as $id) {
$ids[] = intval($id->account_id);
}
$ids = array_unique($ids);
if (count($ids) > 0) {
$accounts = Auth::user()->accounts()->whereIn('id', $ids)->get();
}
$accounts->each(
function (Account $account) use ($start, $end) {
$account->startBalance = Steam::balance($account, $start, true);
$account->endBalance = Steam::balance($account, $end, true);
$account->piggyBalance = 0;
/** @var PiggyBank $piggyBank */
foreach ($account->piggyBanks as $piggyBank) {
$account->piggyBalance += $piggyBank->currentRelevantRep()->currentamount;
}
// sum of piggy bank amounts on this account:
// diff between endBalance and piggyBalance.
// then, percentage.
$difference = $account->endBalance - $account->piggyBalance;
$account->difference = $difference;
$account->percentage = $difference != 0 && $account->endBalance != 0 ? round((($difference / $account->endBalance) * 100)) : 100;
}
);
return $accounts;
}
/**
* Get savings accounts and the balance difference in the period.
*
* @return Collection
*/
public function getSavingsAccounts()
{
$accounts = Auth::user()->accounts()->accountTypeIn(['Default account', 'Asset account'])->orderBy('accounts.name', 'ASC')
->leftJoin('account_meta', 'account_meta.account_id', '=', 'accounts.id')
->where('account_meta.name', 'accountRole')
->where('account_meta.data', '"savingAsset"')
->get(['accounts.*']);
$start = clone Session::get('start', new Carbon);
$end = clone Session::get('end', new Carbon);
$accounts->each(
function (Account $account) use ($start, $end) {
$account->startBalance = Steam::balance($account, $start);
$account->endBalance = Steam::balance($account, $end);
// diff (negative when lost, positive when gained)
$diff = $account->endBalance - $account->startBalance;
if ($diff < 0 && $account->startBalance > 0) {
// percentage lost compared to start.
$pct = (($diff * -1) / $account->startBalance) * 100;
} else {
if ($diff >= 0 && $account->startBalance > 0) {
$pct = ($diff / $account->startBalance) * 100;
} else {
$pct = 100;
}
}
$pct = $pct > 100 ? 100 : $pct;
$account->difference = $diff;
$account->percentage = round($pct);
}
);
return $accounts;
}
/**
* Get all transfers TO this account in this range.
*
* @param Account $account
* @param Carbon $start
* @param Carbon $end
*
* @return Collection
*/
public function getTransfersInRange(Account $account, Carbon $start, Carbon $end)
{
return TransactionJournal::whereIn(
'id', function (Builder $q) use ($account, $start, $end) {
$q->select('transaction_journals.id')
->from('transactions')
->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id')
->where('transactions.account_id', $account->id)
->where('transaction_journals.user_id', Auth::user()->id)
->where('transaction_journals.date', '>=', $start->format('Y-m-d'))
->where('transaction_journals.date', '<=', $end->format('Y-m-d'))
->where('transactions.amount', '>', 0)
->where('transaction_types.type', 'Transfer');
}
)->get();
}
/**
@@ -121,7 +313,7 @@ class AccountRepository implements AccountRepositoryInterface
*/
public function leftOnAccount(Account $account)
{
$balance = \Steam::balance($account);
$balance = Steam::balance($account, null, true);
/** @var PiggyBank $p */
foreach ($account->piggybanks()->get() as $p) {
$balance -= $p->currentRelevantRep()->currentamount;
@@ -151,21 +343,22 @@ class AccountRepository implements AccountRepositoryInterface
*/
public function store(array $data)
{
$newAccount = $this->_store($data);
$this->_storeMetadata($newAccount, $data);
$newAccount = $this->storeAccount($data);
$this->storeMetadata($newAccount, $data);
// continue with the opposing account:
if ($data['openingBalance'] != 0) {
$type = $data['openingBalance'] < 0 ? 'expense' : 'revenue';
$opposingData = [
'user' => $data['user'],
'accountType' => $type,
'name' => $data['name'] . ' initial balance',
'active' => false,
'user' => $data['user'],
'accountType' => $type,
'virtual_balance' => $data['virtualBalance'],
'name' => $data['name'] . ' initial balance',
'active' => false,
];
$opposing = $this->_store($opposingData);
$this->_storeInitialBalance($newAccount, $opposing, $data);
$opposing = $this->storeAccount($opposingData);
$this->storeInitialBalance($newAccount, $opposing, $data);
}
@@ -173,19 +366,30 @@ class AccountRepository implements AccountRepositoryInterface
}
/**
* @return float
*/
public function sumOfEverything()
{
return floatval(Auth::user()->transactions()->sum('amount'));
}
/**
* @param Account $account
* @param array $data
*
* @return Account
*/
public function update(Account $account, array $data)
{
// update the account:
$account->name = $data['name'];
$account->active = $data['active'] == '1' ? true : false;
$account->name = $data['name'];
$account->active = $data['active'] == '1' ? true : false;
$account->virtual_balance = $data['virtualBalance'];
$account->save();
// update meta data:
$this->_updateMetadata($account, $data);
$this->updateMetadata($account, $data);
$openingBalance = $this->openingBalanceTransaction($account);
@@ -194,7 +398,7 @@ class AccountRepository implements AccountRepositoryInterface
// if opening balance, do an update:
if ($openingBalance) {
// update existing opening balance.
$this->_updateInitialBalance($account, $openingBalance, $data);
$this->updateInitialBalance($account, $openingBalance, $data);
} else {
// create new opening balance.
$type = $data['openingBalance'] < 0 ? 'expense' : 'revenue';
@@ -204,8 +408,8 @@ class AccountRepository implements AccountRepositoryInterface
'name' => $data['name'] . ' initial balance',
'active' => false,
];
$opposing = $this->_store($opposingData);
$this->_storeInitialBalance($account, $opposing, $data);
$opposing = $this->storeAccount($opposingData);
$this->storeInitialBalance($account, $opposing, $data);
}
} else {
@@ -224,7 +428,7 @@ class AccountRepository implements AccountRepositoryInterface
*
* @return Account
*/
protected function _store(array $data)
protected function storeAccount(array $data)
{
$type = Config::get('firefly.accountTypeByIdentifier.' . $data['accountType']);
$accountType = AccountType::whereType($type)->first();
@@ -236,14 +440,23 @@ class AccountRepository implements AccountRepositoryInterface
'active' => $data['active'] === true ? true : false,
]
);
if (!$newAccount->isValid()) {
// does the account already exist?
$existingAccount = Account::where('user_id', $data['user'])->where('account_type_id', $accountType->id)->where('name', $data['name'])->first();
$searchData = [
'user_id' => $data['user'],
'account_type_id' => $accountType->id,
'name' => $data['name']
];
$existingAccount = Account::firstOrNullEncrypted($searchData);
if (!$existingAccount) {
Log::error('Account create error: ' . $newAccount->getErrors()->toJson());
var_dump($newAccount->getErrors()->toArray());
App::abort(500);
// @codeCoverageIgnoreStart
}
// @codeCoverageIgnoreEnd
$newAccount = $existingAccount;
}
$newAccount->save();
@@ -254,19 +467,23 @@ class AccountRepository implements AccountRepositoryInterface
* @param Account $account
* @param array $data
*/
protected function _storeMetadata(Account $account, array $data)
protected function storeMetadata(Account $account, array $data)
{
$metaData = new AccountMeta(
[
'account_id' => $account->id,
'name' => 'accountRole',
'data' => $data['accountRole']
]
);
if (!$metaData->isValid()) {
App::abort(500);
$validFields = ['accountRole', 'ccMonthlyPaymentDate', 'ccType'];
foreach ($validFields as $field) {
if (isset($data[$field])) {
$metaData = new AccountMeta(
[
'account_id' => $account->id,
'name' => $field,
'data' => $data[$field]
]
);
$metaData->save();
}
}
$metaData->save();
}
/**
@@ -276,7 +493,7 @@ class AccountRepository implements AccountRepositoryInterface
*
* @return TransactionJournal
*/
protected function _storeInitialBalance(Account $account, Account $opposing, array $data)
protected function storeInitialBalance(Account $account, Account $opposing, array $data)
{
$type = $data['openingBalance'] < 0 ? 'Withdrawal' : 'Deposit';
$transactionType = TransactionType::whereType($type)->first();
@@ -345,32 +562,29 @@ class AccountRepository implements AccountRepositoryInterface
* @param Account $account
* @param array $data
*/
protected function _updateMetadata(Account $account, array $data)
protected function updateMetadata(Account $account, array $data)
{
$metaEntries = $account->accountMeta()->get();
$updated = false;
$validFields = ['accountRole', 'ccMonthlyPaymentDate', 'ccType'];
/** @var AccountMeta $entry */
foreach ($metaEntries as $entry) {
if ($entry->name == 'accountRole') {
$entry->data = $data['accountRole'];
$updated = true;
foreach ($validFields as $field) {
$entry = $account->accountMeta()->where('name', $field)->first();
// update if new data is present:
if ($entry && isset($data[$field])) {
$entry->data = $data[$field];
$entry->save();
}
}
if ($updated === false) {
$metaData = new AccountMeta(
[
'account_id' => $account->id,
'name' => 'accountRole',
'data' => $data['accountRole']
]
);
if (!$metaData->isValid()) {
App::abort(500);
// no entry but data present?
if (!$entry && isset($data[$field])) {
$metaData = new AccountMeta(
[
'account_id' => $account->id,
'name' => $field,
'data' => $data[$field]
]
);
$metaData->save();
}
$metaData->save();
}
}
@@ -382,7 +596,7 @@ class AccountRepository implements AccountRepositoryInterface
*
* @return TransactionJournal
*/
protected function _updateInitialBalance(Account $account, TransactionJournal $journal, array $data)
protected function updateInitialBalance(Account $account, TransactionJournal $journal, array $data)
{
$journal->date = $data['openingBalanceDate'];
@@ -400,4 +614,4 @@ class AccountRepository implements AccountRepositoryInterface
return $journal;
}
}
}

View File

@@ -2,11 +2,14 @@
namespace FireflyIII\Repositories\Account;
use FireflyIII\Models\Account;
use FireflyIII\Models\TransactionJournal;
use FireflyIII\Models\Preference;
use Illuminate\Support\Collection;
use Carbon\Carbon;
use FireflyIII\Models\Account;
use FireflyIII\Models\Preference;
use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionJournal;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
/**
* Interface AccountRepositoryInterface
*
@@ -14,6 +17,13 @@ use Carbon\Carbon;
*/
interface AccountRepositoryInterface
{
/**
* @param array $types
*
* @return int
*/
public function countAccounts(array $types);
/**
* @param Account $account
*
@@ -22,9 +32,43 @@ interface AccountRepositoryInterface
public function destroy(Account $account);
/**
* @return int
* @param array $types
*
* @return mixed
*/
public function countAssetAccounts();
public function getAccounts(array $types);
/**
* @param TransactionJournal $journal
* @param Account $account
*
* @return Transaction
*/
public function getFirstTransaction(TransactionJournal $journal, Account $account);
/**
* @return Collection
*/
public function getCreditCards();
/**
* Get the accounts of a user that have piggy banks connected to them.
*
* @return Collection
*/
public function getPiggyBankAccounts();
/**
* Get all transfers TO this account in this range.
*
* @param Account $account
* @param Carbon $start
* @param Carbon $end
*
* @return Collection
*/
public function getTransfersInRange(Account $account, Carbon $start, Carbon $end);
/**
* @param Preference $preference
@@ -44,12 +88,38 @@ interface AccountRepositoryInterface
/**
* @param Account $account
* @param string $range
* @param $page
*
* @return mixed
* @return LengthAwarePaginator
*/
public function getJournals(Account $account, $page);
/**
* @param Account $account
*
* @return Carbon|null
*/
public function getLastActivity(Account $account);
/**
* @return float
*/
public function sumOfEverything();
/**
* Get savings accounts and the balance difference in the period.
*
* @return Collection
*/
public function getSavingsAccounts();
/**
* @param Account $account
*
* @return float
*/
public function leftOnAccount(Account $account);
/**
* @param Account $account
*
@@ -71,11 +141,4 @@ interface AccountRepositoryInterface
* @return Account
*/
public function update(Account $account, array $data);
/**
* @param Account $account
*
* @return float
*/
public function leftOnAccount(Account $account);
}
}

View File

@@ -2,9 +2,15 @@
namespace FireflyIII\Repositories\Bill;
use Auth;
use Carbon\Carbon;
use FireflyIII\Models\Account;
use FireflyIII\Models\AccountType;
use FireflyIII\Models\Bill;
use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionJournal;
use Illuminate\Database\Query\JoinClause;
use Illuminate\Support\Collection;
use Log;
use Navigation;
@@ -15,6 +21,121 @@ use Navigation;
*/
class BillRepository implements BillRepositoryInterface
{
/**
* Create a fake bill to help the chart controller.
*
* @param string $description
* @param Carbon $date
* @param float $amount
*
* @return Bill
*/
public function createFakeBill($description, Carbon $date, $amount)
{
$bill = new Bill;
$bill->name = $description;
$bill->match = $description;
$bill->amount_min = $amount;
$bill->amount_max = $amount;
$bill->date = $date;
$bill->repeat_freq = 'monthly';
$bill->skip = 0;
$bill->automatch = false;
$bill->active = false;
return $bill;
}
/**
* @param Bill $bill
*
* @return mixed
*/
public function destroy(Bill $bill)
{
return $bill->delete();
}
/**
* @return Collection
*/
public function getActiveBills()
{
/** @var Collection $set */
$set = Auth::user()->bills()->orderBy('name', 'ASC')->where('active', 1)->get()->sortBy('name');
return $set;
}
/**
* @return Collection
*/
public function getBills()
{
/** @var Collection $set */
$set = Auth::user()->bills()->orderBy('name', 'ASC')->get()->sortBy('name');
return $set;
}
/**
* @param Bill $bill
*
* @return Collection
*/
public function getJournals(Bill $bill)
{
return $bill->transactionjournals()->withRelevantData()
->leftJoin(
'transactions', function (JoinClause $join) {
$join->on('transactions.transaction_journal_id', '=', 'transaction_journals.id')
->where('transactions.amount', '>', 0);
}
)
->orderBy('transaction_journals.date', 'DESC')
->orderBy('transaction_journals.order', 'ASC')
->orderBy('transaction_journals.id', 'DESC')
->get(['transaction_journals.*', 'transactions.amount']);
}
/**
* Get all journals that were recorded on this bill between these dates.
*
* @param Bill $bill
* @param Carbon $start
* @param Carbon $end
*
* @return Collection
*/
public function getJournalsInRange(Bill $bill, Carbon $start, Carbon $end)
{
return $bill->transactionjournals()->before($end)->after($start)->get();
}
/**
* @param Bill $bill
*
* @return Collection
*/
public function getPossiblyRelatedJournals(Bill $bill)
{
$set = \DB::table('transactions')->where('amount', '>', 0)->where('amount', '>=', $bill->amount_min)->where('amount', '<=', $bill->amount_max)->get(
['transaction_journal_id']
);
$ids = [];
/** @var Transaction $entry */
foreach ($set as $entry) {
$ids[] = intval($entry->transaction_journal_id);
}
$journals = new Collection;
if (count($ids) > 0) {
$journals = Auth::user()->transactionjournals()->whereIn('id', $ids)->get();
}
return $journals;
}
/**
* Every bill repeats itself weekly, monthly or yearly (or whatever). This method takes a date-range (usually the view-range of Firefly itself)
* and returns date ranges that fall within the given range; those ranges are the bills expected. When a bill is due on the 14th of the month and
@@ -51,16 +172,26 @@ class BillRepository implements BillRepositoryInterface
foreach ($billStarts as $dateEntry) {
if ($dateEntry['end'] > $start && $dateEntry['start'] < $end) {
// count transactions for bill in this range (not relevant yet!):
// $count = $bill->transactionjournals()->before($dateEntry['end'])->after($dateEntry['start'])->count();
// if ($count == 0) {
$validRanges[] = $dateEntry;
// }
}
}
return $validRanges;
// echo $bill->name;
// var_dump($validRanges);
}
/**
* @param Bill $bill
*
* @return Carbon|null
*/
public function lastFoundMatch(Bill $bill)
{
$last = $bill->transactionjournals()->orderBy('date', 'DESC')->first();
if ($last) {
return $last->date;
}
return null;
}
/**
@@ -80,10 +211,12 @@ class BillRepository implements BillRepositoryInterface
* $today is the start of the next period, to make sure FF3 won't miss anything
* when the current period has a transaction journal.
*/
$today = Navigation::addPeriod(new Carbon, $bill->repeat_freq, 0);
/** @var \Carbon\Carbon $obj */
$obj = new Carbon;
$today = Navigation::addPeriod($obj, $bill->repeat_freq, 0);
$skip = $bill->skip + 1;
$start = Navigation::startOfPeriod(new Carbon, $bill->repeat_freq);
$start = Navigation::startOfPeriod($obj, $bill->repeat_freq);
/*
* go back exactly one month/week/etc because FF3 does not care about 'next'
* bills if they're too far into the past.
@@ -184,6 +317,12 @@ class BillRepository implements BillRepositoryInterface
Log::debug('TOTAL match is true!');
$journal->bill()->associate($bill);
$journal->save();
} else {
if ((!$wordMatch || !$amountMatch) && $bill->id == $journal->bill_id) {
// if no match, but bill used to match, remove it:
$journal->bill_id = null;
$journal->save();
}
}
}

View File

@@ -5,13 +5,89 @@ namespace FireflyIII\Repositories\Bill;
use Carbon\Carbon;
use FireflyIII\Models\Bill;
use FireflyIII\Models\TransactionJournal;
use Illuminate\Support\Collection;
/**
* Interface BillRepositoryInterface
*
* @package FireflyIII\Repositories\Bill
*/
interface BillRepositoryInterface {
interface BillRepositoryInterface
{
/**
* Create a fake bill to help the chart controller.
*
* @param string $description
* @param Carbon $date
* @param float $amount
*
* @return Bill
*/
public function createFakeBill($description, Carbon $date, $amount);
/**
* @param Bill $bill
*
* @return mixed
*/
public function destroy(Bill $bill);
/**
* @return Collection
*/
public function getActiveBills();
/**
* @return Collection
*/
public function getBills();
/**
* @param Bill $bill
*
* @return Collection
*/
public function getJournals(Bill $bill);
/**
* Get all journals that were recorded on this bill between these dates.
*
* @param Bill $bill
* @param Carbon $start
* @param Carbon $end
*
* @return Collection
*/
public function getJournalsInRange(Bill $bill, Carbon $start, Carbon $end);
/**
* @param Bill $bill
*
* @return Collection
*/
public function getPossiblyRelatedJournals(Bill $bill);
/**
* Every bill repeats itself weekly, monthly or yearly (or whatever). This method takes a date-range (usually the view-range of Firefly itself)
* and returns date ranges that fall within the given range; those ranges are the bills expected. When a bill is due on the 14th of the month and
* you give 1st and the 31st of that month as argument, you'll get one response, matching the range of your bill.
*
* @param Bill $bill
* @param Carbon $start
* @param Carbon $end
*
* @return mixed
*/
public function getRanges(Bill $bill, Carbon $start, Carbon $end);
/**
* @param Bill $bill
*
* @return Carbon|null
*/
public function lastFoundMatch(Bill $bill);
/**
* @param Bill $bill
@@ -21,17 +97,12 @@ interface BillRepositoryInterface {
public function nextExpectedMatch(Bill $bill);
/**
* Every bill repeats itself weekly, monthly or yearly (or whatever). This method takes a date-range (usually the view-range of Firefly itself)
* and returns date ranges that fall within the given range; those ranges are the bills expected. When a bill is due on the 14th of the month and
* you give 1st and the 31st of that month as argument, you'll get one response, matching the range of your bill.
* @param Bill $bill
* @param TransactionJournal $journal
*
* @param Bill $bill
* @param Carbon $start
* @param Carbon $end
*
* @return mixed
* @return bool
*/
public function getRanges(Bill $bill, Carbon $start, Carbon $end);
public function scan(Bill $bill, TransactionJournal $journal);
/**
* @param array $data
@@ -48,12 +119,4 @@ interface BillRepositoryInterface {
*/
public function update(Bill $bill, array $data);
/**
* @param Bill $bill
* @param TransactionJournal $journal
*
* @return bool
*/
public function scan(Bill $bill, TransactionJournal $journal);
}
}

View File

@@ -2,11 +2,14 @@
namespace FireflyIII\Repositories\Budget;
use Auth;
use Carbon\Carbon;
use FireflyIII\Models\Budget;
use FireflyIII\Models\BudgetLimit;
use FireflyIII\Models\LimitRepetition;
use Illuminate\Database\Query\Builder as QueryBuilder;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
/**
* Class BudgetRepository
@@ -16,6 +19,31 @@ use Illuminate\Pagination\LengthAwarePaginator;
class BudgetRepository implements BudgetRepositoryInterface
{
/**
* @return void
*/
public function cleanupBudgets()
{
$limits = BudgetLimit::leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id')->get(['budget_limits.*']);
// loop budget limits:
$found = [];
/** @var BudgetLimit $limit */
foreach ($limits as $limit) {
$key = $limit->budget_id . '-' . $limit->startdate;
if (isset($found[$key])) {
$limit->delete();
} else {
$found[$key] = true;
}
unset($key);
}
// delete limits with amount 0:
BudgetLimit::where('amount', 0)->delete();
}
/**
* @param Budget $budget
*
@@ -28,6 +56,101 @@ class BudgetRepository implements BudgetRepositoryInterface
return true;
}
/**
* @param Budget $budget
* @param Carbon $date
*
* @return float
*/
public function expensesOnDay(Budget $budget, Carbon $date)
{
return floatval($budget->transactionjournals()->lessThan(0)->transactionTypes(['Withdrawal'])->onDate($date)->sum('amount'));
}
/**
* @return Collection
*/
public function getActiveBudgets()
{
$budgets = Auth::user()->budgets()->where('active', 1)->get();
$budgets->sortBy('name');
return $budgets;
}
/**
* @param Budget $budget
* @param Carbon $start
* @param Carbon $end
*
* @return Collection
*/
public function getBudgetLimitRepetitions(Budget $budget, Carbon $start, Carbon $end)
{
/** @var Collection $repetitions */
return LimitRepetition::
leftJoin('budget_limits', 'limit_repetitions.budget_limit_id', '=', 'budget_limits.id')
->where('limit_repetitions.startdate', '<=', $end->format('Y-m-d 00:00:00'))
->where('limit_repetitions.startdate', '>=', $start->format('Y-m-d 00:00:00'))
->where('budget_limits.budget_id', $budget->id)
->get(['limit_repetitions.*']);
}
/**
* @param Budget $budget
*
* @return Collection
*/
public function getBudgetLimits(Budget $budget)
{
return $budget->budgetLimits()->orderBy('startdate', 'DESC')->get();
}
/**
* @return Collection
*/
public function getBudgets()
{
$budgets = Auth::user()->budgets()->get();
$budgets->sortBy('name');
return $budgets;
}
/**
* @param Budget $budget
* @param Carbon $date
*
* @return LimitRepetition|null
*/
public function getCurrentRepetition(Budget $budget, Carbon $date)
{
return $budget->limitrepetitions()->where('limit_repetitions.startdate', $date)->first(['limit_repetitions.*']);
}
/**
* @param Budget $budget
*
* @return Carbon
*/
public function getFirstBudgetLimitDate(Budget $budget)
{
$limit = $budget->budgetlimits()->orderBy('startdate', 'ASC')->first();
if ($limit) {
return $limit->startdate;
}
return Carbon::now()->startOfYear();
}
/**
* @return Collection
*/
public function getInactiveBudgets()
{
return Auth::user()->budgets()->where('active', 0)->get();
}
/**
* Returns all the transaction journals for a limit, possibly limited by a limit repetition.
*
@@ -42,7 +165,10 @@ class BudgetRepository implements BudgetRepositoryInterface
$offset = intval(\Input::get('page')) > 0 ? intval(\Input::get('page')) * $take : 0;
$setQuery = $budget->transactionJournals()->withRelevantData()->take($take)->offset($offset)->orderBy('date', 'DESC');
$setQuery = $budget->transactionJournals()->withRelevantData()->take($take)->offset($offset)
->orderBy('transaction_journals.date', 'DESC')
->orderBy('transaction_journals.order', 'ASC')
->orderBy('transaction_journals.id', 'DESC');
$countQuery = $budget->transactionJournals();
@@ -54,9 +180,95 @@ class BudgetRepository implements BudgetRepositoryInterface
$set = $setQuery->get(['transaction_journals.*']);
$count = $countQuery->count();
return new LengthAwarePaginator($set, $count, $take, $offset);
}
/**
* @param Budget $budget
*
* @return Carbon
*/
public function getLastBudgetLimitDate(Budget $budget)
{
$limit = $budget->budgetlimits()->orderBy('startdate', 'DESC')->first();
if ($limit) {
return $limit->startdate;
}
return Carbon::now()->startOfYear();
}
/**
* @param Budget $budget
* @param Carbon $date
*
* @return float|null
*/
public function getLimitAmountOnDate(Budget $budget, Carbon $date)
{
$repetition = LimitRepetition::leftJoin('budget_limits', 'limit_repetitions.budget_limit_id', '=', 'budget_limits.id')
->where('limit_repetitions.startdate', $date->format('Y-m-d 00:00:00'))
->where('budget_limits.budget_id', $budget->id)
->first(['limit_repetitions.*']);
if ($repetition) {
return floatval($repetition->amount);
}
return null;
}
/**
* @param Carbon $start
* @param Carbon $end
*
* @return Collection
*/
public function getWithoutBudget(Carbon $start, Carbon $end)
{
return Auth::user()
->transactionjournals()
->leftJoin('budget_transaction_journal', 'budget_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id')
->whereNull('budget_transaction_journal.id')
->before($end)
->after($start)
->orderBy('transaction_journals.date', 'DESC')
->orderBy('transaction_journals.order', 'ASC')
->orderBy('transaction_journals.id', 'DESC')
->get(['transaction_journals.*']);
}
/**
* @param Carbon $start
* @param Carbon $end
*
* @return mixed
*/
public function getWithoutBudgetSum(Carbon $start, Carbon $end)
{
$noBudgetSet = Auth::user()
->transactionjournals()
->whereNotIn(
'transaction_journals.id', function (QueryBuilder $query) use ($start, $end) {
$query
->select('transaction_journals.id')
->from('transaction_journals')
->leftJoin('budget_transaction_journal', 'budget_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id')
->where('transaction_journals.date', '>=', $start->format('Y-m-d 00:00:00'))
->where('transaction_journals.date', '<=', $end->format('Y-m-d 00:00:00'))
->whereNotNull('budget_transaction_journal.budget_id');
}
)
->before($end)
->after($start)
->lessThan(0)
->transactionTypes(['Withdrawal'])
->get();
return floatval($noBudgetSet->sum('amount')) * -1;
}
/**
* @param Budget $budget
* @param Carbon $date
@@ -91,6 +303,18 @@ class BudgetRepository implements BudgetRepositoryInterface
return $newBudget;
}
/**
* @param Budget $budget
* @param Carbon $start
* @param Carbon $end
*
* @return float
*/
public function sumBudgetExpensesInPeriod(Budget $budget, $start, $end)
{
return floatval($budget->transactionjournals()->before($end)->after($start)->lessThan(0)->sum('amount')) * -1;
}
/**
* @param Budget $budget
* @param array $data
@@ -100,7 +324,8 @@ class BudgetRepository implements BudgetRepositoryInterface
public function update(Budget $budget, array $data)
{
// update the account:
$budget->name = $data['name'];
$budget->name = $data['name'];
$budget->active = $data['active'];
$budget->save();
return $budget;
@@ -115,10 +340,12 @@ class BudgetRepository implements BudgetRepositoryInterface
*/
public function updateLimitAmount(Budget $budget, Carbon $date, $amount)
{
// there should be a budget limit for this startdate:
/** @var BudgetLimit $limit */
$limit = $budget->limitrepetitions()->where('limit_repetitions.startdate', $date)->first(['limit_repetitions.*']);
$limit = $budget->budgetlimits()->where('budget_limits.startdate', $date)->first(['budget_limits.*']);
if (!$limit) {
// create one!
// if not, create one!
$limit = new BudgetLimit;
$limit->budget()->associate($budget);
$limit->startdate = $date;
@@ -126,6 +353,10 @@ class BudgetRepository implements BudgetRepositoryInterface
$limit->repeat_freq = 'monthly';
$limit->repeats = 0;
$limit->save();
// likewise, there should be a limit repetition to match the end date
// (which is always the end of the month) but that is caught by an event.
} else {
if ($amount > 0) {
$limit->amount = $amount;
@@ -139,4 +370,4 @@ class BudgetRepository implements BudgetRepositoryInterface
}
}
}

View File

@@ -5,6 +5,7 @@ namespace FireflyIII\Repositories\Budget;
use Carbon\Carbon;
use FireflyIII\Models\Budget;
use FireflyIII\Models\LimitRepetition;
use Illuminate\Support\Collection;
/**
* Interface BudgetRepositoryInterface
@@ -13,6 +14,11 @@ use FireflyIII\Models\LimitRepetition;
*/
interface BudgetRepositoryInterface
{
/**
* @return void
*/
public function cleanupBudgets();
/**
* @param Budget $budget
*
@@ -26,31 +32,53 @@ interface BudgetRepositoryInterface
*
* @return float
*/
public function spentInMonth(Budget $budget, Carbon $date);
public function expensesOnDay(Budget $budget, Carbon $date);
/**
* @return Collection
*/
public function getActiveBudgets();
/**
* @param Budget $budget
* @param Carbon $start
* @param Carbon $end
*
* @return Collection
*/
public function getBudgetLimitRepetitions(Budget $budget, Carbon $start, Carbon $end);
/**
* @param Budget $budget
*
* @return Collection
*/
public function getBudgetLimits(Budget $budget);
/**
* @return Collection
*/
public function getBudgets();
/**
* @param Budget $budget
* @param Carbon $date
* @param $amount
*
* @return mixed
* @return LimitRepetition|null
*/
public function updateLimitAmount(Budget $budget, Carbon $date, $amount);
/**
* @param array $data
*
* @return Budget
*/
public function store(array $data);
public function getCurrentRepetition(Budget $budget, Carbon $date);
/**
* @param Budget $budget
* @param array $data
*
* @return Budget
* @return Carbon
*/
public function update(Budget $budget, array $data);
public function getFirstBudgetLimitDate(Budget $budget);
/**
* @return Collection
*/
public function getInactiveBudgets();
/**
* Returns all the transaction journals for a limit, possibly limited by a limit repetition.
@@ -63,4 +91,76 @@ interface BudgetRepositoryInterface
*/
public function getJournals(Budget $budget, LimitRepetition $repetition = null, $take = 50);
}
/**
* @param Budget $budget
*
* @return Carbon
*/
public function getLastBudgetLimitDate(Budget $budget);
/**
* @param Budget $budget
* @param Carbon $date
*
* @return float
*/
public function getLimitAmountOnDate(Budget $budget, Carbon $date);
/**
* @param Carbon $start
* @param Carbon $end
*
* @return Collection
*/
public function getWithoutBudget(Carbon $start, Carbon $end);
/**
* @param Carbon $start
* @param Carbon $end
*
* @return mixed
*/
public function getWithoutBudgetSum(Carbon $start, Carbon $end);
/**
* @param Budget $budget
* @param Carbon $date
*
* @return float
*/
public function spentInMonth(Budget $budget, Carbon $date);
/**
* @param array $data
*
* @return Budget
*/
public function store(array $data);
/**
* @param Budget $budget
* @param Carbon $start
* @param Carbon $end
*
* @return float
*/
public function sumBudgetExpensesInPeriod(Budget $budget, $start, $end);
/**
* @param Budget $budget
* @param array $data
*
* @return Budget
*/
public function update(Budget $budget, array $data);
/**
* @param Budget $budget
* @param Carbon $date
* @param $amount
*
* @return mixed
*/
public function updateLimitAmount(Budget $budget, Carbon $date, $amount);
}

View File

@@ -2,7 +2,13 @@
namespace FireflyIII\Repositories\Category;
use Auth;
use Carbon\Carbon;
use DB;
use FireflyIII\Models\Category;
use FireflyIII\Models\TransactionJournal;
use Illuminate\Database\Query\JoinClause;
use Illuminate\Support\Collection;
/**
* Class CategoryRepository
@@ -12,6 +18,17 @@ use FireflyIII\Models\Category;
class CategoryRepository implements CategoryRepositoryInterface
{
/**
* @param Category $category
*
* @return int
*/
public function countJournals(Category $category)
{
return $category->transactionJournals()->count();
}
/**
* @param Category $category
*
@@ -24,6 +41,150 @@ class CategoryRepository implements CategoryRepositoryInterface
return true;
}
/**
* @return Collection
*/
public function getCategories()
{
/** @var Collection $set */
$set = Auth::user()->categories()->orderBy('name', 'ASC')->get();
$set->sortBy(
function (Category $category) {
return $category->name;
}
);
return $set;
}
/**
* @param Carbon $start
* @param Carbon $end
*
* @return Collection
*/
public function getCategoriesAndExpenses($start, $end)
{
return TransactionJournal::
where('transaction_journals.user_id', Auth::user()->id)
->leftJoin(
'transactions',
function (JoinClause $join) {
$join->on('transaction_journals.id', '=', 'transactions.transaction_journal_id')->where('amount', '>', 0);
}
)
->leftJoin(
'category_transaction_journal', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id'
)
->leftJoin('categories', 'categories.id', '=', 'category_transaction_journal.category_id')
->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id')
->before($end)
->where('categories.user_id', Auth::user()->id)
->after($start)
->where('transaction_types.type', 'Withdrawal')
->groupBy('categories.id')
->orderBy('sum', 'DESC')
->get(['categories.id', 'categories.encrypted', 'categories.name', DB::Raw('SUM(`transactions`.`amount`) AS `sum`')]);
}
/**
* @param Category $category
*
* @return Carbon
*/
public function getFirstActivityDate(Category $category)
{
/** @var TransactionJournal $first */
$first = $category->transactionjournals()->orderBy('date', 'ASC')->first();
if ($first) {
return $first->date;
}
return new Carbon;
}
/**
* @param Category $category
* @param int $page
*
* @return Collection
*/
public function getJournals(Category $category, $page)
{
$offset = $page > 0 ? $page * 50 : 0;
return $category->transactionJournals()->withRelevantData()->take(50)->offset($offset)
->orderBy('transaction_journals.date', 'DESC')
->orderBy('transaction_journals.order', 'ASC')
->orderBy('transaction_journals.id', 'DESC')
->get(
['transaction_journals.*']
);
}
/**
* @param Category $category
*
* @return Carbon|null
*/
public function getLatestActivity(Category $category)
{
$latest = $category->transactionjournals()
->orderBy('transaction_journals.date', 'DESC')
->orderBy('transaction_journals.order', 'ASC')
->orderBy('transaction_journals.id', 'DESC')
->first();
if ($latest) {
return $latest->date;
}
return null;
}
/**
* @param Carbon $start
* @param Carbon $end
*
* @return Collection
*/
public function getWithoutCategory(Carbon $start, Carbon $end)
{
return Auth::user()
->transactionjournals()
->leftJoin('category_transaction_journal', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id')
->whereNull('category_transaction_journal.id')
->before($end)
->after($start)
->orderBy('transaction_journals.date', 'DESC')
->orderBy('transaction_journals.order', 'ASC')
->orderBy('transaction_journals.id', 'DESC')
->get(['transaction_journals.*']);
}
/**
* @param Category $category
* @param Carbon $start
* @param Carbon $end
*
* @return float
*/
public function spentInPeriodSum(Category $category, Carbon $start, Carbon $end)
{
return floatval($category->transactionjournals()->before($end)->after($start)->lessThan(0)->sum('amount')) * -1;
}
/**
* @param Category $category
* @param Carbon $date
*
* @return float
*/
public function spentOnDaySum(Category $category, Carbon $date)
{
return floatval($category->transactionjournals()->onDate($date)->lessThan(0)->sum('amount')) * -1;
}
/**
* @param array $data
@@ -57,5 +218,4 @@ class CategoryRepository implements CategoryRepositoryInterface
return $category;
}
}
}

View File

@@ -2,7 +2,9 @@
namespace FireflyIII\Repositories\Category;
use Carbon\Carbon;
use FireflyIII\Models\Category;
use Illuminate\Support\Collection;
/**
* Interface CategoryRepositoryInterface
@@ -11,6 +13,13 @@ use FireflyIII\Models\Category;
*/
interface CategoryRepositoryInterface
{
/**
* @param Category $category
*
* @return int
*/
public function countJournals(Category $category);
/**
* @param Category $category
*
@@ -18,6 +27,66 @@ interface CategoryRepositoryInterface
*/
public function destroy(Category $category);
/**
* @return Collection
*/
public function getCategories();
/**
* @param Carbon $start
* @param Carbon $end
*
* @return Collection
*/
public function getCategoriesAndExpenses($start, $end);
/**
* @param Category $category
*
* @return Carbon
*/
public function getFirstActivityDate(Category $category);
/**
* @param Category $category
* @param int $page
*
* @return Collection
*/
public function getJournals(Category $category, $page);
/**
* @param Category $category
*
* @return Carbon|null
*/
public function getLatestActivity(Category $category);
/**
* @param Carbon $start
* @param Carbon $end
*
* @return Collection
*/
public function getWithoutCategory(Carbon $start, Carbon $end);
/**
* @param Category $category
* @param \Carbon\Carbon $start
* @param \Carbon\Carbon $end
*
* @return float
*/
public function spentInPeriodSum(Category $category, Carbon $start, Carbon $end);
/**
* @param Category $category
* @param Carbon $date
*
* @return float
*/
public function spentOnDaySum(Category $category, Carbon $date);
/**
* @param array $data
*
@@ -33,4 +102,4 @@ interface CategoryRepositoryInterface
*/
public function update(Category $category, array $data);
}
}

View File

@@ -0,0 +1,84 @@
<?php
namespace FireflyIII\Repositories\Currency;
use FireflyIII\Models\Preference;
use FireflyIII\Models\TransactionCurrency;
use Illuminate\Support\Collection;
/**
* Class CurrencyRepository
*
* @package FireflyIII\Repositories\Currency
*/
class CurrencyRepository implements CurrencyRepositoryInterface
{
/**
* @param TransactionCurrency $currency
*
* @return int
*/
public function countJournals(TransactionCurrency $currency)
{
return $currency->transactionJournals()->count();
}
/**
* @return Collection
*/
public function get()
{
return TransactionCurrency::get();
}
/**
* @param Preference $preference
*
* @return TransactionCurrency
*/
public function getCurrencyByPreference(Preference $preference)
{
$preferred = TransactionCurrency::whereCode($preference->data)->first();
if (is_null($preferred)) {
$preferred = TransactionCurrency::first();
}
return $preferred;
}
/**
* @param array $data
*
* @return TransactionCurrency
*/
public function store(array $data)
{
$currency = TransactionCurrency::create(
[
'name' => $data['name'],
'code' => $data['code'],
'symbol' => $data['symbol'],
]
);
return $currency;
}
/**
* @param TransactionCurrency $currency
* @param array $data
*
* @return TransactionCurrency
*/
public function update(TransactionCurrency $currency, array $data)
{
$currency->code = $data['code'];
$currency->symbol = $data['symbol'];
$currency->name = $data['name'];
$currency->save();
return $currency;
}
}

View File

@@ -0,0 +1,52 @@
<?php
namespace FireflyIII\Repositories\Currency;
use FireflyIII\Models\Preference;
use FireflyIII\Models\TransactionCurrency;
use Illuminate\Support\Collection;
/**
* Interface CurrencyRepositoryInterface
*
* @package FireflyIII\Repositories\Currency
*/
interface CurrencyRepositoryInterface
{
/**
* @param TransactionCurrency $currency
*
* @return int
*/
public function countJournals(TransactionCurrency $currency);
/**
* @return Collection
*/
public function get();
/**
* @param Preference $preference
*
* @return TransactionCurrency
*/
public function getCurrencyByPreference(Preference $preference);
/**
* @param array $data
*
* @return TransactionCurrency
*/
public function store(array $data);
/**
* @param TransactionCurrency $currency
* @param array $data
*
* @return TransactionCurrency
*/
public function update(TransactionCurrency $currency, array $data);
}

View File

@@ -2,15 +2,21 @@
namespace FireflyIII\Repositories\Journal;
use App;
use Auth;
use Carbon\Carbon;
use DB;
use FireflyIII\Models\Account;
use FireflyIII\Models\AccountType;
use FireflyIII\Models\Budget;
use FireflyIII\Models\Category;
use FireflyIII\Models\Tag;
use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionJournal;
use FireflyIII\Models\TransactionType;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
use Log;
/**
* Class JournalRepository
@@ -21,85 +27,140 @@ class JournalRepository implements JournalRepositoryInterface
{
/**
* @param int $reminderId
*
* Get the account_id, which is the asset account that paid for the transaction.
*
* @param TransactionJournal $journal
*
* @return mixed
* @return bool
*/
public function getAssetAccount(TransactionJournal $journal)
public function deactivateReminder($reminderId)
{
$positive = true; // the asset account is in the transaction with the positive amount.
switch ($journal->transactionType->type) {
case 'Withdrawal':
$positive = false;
break;
}
/** @var Transaction $transaction */
foreach ($journal->transactions()->get() as $transaction) {
if (floatval($transaction->amount) > 0 && $positive === true) {
return $transaction->account_id;
}
if (floatval($transaction->amount) < 0 && $positive === false) {
return $transaction->account_id;
}
$reminder = Auth::user()->reminders()->find($reminderId);
if ($reminder) {
$reminder->active = 0;
$reminder->save();
}
return $journal->transactions()->first()->account_id;
}
/**
* @param string $query
* @param TransactionJournal $journal
*
* @return bool
*/
public function delete(TransactionJournal $journal)
{
// delete transactions first:
/** @var Transaction $transaction */
foreach ($journal->transactions()->get() as $transaction) {
$transaction->delete();
}
$journal->delete();
return true;
}
/**
* Get users first transaction journal
*
* @return TransactionJournal
*/
public function first()
{
return Auth::user()->transactionjournals()->orderBy('date', 'ASC')->first(['transaction_journals.*']);
}
/**
* @param TransactionJournal $journal
* @param Transaction $transaction
*
* @return float
*/
public function getAmountBefore(TransactionJournal $journal, Transaction $transaction)
{
return floatval(
$transaction->account->transactions()->leftJoin(
'transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id'
)
->where('transaction_journals.date', '<=', $journal->date->format('Y-m-d'))
->where('transaction_journals.order', '>=', $journal->order)
->where('transaction_journals.id', '!=', $journal->id)
->sum('transactions.amount')
);
}
/**
* @param TransactionType $dbType
*
* @return Collection
*/
public function searchRelated($query, TransactionJournal $journal)
public function getJournalsOfType(TransactionType $dbType)
{
$start = clone $journal->date;
$end = clone $journal->date;
$start->startOfMonth();
$end->endOfMonth();
return Auth::user()->transactionjournals()->where('transaction_type_id', $dbType->id)->orderBy('id', 'DESC')->take(50)->get();
}
// get already related transactions:
$exclude = [$journal->id];
foreach ($journal->transactiongroups()->get() as $group) {
foreach ($group->transactionjournals()->get() as $current) {
$exclude[] = $current->id;
/**
* @param array $types
* @param int $offset
* @param int $page
*
* @return LengthAwarePaginator
*/
public function getJournalsOfTypes(array $types, $offset, $page)
{
$set = Auth::user()->transactionJournals()->transactionTypes($types)->withRelevantData()->take(50)->offset($offset)
->orderBy('date', 'DESC')
->orderBy('order', 'ASC')
->orderBy('id', 'DESC')
->get(
['transaction_journals.*']
);
$count = Auth::user()->transactionJournals()->transactionTypes($types)->count();
$journals = new LengthAwarePaginator($set, $count, 50, $page);
return $journals;
}
/**
* @param $type
*
* @return TransactionType
*/
public function getTransactionType($type)
{
return TransactionType::whereType($type)->first();
}
/**
* @param $id
* @param Carbon $date
*
* @return TransactionJournal
*/
public function getWithDate($id, Carbon $date)
{
return Auth::user()->transactionjournals()->where('id', $id)->where('date', $date->format('Y-m-d'))->first();
}
/**
*
* * Remember: a balancingAct takes at most one expense and one transfer.
* an advancePayment takes at most one expense, infinite deposits and NO transfers.
*
* @param TransactionJournal $journal
* @param array $array
*
* @return void
*/
public function saveTags(TransactionJournal $journal, array $array)
{
/** @var \FireflyIII\Repositories\Tag\TagRepositoryInterface $tagRepository */
$tagRepository = App::make('FireflyIII\Repositories\Tag\TagRepositoryInterface');
foreach ($array as $name) {
if (strlen(trim($name)) > 0) {
$tag = Tag::firstOrCreateEncrypted(['tag' => $name, 'user_id' => $journal->user_id]);
$tagRepository->connect($journal, $tag);
}
}
$exclude = array_unique($exclude);
/** @var Collection $collection */
$collection = Auth::user()->transactionjournals()
->withRelevantData()
->before($end)->after($start)->where('encrypted', 0)
->whereNotIn('id', $exclude)
->where('description', 'LIKE', '%' . $query . '%')
->get();
// manually search encrypted entries:
/** @var Collection $encryptedCollection */
$encryptedCollection = Auth::user()->transactionjournals()
->withRelevantData()
->before($end)->after($start)
->where('encrypted', 1)
->whereNotIn('id', $exclude)
->get();
$encrypted = $encryptedCollection->filter(
function (TransactionJournal $journal) use ($query) {
$strPos = strpos(strtolower($journal->description), strtolower($query));
if ($strPos !== false) {
return $journal;
}
return null;
}
);
return $collection->merge($encrypted);
}
/**
@@ -128,52 +189,19 @@ class JournalRepository implements JournalRepositoryInterface
// store or get category
if (strlen($data['category']) > 0) {
$category = Category::firstOrCreate(['name' => $data['category'], 'user_id' => $data['user']]);
$category = Category::firstOrCreateEncrypted(['name' => $data['category'], 'user_id' => $data['user']]);
$journal->categories()->save($category);
}
// store or get budget
if (intval($data['budget_id']) > 0) {
/** @var \FireflyIII\Models\Budget $budget */
$budget = Budget::find($data['budget_id']);
$journal->budgets()->save($budget);
}
// store accounts (depends on type)
switch ($transactionType->type) {
case 'Withdrawal':
$from = Account::find($data['account_id']);
if (strlen($data['expense_account']) > 0) {
$toType = AccountType::where('type', 'Expense account')->first();
$to = Account::firstOrCreate(
['user_id' => $data['user'], 'account_type_id' => $toType->id, 'name' => $data['expense_account'], 'active' => 1]
);
} else {
$toType = AccountType::where('type', 'Cash account')->first();
$to = Account::firstOrCreate(['user_id' => $data['user'], 'account_type_id' => $toType->id, 'name' => 'Cash account', 'active' => 1]);
}
break;
case 'Deposit':
$to = Account::find($data['account_id']);
if (strlen($data['revenue_account']) > 0) {
$fromType = AccountType::where('type', 'Revenue account')->first();
$from = Account::firstOrCreate(
['user_id' => $data['user'], 'account_type_id' => $fromType->id, 'name' => $data['revenue_account'], 'active' => 1]
);
} else {
$toType = AccountType::where('type', 'Cash account')->first();
$from = Account::firstOrCreate(['user_id' => $data['user'], 'account_type_id' => $toType->id, 'name' => 'Cash account', 'active' => 1]);
}
break;
case 'Transfer':
$from = Account::find($data['account_from_id']);
$to = Account::find($data['account_to_id']);
break;
}
list($from, $to) = $this->storeAccounts($transactionType, $data);
// store accompanying transactions.
Transaction::create( // first transaction.
@@ -193,12 +221,16 @@ class JournalRepository implements JournalRepositoryInterface
$journal->completed = 1;
$journal->save();
// store tags
if (isset($data['tags']) && is_array($data['tags'])) {
$this->saveTags($journal, $data['tags']);
}
return $journal;
}
/**
* @param TransactionJournal $journal
* @param array $data
@@ -216,53 +248,20 @@ class JournalRepository implements JournalRepositoryInterface
// unlink all categories, recreate them:
$journal->categories()->detach();
if (strlen($data['category']) > 0) {
$category = Category::firstOrCreate(['name' => $data['category'], 'user_id' => $data['user']]);
$category = Category::firstOrCreateEncrypted(['name' => $data['category'], 'user_id' => $data['user']]);
$journal->categories()->save($category);
}
// unlink all budgets and recreate them:
$journal->budgets()->detach();
if (intval($data['budget_id']) > 0) {
/** @var \FireflyIII\Models\Budget $budget */
$budget = Budget::find($data['budget_id']);
$journal->budgets()->save($budget);
}
// store accounts (depends on type)
switch ($journal->transactionType->type) {
case 'Withdrawal':
$from = Account::find($data['account_id']);
if (strlen($data['expense_account']) > 0) {
$toType = AccountType::where('type', 'Expense account')->first();
$to = Account::firstOrCreate(
['user_id' => $data['user'], 'account_type_id' => $toType->id, 'name' => $data['expense_account'], 'active' => 1]
);
} else {
$toType = AccountType::where('type', 'Cash account')->first();
$to = Account::firstOrCreate(['user_id' => $data['user'], 'account_type_id' => $toType->id, 'name' => 'Cash account', 'active' => 1]);
}
break;
case 'Deposit':
$to = Account::find($data['account_id']);
if (strlen($data['revenue_account']) > 0) {
$fromType = AccountType::where('type', 'Revenue account')->first();
$from = Account::firstOrCreate(
['user_id' => $data['user'], 'account_type_id' => $fromType->id, 'name' => $data['revenue_account'], 'active' => 1]
);
} else {
$toType = AccountType::where('type', 'Cash account')->first();
$from = Account::firstOrCreate(['user_id' => $data['user'], 'account_type_id' => $toType->id, 'name' => 'Cash account', 'active' => 1]);
}
break;
case 'Transfer':
$from = Account::find($data['account_from_id']);
$to = Account::find($data['account_to_id']);
break;
}
list($from, $to) = $this->storeAccounts($journal->transactionType, $data);
// update the from and to transaction.
/** @var Transaction $transaction */
@@ -274,7 +273,7 @@ class JournalRepository implements JournalRepositoryInterface
$transaction->save();
}
if (floatval($transaction->amount) > 0) {
$transaction->amount = $data['amount'];
$transaction->amount = $data['amount'];
$transaction->account_id = $to->id;
$transaction->save();
}
@@ -283,7 +282,112 @@ class JournalRepository implements JournalRepositoryInterface
$journal->save();
// update tags:
if (isset($data['tags']) && is_array($data['tags'])) {
$this->updateTags($journal, $data['tags']);
}
return $journal;
}
}
/**
* @param TransactionJournal $journal
* @param array $array
*
* @return void
*/
public function updateTags(TransactionJournal $journal, array $array)
{
// create tag repository
/** @var \FireflyIII\Repositories\Tag\TagRepositoryInterface $tagRepository */
$tagRepository = App::make('FireflyIII\Repositories\Tag\TagRepositoryInterface');
// find or create all tags:
$tags = [];
$ids = [];
foreach ($array as $name) {
if (strlen(trim($name)) > 0) {
$tag = Tag::firstOrCreateEncrypted(['tag' => $name, 'user_id' => $journal->user_id]);
$tags[] = $tag;
$ids[] = $tag->id;
}
}
// delete all tags connected to journal not in this array:
if (count($ids) > 0) {
DB::table('tag_transaction_journal')->where('transaction_journal_id', $journal->id)->whereNotIn('tag_id', $ids)->delete();
}
// if count is zero, delete them all:
if (count($ids) == 0) {
DB::table('tag_transaction_journal')->where('transaction_journal_id', $journal->id)->delete();
}
// connect each tag to journal (if not yet connected):
/** @var Tag $tag */
foreach ($tags as $tag) {
$tagRepository->connect($journal, $tag);
}
}
/**
* @param TransactionType $type
* @param array $data
*
* @return array
*/
protected function storeAccounts(TransactionType $type, array $data)
{
$from = null;
$to = null;
switch ($type->type) {
case 'Withdrawal':
$from = Account::find($data['account_id']);
if (strlen($data['expense_account']) > 0) {
$toType = AccountType::where('type', 'Expense account')->first();
$to = Account::firstOrCreateEncrypted(
['user_id' => $data['user'], 'account_type_id' => $toType->id, 'name' => $data['expense_account'], 'active' => 1]
);
} else {
$toType = AccountType::where('type', 'Cash account')->first();
$to = Account::firstOrCreateEncrypted(
['user_id' => $data['user'], 'account_type_id' => $toType->id, 'name' => 'Cash account', 'active' => 1]
);
}
break;
case 'Deposit':
$to = Account::find($data['account_id']);
if (strlen($data['revenue_account']) > 0) {
$fromType = AccountType::where('type', 'Revenue account')->first();
$from = Account::firstOrCreateEncrypted(
['user_id' => $data['user'], 'account_type_id' => $fromType->id, 'name' => $data['revenue_account'], 'active' => 1]
);
} else {
$toType = AccountType::where('type', 'Cash account')->first();
$from = Account::firstOrCreateEncrypted(
['user_id' => $data['user'], 'account_type_id' => $toType->id, 'name' => 'Cash account', 'active' => 1]
);
}
break;
case 'Transfer':
$from = Account::find($data['account_from_id']);
$to = Account::find($data['account_to_id']);
break;
}
if (is_null($to->id)) {
Log::error('"to"-account is null, so we cannot continue!');
App::abort(500, '"to"-account is null, so we cannot continue!');
}
if (is_null($from->id)) {
Log::error('"from"-account is null, so we cannot continue!');
App::abort(500, '"from"-account is null, so we cannot continue!');
}
return [$from, $to];
}
}

View File

@@ -2,7 +2,11 @@
namespace FireflyIII\Repositories\Journal;
use Carbon\Carbon;
use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionJournal;
use FireflyIII\Models\TransactionType;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
/**
@@ -13,22 +17,79 @@ use Illuminate\Support\Collection;
interface JournalRepositoryInterface
{
/**
* @param int $reminderId
*
* Get the account_id, which is the asset account that paid for the transaction.
*
* @param TransactionJournal $journal
*
* @return int
* @return bool
*/
public function getAssetAccount(TransactionJournal $journal);
public function deactivateReminder($reminderId);
/**
* @param string $query
* @param TransactionJournal $journal
*
* @return bool
*/
public function delete(TransactionJournal $journal);
/**
* Get users first transaction journal
*
* @return TransactionJournal
*/
public function first();
/**
* @param TransactionJournal $journal
* @param Transaction $transaction
*
* @return float
*/
public function getAmountBefore(TransactionJournal $journal, Transaction $transaction);
/**
* @param TransactionType $dbType
*
* @return Collection
*/
public function searchRelated($query, TransactionJournal $journal);
public function getJournalsOfType(TransactionType $dbType);
/**
* @param array $types
* @param int $offset
* @param int $page
*
* @return LengthAwarePaginator
*/
public function getJournalsOfTypes(array $types, $offset, $page);
/**
* @param $type
*
* @return TransactionType
*/
public function getTransactionType($type);
/**
* @param $id
* @param Carbon $date
*
* @return TransactionJournal
*/
public function getWithDate($id, Carbon $date);
/**
* @param TransactionJournal $journal
* @param array $array
*
* @return void
/**
*
* @param TransactionJournal $journal
* @param array $array
*
* @return void
*/
public function saveTags(TransactionJournal $journal, array $array);
/**
* @param array $data
@@ -44,4 +105,12 @@ interface JournalRepositoryInterface
* @return mixed
*/
public function update(TransactionJournal $journal, array $data);
}
/**
* @param TransactionJournal $journal
* @param array $array
*
* @return mixed
*/
public function updateTags(TransactionJournal $journal, array $array);
}

View File

@@ -2,12 +2,12 @@
namespace FireflyIII\Repositories\PiggyBank;
use Amount;
use Auth;
use Carbon\Carbon;
use DB;
use FireflyIII\Models\PiggyBank;
use FireflyIII\Models\PiggyBankEvent;
use FireflyIII\Models\PiggyBankRepetition;
use FireflyIII\Models\Reminder;
use Illuminate\Support\Collection;
use Navigation;
@@ -19,8 +19,8 @@ use Navigation;
class PiggyBankRepository implements PiggyBankRepositoryInterface
{
/**
* @SuppressWarnings("CyclomaticComplexity") // It's exactly 5. So I don't mind.
*
* Based on the piggy bank, the reminder-setting and
* other variables this method tries to divide the piggy bank into equal parts. Each is
@@ -70,6 +70,19 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface
return $bars;
}
/**
* @param PiggyBank $piggyBank
* @param $amount
*
* @return bool
*/
public function createEvent(PiggyBank $piggyBank, $amount)
{
PiggyBankEvent::create(['date' => Carbon::now(), 'amount' => $amount, 'piggy_bank_id' => $piggyBank->id]);
return true;
}
/**
* @param array $data
*
@@ -88,6 +101,79 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface
return $part;
}
/**
* @param PiggyBank $piggyBank
*
* @return bool
*/
public function destroy(PiggyBank $piggyBank)
{
return $piggyBank->delete();
}
/**
* @param PiggyBank $piggyBank
*
* @return Collection
*/
public function getEventSummarySet(PiggyBank $piggyBank)
{
return DB::table('piggy_bank_events')->where('piggy_bank_id', $piggyBank->id)->groupBy('date')->get(['date', DB::Raw('SUM(`amount`) AS `sum`')]);
}
/**
* @param PiggyBank $piggyBank
*
* @return Collection
*/
public function getEvents(PiggyBank $piggyBank)
{
return $piggyBank->piggyBankEvents()->orderBy('date', 'DESC')->orderBy('id', 'DESC')->get();
}
/**
* @return Collection
*/
public function getPiggyBanks()
{
/** @var Collection $set */
$set = Auth::user()->piggyBanks()->orderBy('order', 'ASC')->get();
return $set;
}
/**
* Set all piggy banks to order 0.
*
* @return void
*/
public function reset()
{
DB::table('piggy_banks')
->leftJoin('accounts', 'accounts.id', '=', 'piggy_banks.id')
->where('accounts.user_id', Auth::user()->id)
->update(['order' => 0, 'piggy_banks.updated_at' => DB::Raw('NOW()')]);
}
/**
*
* set id of piggy bank.
*
* @param int $id
* @param int $order
*
* @return void
*/
public function setOrder($id, $order)
{
$piggyBank = PiggyBank::leftJoin('accounts', 'accounts.id', '=', 'piggy_banks.account_id')->where('accounts.user_id', Auth::user()->id)
->where('piggy_banks.id', $id)->first(['piggy_banks.*']);
if ($piggyBank) {
$piggyBank->order = $order;
$piggyBank->save();
}
}
/**
* @param array $data
*
@@ -102,10 +188,11 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface
}
/**
* @param PiggyBank $account
* @param PiggyBank $piggyBank
* @param array $data
*
* @return PiggyBank
* @internal param PiggyBank $account
*/
public function update(PiggyBank $piggyBank, array $data)
{
@@ -123,14 +210,10 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface
$piggyBank->targetdate = $data['targetdate'];
$piggyBank->reminder = $data['reminder'];
$piggyBank->startdate = $data['startdate'];
$piggyBank->rep_length = isset($data['rep_length']) ? $data['rep_length'] : null;
$piggyBank->rep_every = isset($data['rep_every']) ? $data['rep_every'] : null;
$piggyBank->rep_times = isset($data['rep_times']) ? $data['rep_times'] : null;
$piggyBank->remind_me = isset($data['remind_me']) && $data['remind_me'] == '1' ? 1 : 0;
$piggyBank->save();
return $piggyBank;
}
}
}

View File

@@ -4,9 +4,7 @@ namespace FireflyIII\Repositories\PiggyBank;
use FireflyIII\Models\PiggyBank;
use FireflyIII\Models\PiggyBankRepetition;
use FireflyIII\Models\Reminder;
use Illuminate\Support\Collection;
use Carbon\Carbon;
/**
* Interface PiggyBankRepositoryInterface
@@ -16,9 +14,7 @@ use Carbon\Carbon;
interface PiggyBankRepositoryInterface
{
/**
* @SuppressWarnings("CyclomaticComplexity") // It's exactly 5. So I don't mind.
*
* Based on the piggy bank, the reminder-setting and
* other variables this method tries to divide the piggy bank into equal parts. Each is
@@ -30,6 +26,18 @@ interface PiggyBankRepositoryInterface
*/
public function calculateParts(PiggyBankRepetition $repetition);
/**
* @return Collection
*/
public function getPiggyBanks();
/**
* @param PiggyBank $piggyBank
*
* @return Collection
*/
public function getEvents(PiggyBank $piggyBank);
/**
* @param array $data
*
@@ -37,6 +45,45 @@ interface PiggyBankRepositoryInterface
*/
public function createPiggyBankPart(array $data);
/**
* @param PiggyBank $piggyBank
* @param $amount
*
* @return bool
*/
public function createEvent(PiggyBank $piggyBank, $amount);
/**
* @param PiggyBank $piggyBank
*
* @return Collection
*/
public function getEventSummarySet(PiggyBank $piggyBank);
/**
* @param PiggyBank $piggyBank
*
* @return bool
*/
public function destroy(PiggyBank $piggyBank);
/**
* Set all piggy banks to order 0.
*
* @return void
*/
public function reset();
/**
*
* set id of piggy bank.
*
* @param int $id
* @param int $order
*
* @return void
*/
public function setOrder($id, $order);
/**
@@ -47,10 +94,10 @@ interface PiggyBankRepositoryInterface
public function store(array $data);
/**
* @param PiggyBank $account
* @param PiggyBank $piggyBank
* @param array $data
*
* @return PiggyBank
*/
public function update(PiggyBank $piggyBank, array $data);
}
}

View File

@@ -2,10 +2,9 @@
namespace FireflyIII\Repositories\PiggyBank;
use FireflyIII\Models\Reminder;
use FireflyIII\Models\PiggyBankRepetition;
use Carbon\Carbon;
use FireflyIII\Models\PiggyBankRepetition;
use FireflyIII\Models\Reminder;
/**
* Class PiggyBankPart

View File

@@ -0,0 +1,116 @@
<?php
namespace FireflyIII\Repositories\Reminder;
use App;
use Auth;
use Carbon\Carbon;
use FireflyIII\Models\Reminder;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection;
/**
* Class ReminderRepository
*
* @package FireflyIII\Repositories\Reminder
*/
class ReminderRepository implements ReminderRepositoryInterface
{
/** @var \FireflyIII\Helpers\Reminders\ReminderHelperInterface */
protected $helper;
/**
*
*/
public function __construct()
{
/** @var \FireflyIII\Helpers\Reminders\ReminderHelperInterface helper */
$this->helper = App::make('FireflyIII\Helpers\Reminders\ReminderHelperInterface');
}
/**
* @return Collection
*/
public function getActiveReminders()
{
$today = new Carbon;
// active reminders:
$active = Auth::user()->reminders()
->where('notnow', 0)
->where('active', 1)
->where('startdate', '<=', $today->format('Y-m-d 00:00:00'))
->where('enddate', '>=', $today->format('Y-m-d 00:00:00'))
->get();
$active->each(
function (Reminder $reminder) {
$reminder->description = $this->helper->getReminderText($reminder);
}
);
return $active;
}
/**
* @return Collection
*/
public function getDismissedReminders()
{
$dismissed = Auth::user()->reminders()
->where('notnow', 1)
->get();
$dismissed->each(
function (Reminder $reminder) {
$reminder->description = $this->helper->getReminderText($reminder);
}
);
return $dismissed;
}
/**
* @return Collection
*/
public function getExpiredReminders()
{
$expired = Auth::user()->reminders()
->where('notnow', 0)
->where('active', 1)
->where(
function (Builder $q) {
$today = new Carbon;
$q->where('startdate', '>', $today->format('Y-m-d 00:00:00'));
$q->orWhere('enddate', '<', $today->format('Y-m-d 00:00:00'));
}
)->get();
$expired->each(
function (Reminder $reminder) {
$reminder->description = $this->helper->getReminderText($reminder);
}
);
return $expired;
}
/**
* @return Collection
*/
public function getInactiveReminders()
{
$inactive = Auth::user()->reminders()
->where('active', 0)
->get();
$inactive->each(
function (Reminder $reminder) {
$reminder->description = $this->helper->getReminderText($reminder);
}
);
return $inactive;
}
}

View File

@@ -0,0 +1,35 @@
<?php
namespace FireflyIII\Repositories\Reminder;
use Illuminate\Support\Collection;
/**
* Interface ReminderRepositoryInterface
*
* @package FireflyIII\Repositories\Reminder
*/
interface ReminderRepositoryInterface
{
/**
* @return Collection
*/
public function getActiveReminders();
/**
* @return Collection
*/
public function getDismissedReminders();
/**
* @return Collection
*/
public function getExpiredReminders();
/**
* @return Collection
*/
public function getInactiveReminders();
}

Some files were not shown because too many files have changed in this diff Show More