Compare commits

..

85 Commits

Author SHA1 Message Date
github-actions
4aaea89f2c Auto commit for release 'branch-v6.2' on 2024-12-21 2024-12-21 12:27:07 +01:00
James Cole
4fbf7b38fb Do not pull in invalid transactions 2024-12-21 11:40:34 +01:00
James Cole
76075401f9 Recalculate amounts. 2024-12-21 11:33:58 +01:00
James Cole
e2a20dd63d Command to recalculate foreign amounts. 2024-12-21 11:20:48 +01:00
James Cole
b52a1f3eb1 Respond to currency changes. 2024-12-21 07:12:11 +01:00
James Cole
7fd5a88122 Add more column conversions. 2024-12-20 05:31:16 +01:00
James Cole
1a1baa5cda Add observers for amounts. 2024-12-20 05:20:37 +01:00
James Cole
577d671a0c Add native amount column 2024-12-19 06:21:17 +01:00
James Cole
380029ffd8 Fix missing method. 2024-12-18 16:57:11 +01:00
github-actions
76cc27a267 Auto commit for release 'branch-v6.2' on 2024-12-18 2024-12-18 16:45:41 +01:00
James Cole
e8a6f30e4e Merge branch 'develop' into v6.2
# Conflicts:
#	composer.lock
#	config/firefly.php
#	package-lock.json
2024-12-18 16:39:22 +01:00
github-actions
fe6021a3d6 Auto commit for release 'v6.1.25' on 2024-12-18 2024-12-18 16:36:08 +01:00
James Cole
563c54702b Update changelog. 2024-12-18 16:31:37 +01:00
James Cole
4d67d27ba0 Fix #9546 2024-12-18 16:29:19 +01:00
James Cole
edf3876a57 Merge branch 'main' into develop 2024-12-18 16:26:35 +01:00
James Cole
2d10f255c2 Fix reference to old method. 2024-12-18 16:18:06 +01:00
James Cole
ee76cc6761 Fix methods 2024-12-18 16:13:32 +01:00
James Cole
f197e6623b Merge pull request #9551 from firefly-iii/dependabot/github_actions/github/command-1.3.0 2024-12-16 06:59:19 +01:00
James Cole
42a9809450 Merge pull request #9550 from firefly-iii/dependabot/npm_and_yarn/develop/chartjs-chart-sankey-0.14.0 2024-12-16 06:59:10 +01:00
James Cole
444f80a933 Merge pull request #9549 from firefly-iii/dependabot/npm_and_yarn/develop/ag-grid-community/styles-33.0.2 2024-12-16 06:59:01 +01:00
dependabot[bot]
4b985c818a Bump github/command from 1.2.2 to 1.3.0
Bumps [github/command](https://github.com/github/command) from 1.2.2 to 1.3.0.
- [Release notes](https://github.com/github/command/releases)
- [Commits](https://github.com/github/command/compare/v1.2.2...v1.3.0)

---
updated-dependencies:
- dependency-name: github/command
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-12-16 03:49:31 +00:00
github-actions
2e62fe7b72 Auto commit for release 'develop' on 2024-12-16 2024-12-16 04:22:19 +01:00
dependabot[bot]
ccd182aed9 Bump chartjs-chart-sankey from 0.13.0 to 0.14.0
Bumps [chartjs-chart-sankey](https://github.com/kurkle/chartjs-chart-sankey) from 0.13.0 to 0.14.0.
- [Release notes](https://github.com/kurkle/chartjs-chart-sankey/releases)
- [Commits](https://github.com/kurkle/chartjs-chart-sankey/compare/v0.13.0...v0.14.0)

---
updated-dependencies:
- dependency-name: chartjs-chart-sankey
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-12-16 03:06:22 +00:00
dependabot[bot]
615eef3fdd Bump @ag-grid-community/styles from 32.3.3 to 33.0.2
Bumps [@ag-grid-community/styles](https://github.com/ag-grid/ag-grid) from 32.3.3 to 33.0.2.
- [Release notes](https://github.com/ag-grid/ag-grid/releases)
- [Commits](https://github.com/ag-grid/ag-grid/compare/v32.3.3...v33.0.2)

---
updated-dependencies:
- dependency-name: "@ag-grid-community/styles"
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-12-16 03:06:13 +00:00
James Cole
d4e4907363 Add option for manual activation. 2024-12-15 19:59:36 +01:00
James Cole
c205e93876 Fix https://github.com/firefly-iii/firefly-iii/issues/7288 2024-12-15 19:51:46 +01:00
James Cole
3b24bb99bb Merge branch 'v6.2' of github.com:firefly-iii/firefly-iii into v6.2 2024-12-15 19:51:37 +01:00
James Cole
2814cd1b2a Better name 2024-12-15 19:51:30 +01:00
github-actions
5285e1ac14 Auto commit for release 'branch-v6.2' on 2024-12-15 2024-12-15 16:16:13 +01:00
James Cole
48a999cf91 Fix old reference. 2024-12-15 16:11:48 +01:00
James Cole
3117c8846e Rename branch release. 2024-12-15 12:31:36 +01:00
github-actions
6bb297e76f Auto commit for release 'branch-v6.2' on 2024-12-15 2024-12-15 10:32:00 +01:00
James Cole
bc698f67ea Merge branch 'main' into v6.2 2024-12-15 09:07:04 +01:00
James Cole
f1c859aaa3 Update build job 2024-12-15 08:57:55 +01:00
James Cole
2d0aa207d4 Fix various piggy bank errors 2024-12-15 08:50:57 +01:00
James Cole
4a75e9c262 Merge branch 'v6.2' of github.com:firefly-iii/firefly-iii into v6.2 2024-12-15 08:20:52 +01:00
James Cole
ee7c4b8863 Fix user test notification. 2024-12-15 08:20:42 +01:00
github-actions
f782979d6c Auto commit for release 'develop' on 2024-12-15 2024-12-15 04:09:28 +01:00
github-actions
53cce6510c Auto commit for release 'branch-v6.2' on 2024-12-14 2024-12-14 22:20:13 +01:00
github-actions
53252b84fd Auto commit for release 'develop' on 2024-12-14 2024-12-14 22:13:19 +01:00
James Cole
8f3cf38f77 Remove exception because it breaks the upgrade. 2024-12-14 22:12:56 +01:00
James Cole
f33766a062 Make column nullable so migration does not fail. 2024-12-14 22:06:53 +01:00
James Cole
ac5e62c65d Merge branch 'main' into v6.2 2024-12-14 21:56:26 +01:00
github-actions
e2289ce1e6 Auto commit for release 'branch-v6.2' on 2024-12-14 2024-12-14 21:55:42 +01:00
James Cole
f0e2913802 Ignore phpcs errors. 2024-12-14 21:50:46 +01:00
James Cole
1fa928b98f Should work from here 2024-12-14 21:45:20 +01:00
James Cole
1c691cca33 Duh, that wasn't smart. 2024-12-14 21:39:30 +01:00
James Cole
69e1eb3eff echo debug and upgrade to 8.4 2024-12-14 21:37:45 +01:00
James Cole
90794cb515 Experimental branch build. 2024-12-14 21:35:14 +01:00
James Cole
28d7e24d30 Fix piggy bank orders 2024-12-14 20:16:08 +01:00
James Cole
6a62f781e9 Multi account piggy banks. 2024-12-14 17:32:03 +01:00
James Cole
fb6c67fa04 Fix https://github.com/firefly-iii/firefly-iii/issues/9532 2024-12-14 08:10:58 +01:00
James Cole
03e9e3dbdb Expand all notifications. 2024-12-14 08:03:18 +01:00
James Cole
5520992861 Clean up and fix notifications. 2024-12-14 07:52:02 +01:00
James Cole
5f1502eea7 Clean up code. 2024-12-14 07:22:46 +01:00
James Cole
b3560ff525 Clean up notifications 2024-12-14 07:13:01 +01:00
James Cole
8030167ffc Clean up notifications, fix first user notification. 2024-12-14 07:05:08 +01:00
James Cole
fd2c1615cf Start cleaning up notifications. 2024-12-14 06:57:57 +01:00
James Cole
b976239580 Fix all test channels for user and owner. 2024-12-14 06:30:27 +01:00
James Cole
7d8d773f8f Clean up some code. 2024-12-14 05:45:54 +01:00
James Cole
b930ad4da7 Update code and packages 2024-12-14 05:43:13 +01:00
James Cole
abad7cdf16 Update packages and notification settings 2024-12-14 05:39:55 +01:00
James Cole
0e5eb036b0 Unknown user warning. 2024-12-12 07:09:17 +01:00
James Cole
d995bfc081 Update all owner events so they support all channels 2024-12-12 06:33:48 +01:00
James Cole
c920070ce2 Expand settings for notifications. 2024-12-11 07:23:46 +01:00
James Cole
277f5e538f Merge pull request #9534 from firefly-iii/dependabot/composer/composer-736964bd2b 2024-12-10 04:33:36 +01:00
dependabot[bot]
89f197b9d4 Bump league/commonmark in the composer group across 1 directory
Bumps the composer group with 1 update in the / directory: [league/commonmark](https://github.com/thephpleague/commonmark).


Updates `league/commonmark` from 2.5.3 to 2.6.0
- [Release notes](https://github.com/thephpleague/commonmark/releases)
- [Changelog](https://github.com/thephpleague/commonmark/blob/2.6/CHANGELOG.md)
- [Commits](https://github.com/thephpleague/commonmark/compare/2.5.3...2.6.0)

---
updated-dependencies:
- dependency-name: league/commonmark
  dependency-type: direct:production
  dependency-group: composer
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-12-10 01:17:43 +00:00
James Cole
c35ff3174a Add support for Pushover 2024-12-09 07:34:01 +01:00
James Cole
94085ee940 Add config for ntfy 2024-12-09 06:27:37 +01:00
James Cole
c841fa3620 Remove references to discord. 2024-12-09 06:00:43 +01:00
James Cole
2f7a1c941e Expand test notification framework. 2024-12-08 16:28:22 +01:00
James Cole
c06fb8daf6 Expand notifications settings. 2024-12-07 09:41:09 +01:00
James Cole
26948a058a Expand UI for notifications. 2024-12-07 08:05:51 +01:00
James Cole
1220564f30 Fix creating piggies 2024-12-07 08:05:29 +01:00
James Cole
ea4be9dd0c Expand forms and improve validation for multi-account piggy banks 2024-12-06 08:10:31 +01:00
James Cole
4819b5ac5d More code for multi account piggy banks. 2024-12-04 06:38:47 +01:00
James Cole
d740814f88 API works for multi-account piggies, the rest throws an exception 2024-12-01 18:32:05 +01:00
James Cole
cdf1ebf3f7 Better ability to store piggy banks. 2024-12-01 18:16:48 +01:00
James Cole
f2fab5d4ee Update code for piggy banks. 2024-12-01 06:48:15 +01:00
James Cole
21a6927279 Rename fields for piggy bank 2024-11-30 16:02:30 +01:00
James Cole
92190bbc54 Rename fields in piggy bank. 2024-11-30 15:57:11 +01:00
James Cole
9ad005e31f Add edit button for notes https://github.com/firefly-iii/firefly-iii/issues/5523 2024-11-30 06:19:21 +01:00
James Cole
f5c56e02da API allows update/set of budget limit notes. https://github.com/firefly-iii/firefly-iii/issues/5523 2024-11-30 05:42:59 +01:00
James Cole
c25c0d37c5 Replace constants with enums. 2024-11-27 08:08:52 +01:00
James Cole
4ba1c5bcfc New set of PHP 8.4 files 2024-11-26 18:04:32 +01:00
190 changed files with 10024 additions and 5559 deletions

View File

@@ -97,13 +97,13 @@
},
"type": "library",
"extra": {
"branch-alias": {
"dev-main": "3.x-dev"
},
"phpstan": {
"includes": [
"extension.neon"
]
},
"branch-alias": {
"dev-main": "3.x-dev"
}
},
"autoload": {
@@ -1259,16 +1259,16 @@
},
{
"name": "symfony/console",
"version": "v7.2.0",
"version": "v7.2.1",
"source": {
"type": "git",
"url": "https://github.com/symfony/console.git",
"reference": "23c8aae6d764e2bae02d2a99f7532a7f6ed619cf"
"reference": "fefcc18c0f5d0efe3ab3152f15857298868dc2c3"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/console/zipball/23c8aae6d764e2bae02d2a99f7532a7f6ed619cf",
"reference": "23c8aae6d764e2bae02d2a99f7532a7f6ed619cf",
"url": "https://api.github.com/repos/symfony/console/zipball/fefcc18c0f5d0efe3ab3152f15857298868dc2c3",
"reference": "fefcc18c0f5d0efe3ab3152f15857298868dc2c3",
"shasum": ""
},
"require": {
@@ -1332,7 +1332,7 @@
"terminal"
],
"support": {
"source": "https://github.com/symfony/console/tree/v7.2.0"
"source": "https://github.com/symfony/console/tree/v7.2.1"
},
"funding": [
{
@@ -1348,7 +1348,7 @@
"type": "tidelift"
}
],
"time": "2024-11-06T14:24:19+00:00"
"time": "2024-12-11T03:49:26+00:00"
},
{
"name": "symfony/deprecation-contracts",
@@ -1796,8 +1796,8 @@
"type": "library",
"extra": {
"thanks": {
"name": "symfony/polyfill",
"url": "https://github.com/symfony/polyfill"
"url": "https://github.com/symfony/polyfill",
"name": "symfony/polyfill"
}
},
"autoload": {
@@ -1872,8 +1872,8 @@
"type": "library",
"extra": {
"thanks": {
"name": "symfony/polyfill",
"url": "https://github.com/symfony/polyfill"
"url": "https://github.com/symfony/polyfill",
"name": "symfony/polyfill"
}
},
"autoload": {
@@ -1950,8 +1950,8 @@
"type": "library",
"extra": {
"thanks": {
"name": "symfony/polyfill",
"url": "https://github.com/symfony/polyfill"
"url": "https://github.com/symfony/polyfill",
"name": "symfony/polyfill"
}
},
"autoload": {
@@ -2034,8 +2034,8 @@
"type": "library",
"extra": {
"thanks": {
"name": "symfony/polyfill",
"url": "https://github.com/symfony/polyfill"
"url": "https://github.com/symfony/polyfill",
"name": "symfony/polyfill"
}
},
"autoload": {
@@ -2108,8 +2108,8 @@
"type": "library",
"extra": {
"thanks": {
"name": "symfony/polyfill",
"url": "https://github.com/symfony/polyfill"
"url": "https://github.com/symfony/polyfill",
"name": "symfony/polyfill"
}
},
"autoload": {
@@ -2188,8 +2188,8 @@
"type": "library",
"extra": {
"thanks": {
"name": "symfony/polyfill",
"url": "https://github.com/symfony/polyfill"
"url": "https://github.com/symfony/polyfill",
"name": "symfony/polyfill"
}
},
"autoload": {

View File

@@ -26,8 +26,7 @@ SCRIPT_DIR="$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
cd $SCRIPT_DIR/php-cs-fixer
composer update --quiet
rm -f .php-cs-fixer.cache
PHP_CS_FIXER_IGNORE_ENV=true
./vendor/bin/php-cs-fixer fix \
PHP_CS_FIXER_IGNORE_ENV=true ./vendor/bin/php-cs-fixer fix \
--config $SCRIPT_DIR/php-cs-fixer/.php-cs-fixer.php \
--format=txt \
--allow-risky=yes

View File

@@ -13,7 +13,7 @@ jobs:
close_duplicates:
runs-on: ubuntu-latest
steps:
- uses: github/command@v1.2.2
- uses: github/command@v1.3.0
id: command
with:
allowed_contexts: "issue"

View File

@@ -4,9 +4,13 @@ on:
workflow_dispatch:
inputs:
version:
description: 'Release "v1.2.3" or "develop"'
description: 'Release "v1.2.3" or "develop" or "branch-abc"'
required: true
default: 'develop'
phpversion:
description: 'PHP version'
required: true
default: '8.3'
schedule:
- cron: '0 3 * * MON'
@@ -23,6 +27,11 @@ jobs:
if [[ "develop" == "$version" ]]; then
git checkout --track origin/develop
git pull
elif [[ "$version" == branch* ]]; then
PULLBRANCH=${version:7}
echo "The branch is '$PULLBRANCH' ($version)"
git checkout --track origin/$PULLBRANCH
git pull
else
git config user.name github-actions
git config user.email 41898282+github-actions[bot]@users.noreply.github.com
@@ -36,7 +45,7 @@ jobs:
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: '8.3'
php-version: ${{ github.event.inputs.phpversion }}
extensions: mbstring, intl, zip, bcmath
- name: crowdin action
uses: crowdin/github-action@v2
@@ -133,7 +142,7 @@ jobs:
rm -rf vendor composer.lock
composer update --no-dev --no-scripts --no-plugins -q
sudo chown -R runner:docker resources/lang
.ci/phpcs.sh
.ci/phpcs.sh || true
- name: Import GPG key
uses: crazy-max/ghaction-import-gpg@v6
with:
@@ -166,6 +175,16 @@ jobs:
tarName=FireflyIII-develop.tar.gz
fi
# if this is a branch build, also slightly different variable names.
if [[ "$version" == branch* ]]; then
[[ -z $(git status --untracked-files=normal --porcelain) ]] && echo "this branch is clean, no need to push..." && exit 0;
# branch builds overrule develop
releaseName=$version-$(date +'%Y%m%d')
originalName=$releaseName
zipName=FireflyIII-$version.zip
tarName=FireflyIII-$version.tar.gz
fi
# in both cases, if the release or tag already exists, add ".1" until it no longer exists.
tagFound=true
tagCount=1
@@ -207,12 +226,13 @@ jobs:
gpg --armor --detach-sign $zipName
gpg --armor --detach-sign $tarName
# create a development (nightly) release:
# describe the development release.
if [[ "develop" == "$version" ]]; then
echo 'Develop release.'
# add text to output.txt (instructions)
rm output.txt
echo "Bi-weekly development release of Firefly III with the latest fixes, translations and features. Docker users can find this release under the \`develop\` tag." >> output.txt
touch output.txt
sudo chown -R runner:docker output.txt
echo "Weekly development release of Firefly III with the latest fixes, translations and features. Docker users can find this release under the \`develop\` tag." >> output.txt
echo "" >> output.txt
echo "This release was created on **$(date +'%Y-%m-%d')** and may contain unexpected bugs. Data loss is rare but is not impossible. The releases are signed, and you can verify them using the [Firefly III releases PGP key](https://docs.firefly-iii.org/explanation/more-information/signatures/)." >> output.txt
echo "" >> output.txt
@@ -220,15 +240,62 @@ jobs:
echo "* Or read the upgrade instructions for [Docker](https://docs.firefly-iii.org/how-to/firefly-iii/upgrade/docker/), [Kubernetes](https://docs.firefly-iii.org/how-to/firefly-iii/upgrade/kubernetes/) or [self-managed servers](https://docs.firefly-iii.org/how-to/firefly-iii/upgrade/self-managed/)" >> output.txt
echo "" >> output.txt
echo ":warning: Please be careful with this pre-release, as it may not work as expected." >> output.txt
fi
# describe a branch release
if [[ "$version" == branch* ]]; then
echo 'Branch release.'
rm output.txt
touch output.txt
sudo chown -R runner:docker output.txt
echo "Irregular BRANCH release of Firefly III. This release contains specific features or changes. Docker users can find this release under the \`$version\` tag." >> output.txt
echo "" >> output.txt
echo "This release was created on **$(date +'%Y-%m-%d')** and may contain unexpected bugs. Data loss is rare but is not impossible. The releases are signed, and you can verify them using the [Firefly III releases PGP key](https://docs.firefly-iii.org/explanation/more-information/signatures/)." >> output.txt
echo "" >> output.txt
echo "* Please read the installation instructions for [Docker](https://docs.firefly-iii.org/how-to/firefly-iii/installation/docker/), [Portainer](https://docs.firefly-iii.org/how-to/firefly-iii/installation/portainer/), [Kubernetes](https://docs.firefly-iii.org/how-to/firefly-iii/installation/kubernetes/) or [self-managed servers](https://docs.firefly-iii.org/how-to/firefly-iii/installation/self-managed/)" >> output.txt
echo "* Or read the upgrade instructions for [Docker](https://docs.firefly-iii.org/how-to/firefly-iii/upgrade/docker/), [Kubernetes](https://docs.firefly-iii.org/how-to/firefly-iii/upgrade/kubernetes/) or [self-managed servers](https://docs.firefly-iii.org/how-to/firefly-iii/upgrade/self-managed/)" >> output.txt
echo "" >> output.txt
echo ":warning: Please be careful with this branch pre-release, as it may not work as expected." >> output.txt
fi
# describe the main release
if [[ "develop" != "$version" ]] && [[ "$version" != branch* ]]; then
sudo chown -R runner:docker output.txt
echo 'Main release.'
echo '' >> output.txt
echo '### Instructions' >> output.txt
echo '' >> output.txt
echo "* Installation instructions for [Docker](https://docs.firefly-iii.org/how-to/firefly-iii/installation/docker/), [Portainer](https://docs.firefly-iii.org/how-to/firefly-iii/installation/portainer/), [Kubernetes](https://docs.firefly-iii.org/how-to/firefly-iii/installation/kubernetes/) or [self-managed servers](https://docs.firefly-iii.org/how-to/firefly-iii/installation/self-managed/)" >> output.txt
echo "* Or read the upgrade instructions for [Docker](https://docs.firefly-iii.org/how-to/firefly-iii/upgrade/docker/), [Kubernetes](https://docs.firefly-iii.org/how-to/firefly-iii/upgrade/kubernetes/) or [self-managed servers](https://docs.firefly-iii.org/how-to/firefly-iii/upgrade/self-managed/)" >> output.txt
echo "* The releases are signed, and you can verify them using the [Firefly III releases PGP key](https://docs.firefly-iii.org/explanation/more-information/signatures/)." >> output.txt
fi
# create a development release:
if [[ "develop" == "$version" ]]; then
# create the release:
echo "Create nightly release."
git tag -a $releaseName -m "Nightly development release '$version' on $(date +'%Y-%m-%d')"
echo "Create develop release."
git tag -a $releaseName -m "Development release '$version' on $(date +'%Y-%m-%d')"
git push origin $releaseName
gh release create $releaseName -p --verify-tag \
-t "Development release for $(date +'%Y-%m-%d')" \
-F output.txt
fi
# create a branch release:
if [[ "$version" == branch* ]]; then
# create the release:
echo "Create branch release."
git tag -a $releaseName -m "Branch release '$version' on $(date +'%Y-%m-%d')"
git push origin $releaseName
gh release create $releaseName -p --verify-tag \
-t "Branch release for $(date +'%Y-%m-%d')" \
-F output.txt
fi
# create a development (nightly) release:
if [[ "develop" == "$version" ]] || [[ "$version" == branch* ]]; then
# add zip file to release.
gh release upload $releaseName $zipName
gh release upload $releaseName $tarName
@@ -247,16 +314,6 @@ jobs:
gh release upload $releaseName HEAD.txt
else
echo 'MAIN (real) release'
sudo chown -R runner:docker output.txt
# add text to output.txt (more instructions)
echo '' >> output.txt
echo '### Instructions' >> output.txt
echo '' >> output.txt
echo "* Installation instructions for [Docker](https://docs.firefly-iii.org/how-to/firefly-iii/installation/docker/), [Portainer](https://docs.firefly-iii.org/how-to/firefly-iii/installation/portainer/), [Kubernetes](https://docs.firefly-iii.org/how-to/firefly-iii/installation/kubernetes/) or [self-managed servers](https://docs.firefly-iii.org/how-to/firefly-iii/installation/self-managed/)" >> output.txt
echo "* Or read the upgrade instructions for [Docker](https://docs.firefly-iii.org/how-to/firefly-iii/upgrade/docker/), [Kubernetes](https://docs.firefly-iii.org/how-to/firefly-iii/upgrade/kubernetes/) or [self-managed servers](https://docs.firefly-iii.org/how-to/firefly-iii/upgrade/self-managed/)" >> output.txt
echo "* The releases are signed, and you can verify them using the [Firefly III releases PGP key](https://docs.firefly-iii.org/explanation/more-information/signatures/)." >> output.txt
echo "Create default release."
git tag -a $releaseName -m "Here be changelog"
git push origin $releaseName
gh release create $releaseName -F output.txt -t "$releaseName" --verify-tag

View File

@@ -66,14 +66,13 @@ class PiggyBankController extends Controller
*/
public function piggyBanks(AutocompleteRequest $request): JsonResponse
{
$data = $request->getData();
$piggies = $this->piggyRepository->searchPiggyBank($data['query'], $this->parameters->get('limit'));
$defaultCurrency = app('amount')->getDefaultCurrency();
$response = [];
$data = $request->getData();
$piggies = $this->piggyRepository->searchPiggyBank($data['query'], $this->parameters->get('limit'));
$response = [];
/** @var PiggyBank $piggy */
foreach ($piggies as $piggy) {
$currency = $this->accountRepository->getAccountCurrency($piggy->account) ?? $defaultCurrency;
$currency = $piggy->transactionCurrency;
$objectGroup = $piggy->objectGroups()->first();
$response[] = [
'id' => (string)$piggy->id,
@@ -97,15 +96,14 @@ class PiggyBankController extends Controller
*/
public function piggyBanksWithBalance(AutocompleteRequest $request): JsonResponse
{
$data = $request->getData();
$piggies = $this->piggyRepository->searchPiggyBank($data['query'], $this->parameters->get('limit'));
$defaultCurrency = app('amount')->getDefaultCurrency();
$response = [];
$data = $request->getData();
$piggies = $this->piggyRepository->searchPiggyBank($data['query'], $this->parameters->get('limit'));
$response = [];
/** @var PiggyBank $piggy */
foreach ($piggies as $piggy) {
$currency = $this->accountRepository->getAccountCurrency($piggy->account) ?? $defaultCurrency;
$currentAmount = $this->piggyRepository->getRepetition($piggy)->currentamount ?? '0';
$currency = $piggy->transactionCurrency;
$currentAmount = $this->piggyRepository->getCurrentAmount($piggy);
$objectGroup = $piggy->objectGroups()->first();
$response[] = [
'id' => (string)$piggy->id,
@@ -114,7 +112,7 @@ class PiggyBankController extends Controller
'%s (%s / %s)',
$piggy->name,
app('amount')->formatAnything($currency, $currentAmount, false),
app('amount')->formatAnything($currency, $piggy->targetamount, false),
app('amount')->formatAnything($currency, $piggy->target_amount, false),
),
'currency_id' => (string)$currency->id,
'currency_name' => $currency->name,

View File

@@ -36,6 +36,7 @@ use FireflyIII\Models\RuleGroup;
use FireflyIII\Models\Tag;
use FireflyIII\Models\TransactionGroup;
use FireflyIII\Models\TransactionJournal;
use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface;
use FireflyIII\User;
use Illuminate\Http\JsonResponse;
@@ -52,7 +53,7 @@ class PurgeController extends Controller
public function purge(): JsonResponse
{
/** @var User $user */
$user = auth()->user();
$user = auth()->user();
// some manual code, too lazy to call all repositories.
@@ -63,14 +64,17 @@ class PurgeController extends Controller
Bill::whereUserId($user->id)->onlyTrashed()->forceDelete();
// piggies
$set = PiggyBank::leftJoin('accounts', 'accounts.id', 'piggy_banks.account_id')
->where('accounts.user_id', $user->id)->onlyTrashed()->get(['piggy_banks.*'])
;
/** @var PiggyBank $piggy */
foreach ($set as $piggy) {
$piggy->forceDelete();
}
$repository = app(PiggyBankRepositoryInterface::class);
$repository->setUser($user);
$repository->purgeAll();
// $set = PiggyBank::leftJoin('accounts', 'accounts.id', 'piggy_banks.account_id')
// ->where('accounts.user_id', $user->id)->onlyTrashed()->get(['piggy_banks.*'])
// ;
//
// /** @var PiggyBank $piggy */
// foreach ($set as $piggy) {
// $piggy->forceDelete();
// }
// rule group
RuleGroup::whereUserId($user->id)->onlyTrashed()->forceDelete();

View File

@@ -111,7 +111,7 @@ class ListController extends Controller
// types to get, page size:
$pageSize = $this->parameters->get('limit');
// get list of budgets. Count it and split it.
// get list of piggy banks. Count it and split it.
$collection = $this->repository->getPiggyBanks($account);
$count = $collection->count();
$piggyBanks = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize);

View File

@@ -69,6 +69,7 @@ class StoreController extends Controller
$data = $request->getAll();
$data['start_date'] = $data['start'];
$data['end_date'] = $data['end'];
$data['notes'] = $data['notes'];
$data['budget_id'] = $budget->id;
$budgetLimit = $this->blRepository->store($data);

View File

@@ -28,6 +28,7 @@ use FireflyIII\Api\V1\Controllers\Controller;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\PiggyBank;
use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface;
use FireflyIII\Transformers\AccountTransformer;
use FireflyIII\Transformers\AttachmentTransformer;
use FireflyIII\Transformers\PiggyBankEventTransformer;
use Illuminate\Http\JsonResponse;
@@ -118,4 +119,36 @@ class ListController extends Controller
return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE);
}
/**
* This endpoint is documented at:
* https://api-docs.firefly-iii.org/?urls.primaryName=2.0.0%20(v1)#/piggy_banks/listAccountByPiggyBank
*
* List single resource.
*
* @throws FireflyException
*/
public function accounts(PiggyBank $piggyBank): JsonResponse
{
// types to get, page size:
$pageSize = $this->parameters->get('limit');
$manager = $this->getManager();
$collection = $piggyBank->accounts;
$count = $collection->count();
$events = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize);
// make paginator:
$paginator = new LengthAwarePaginator($events, $count, $pageSize, $this->parameters->get('page'));
$paginator->setPath(route('api.v1.piggy-banks.accounts', [$piggyBank->id]).$this->buildParams());
/** @var AccountTransformer $transformer */
$transformer = app(AccountTransformer::class);
$transformer->setParameters($this->parameters);
$resource = new FractalCollection($events, $transformer, 'accounts');
$resource->setPaginator(new IlluminatePaginatorAdapter($paginator));
return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE);
}
}

View File

@@ -72,7 +72,7 @@ class ShowController extends Controller
// types to get, page size:
$pageSize = $this->parameters->get('limit');
// get list of budgets. Count it and split it.
// get list of piggy banks. Count it and split it.
$collection = $this->repository->getPiggyBanks();
$count = $collection->count();
$piggyBanks = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize);

View File

@@ -62,7 +62,6 @@ class AccountController extends Controller
*/
public function search(Request $request): JsonResponse|Response
{
app('log')->debug('Now in account search()');
$manager = $this->getManager();
$query = trim((string)$request->get('query'));
$field = trim((string)$request->get('field'));
@@ -70,6 +69,7 @@ class AccountController extends Controller
if ('' === $query || !in_array($field, $this->validFields, true)) {
return response(null, 422);
}
app('log')->debug(sprintf('Now in account search("%s", "%s")', $field, $query));
$types = $this->mapAccountTypes($type);
/** @var AccountSearch $search */

View File

@@ -48,6 +48,7 @@ class StoreRequest extends FormRequest
'amount' => $this->convertString('amount'),
'currency_id' => $this->convertInteger('currency_id'),
'currency_code' => $this->convertString('currency_code'),
'notes' => $this->stringWithNewlines('notes'),
];
}
@@ -62,6 +63,7 @@ class StoreRequest extends FormRequest
'amount' => ['required', new IsValidPositiveAmount()],
'currency_id' => 'numeric|exists:transaction_currencies,id',
'currency_code' => 'min:3|max:51|exists:transaction_currencies,code',
'notes' => 'nullable|min:0|max:32768',
];
}
}

View File

@@ -51,7 +51,12 @@ class UpdateRequest extends FormRequest
'amount' => ['amount', 'convertString'],
'currency_id' => ['currency_id', 'convertInteger'],
'currency_code' => ['currency_code', 'convertString'],
'notes' => ['notes', 'stringWithNewlines'],
];
if (false === $this->has('notes')) {
// ignore notes, not submitted.
unset($fields['notes']);
}
return $this->getAllData($fields);
}
@@ -67,6 +72,7 @@ class UpdateRequest extends FormRequest
'amount' => ['nullable', new IsValidPositiveAmount()],
'currency_id' => 'numeric|exists:transaction_currencies,id',
'currency_code' => 'min:3|max:51|exists:transaction_currencies,code',
'notes' => 'nullable|min:0|max:32768',
];
}
@@ -84,7 +90,7 @@ class UpdateRequest extends FormRequest
$start = new Carbon($data['start']);
$end = new Carbon($data['end']);
if ($end->isBefore($start)) {
$validator->errors()->add('end', (string)trans('validation.date_after'));
$validator->errors()->add('end', (string) trans('validation.date_after'));
}
}
}

View File

@@ -24,10 +24,15 @@ declare(strict_types=1);
namespace FireflyIII\Api\V1\Requests\Models\PiggyBank;
use FireflyIII\Rules\IsValidPositiveAmount;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Rules\IsValidZeroOrMoreAmount;
use FireflyIII\Support\Request\ChecksLogin;
use FireflyIII\Support\Request\ConvertsDataTypes;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\Validator;
/**
* Class StoreRequest
@@ -42,19 +47,20 @@ class StoreRequest extends FormRequest
*/
public function getAll(): array
{
$fields = [
$fields = [
'order' => ['order', 'convertInteger'],
];
$data = $this->getAllData($fields);
$data['name'] = $this->convertString('name');
$data['account_id'] = $this->convertInteger('account_id');
$data['targetamount'] = $this->convertString('target_amount');
$data['current_amount'] = $this->convertString('current_amount');
$data['startdate'] = $this->getCarbonDate('start_date');
$data['targetdate'] = $this->getCarbonDate('target_date');
$data['notes'] = $this->stringWithNewlines('notes');
$data['object_group_id'] = $this->convertInteger('object_group_id');
$data['object_group_title'] = $this->convertString('object_group_title');
$data = $this->getAllData($fields);
$data['name'] = $this->convertString('name');
$data['accounts'] = $this->parseAccounts($this->get('accounts'));
$data['target_amount'] = $this->convertString('target_amount');
$data['start_date'] = $this->getCarbonDate('start_date');
$data['target_date'] = $this->getCarbonDate('target_date');
$data['notes'] = $this->stringWithNewlines('notes');
$data['object_group_id'] = $this->convertInteger('object_group_id');
$data['transaction_currency_id'] = $this->convertInteger('transaction_currency_id');
$data['transaction_currency_code'] = $this->convertString('transaction_currency_code');
$data['object_group_title'] = $this->convertString('object_group_title');
return $data;
}
@@ -65,15 +71,99 @@ class StoreRequest extends FormRequest
public function rules(): array
{
return [
'name' => 'required|min:1|max:255|uniquePiggyBankForUser',
'current_amount' => ['nullable', new IsValidPositiveAmount()],
'account_id' => 'required|numeric|belongsToUser:accounts,id',
'object_group_id' => 'numeric|belongsToUser:object_groups,id',
'object_group_title' => ['min:1', 'max:255'],
'target_amount' => ['required', new IsValidPositiveAmount()],
'start_date' => 'date|nullable',
'target_date' => 'date|nullable|after:start_date',
'notes' => 'max:65000',
'name' => 'required|min:1|max:255|uniquePiggyBankForUser',
'accounts' => 'required',
'accounts.*' => 'array|required',
'accounts.*.account_id' => 'required|numeric|belongsToUser:accounts,id',
'accounts.*.current_amount' => ['numeric', new IsValidZeroOrMoreAmount()],
'object_group_id' => 'numeric|belongsToUser:object_groups,id',
'object_group_title' => ['min:1', 'max:255'],
'target_amount' => ['required', new IsValidZeroOrMoreAmount()],
'start_date' => 'date|nullable',
'transaction_currency_id' => 'exists:transaction_currencies,id|required_without:transaction_currency_code',
'transaction_currency_code' => 'exists:transaction_currencies,code|required_without:transaction_currency_id',
'target_date' => 'date|nullable|after:start_date',
'notes' => 'max:65000',
];
}
/**
* Can only store money on liabilities and asset accounts.
*/
public function withValidator(Validator $validator): void
{
$validator->after(
function (Validator $validator): void {
// validate start before end only if both are there.
$data = $validator->getData();
$currency = $this->getCurrencyFromData($data);
$targetAmount = (string) ($data['target_amount'] ?? '0');
$currentAmount = '0';
if (array_key_exists('accounts', $data) && is_array($data['accounts'])) {
$repository = app(AccountRepositoryInterface::class);
$types = config('firefly.piggy_bank_account_types');
foreach ($data['accounts'] as $index => $array) {
$accountId = (int) ($array['account_id'] ?? 0);
$account = $repository->find($accountId);
if (null !== $account) {
// check currency here.
$accountCurrency = $repository->getAccountCurrency($account);
$isMultiCurrency = $repository->getMetaValue($account, 'is_multi_currency');
$currentAmount = bcadd($currentAmount, (string)($array['current_amount'] ?? '0'));
if ($accountCurrency->id !== $currency->id && 'true' !== $isMultiCurrency) {
$validator->errors()->add(sprintf('accounts.%d', $index), trans('validation.invalid_account_currency'));
}
$type = $account->accountType->type;
if (!in_array($type, $types, true)) {
$validator->errors()->add(sprintf('accounts.%d', $index), trans('validation.invalid_account_type'));
}
}
}
}
if (-1 === bccomp($targetAmount, $currentAmount) && 1 === bccomp($targetAmount, '0')) {
$validator->errors()->add('target_amount', trans('validation.current_amount_too_much'));
}
}
);
if ($validator->fails()) {
Log::channel('audit')->error(sprintf('Validation errors in %s', __CLASS__), $validator->errors()->toArray());
}
}
private function parseAccounts(mixed $array): array
{
if (!is_array($array)) {
return [];
}
$return = [];
foreach ($array as $entry) {
if (!is_array($entry)) {
continue;
}
$return[] = [
'account_id' => $this->integerFromValue((string) ($entry['account_id'] ?? '0')),
'current_amount' => $this->clearString((string) ($entry['current_amount'] ?? '0')),
];
}
return $return;
}
private function getCurrencyFromData(array $data): TransactionCurrency
{
if (array_key_exists('transaction_currency_code', $data) && '' !== (string) $data['transaction_currency_code']) {
$currency = TransactionCurrency::whereCode($data['transaction_currency_code'])->first();
if (null !== $currency) {
return $currency;
}
}
if (array_key_exists('transaction_currency_id', $data) && '' !== (string) $data['transaction_currency_id']) {
$currency = TransactionCurrency::find((int) $data['transaction_currency_id']);
if (null !== $currency) {
return $currency;
}
}
throw new FireflyException('Unexpected empty currency.');
}
}

View File

@@ -119,7 +119,7 @@ class StoreRequest extends FormRequest
'description' => 'min:1|max:32768|nullable',
'rule_group_id' => 'belongsToUser:rule_groups|required_without:rule_group_title',
'rule_group_title' => 'nullable|min:1|max:255|required_without:rule_group_id|belongsToUser:rule_groups,title',
'trigger' => 'required|in:store-journal,update-journal',
'trigger' => 'required|in:store-journal,update-journal,manual-activation',
'triggers.*.type' => 'required|in:'.implode(',', $validTriggers),
'triggers.*.value' => 'required_if:actions.*.type,'.$contextTriggers.'|min:1|ruleTriggerValue|max:1024',
'triggers.*.stop_processing' => [new IsBoolean()],

View File

@@ -138,7 +138,7 @@ class UpdateRequest extends FormRequest
'description' => 'min:1|max:32768|nullable',
'rule_group_id' => 'belongsToUser:rule_groups',
'rule_group_title' => 'nullable|min:1|max:255|belongsToUser:rule_groups,title',
'trigger' => 'in:store-journal,update-journal',
'trigger' => 'in:store-journal,update-journal.manual-activation',
'triggers.*.type' => 'required|in:'.implode(',', $validTriggers),
'triggers.*.value' => 'required_if:actions.*.type,'.$contextTriggers.'|min:1|ruleTriggerValue|max:1024',
'triggers.*.stop_processing' => [new IsBoolean()],

View File

@@ -31,7 +31,6 @@ use FireflyIII\Models\Bill;
use FireflyIII\Models\BudgetLimit;
use FireflyIII\Models\CurrencyExchangeRate;
use FireflyIII\Models\PiggyBank;
use FireflyIII\Models\PiggyBankRepetition;
use FireflyIII\Models\RecurrenceTransaction;
use FireflyIII\Models\RuleTrigger;
use Illuminate\Console\Command;
@@ -58,8 +57,6 @@ class CorrectAmounts extends Command
$this->fixBudgetLimits();
// currency_exchange_rates must be positive
$this->fixExchangeRates();
// piggy_bank_repetitions must be positive
$this->fixRepetitions();
// piggy_banks must be positive
$this->fixPiggyBanks();
// recurrences_transactions amount must be positive
@@ -161,27 +158,9 @@ class CorrectAmounts extends Command
$this->friendlyInfo(sprintf('Corrected %d currency exchange rate(s).', $count));
}
private function fixRepetitions(): void
{
$set = PiggyBankRepetition::where('currentamount', '<', 0)->get();
$count = $set->count();
if (0 === $count) {
$this->friendlyPositive('All piggy bank repetition amounts are positive.');
return;
}
/** @var PiggyBankRepetition $item */
foreach ($set as $item) {
$item->currentamount = app('steam')->positive($item->currentamount);
$item->save();
}
$this->friendlyInfo(sprintf('Corrected %d piggy bank repetition amount(s).', $count));
}
private function fixPiggyBanks(): void
{
$set = PiggyBank::where('targetamount', '<', 0)->get();
$set = PiggyBank::where('target_amount', '<', 0)->get();
$count = $set->count();
if (0 === $count) {
$this->friendlyPositive('All piggy bank amounts are positive.');
@@ -191,7 +170,7 @@ class CorrectAmounts extends Command
/** @var PiggyBank $item */
foreach ($set as $item) {
$item->targetamount = app('steam')->positive($item->targetamount);
$item->target_amount = app('steam')->positive($item->target_amount);
$item->save();
}
$this->friendlyInfo(sprintf('Corrected %d piggy bank amount(s).', $count));

View File

@@ -10,6 +10,7 @@ use Illuminate\Console\Command;
*/
class CorrectionSkeleton extends Command
{
use ShowsFriendlyMessages;
protected $description = 'DESCRIPTION HERE';
protected $signature = 'firefly-iii:CORR_COMMAND';

View File

@@ -0,0 +1,229 @@
<?php
declare(strict_types=1);
/*
* RecalculateNativeAmounts.php
* Copyright (c) 2024 james@firefly-iii.org.
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*/
namespace FireflyIII\Console\Commands\Correction;
use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use FireflyIII\Handlers\Observer\TransactionObserver;
use FireflyIII\Models\Account;
use FireflyIII\Models\AutoBudget;
use FireflyIII\Models\AvailableBudget;
use FireflyIII\Models\Bill;
use FireflyIII\Models\Budget;
use FireflyIII\Models\BudgetLimit;
use FireflyIII\Models\PiggyBank;
use FireflyIII\Models\PiggyBankEvent;
use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Models\UserGroup;
use FireflyIII\Repositories\UserGroup\UserGroupRepositoryInterface;
use FireflyIII\Repositories\UserGroups\PiggyBank\PiggyBankRepositoryInterface;
use FireflyIII\Support\Facades\Preferences;
use FireflyIII\Support\Http\Api\ExchangeRateConverter;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Query\Builder as DatabaseBuilder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class RecalculateNativeAmounts extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Recalculate native amounts for all objects.';
protected $signature = 'firefly-iii:recalculate-native-amounts';
/**
* Execute the console command.
*/
public function handle(): int
{
Log::debug('Will update all native amounts. This may take some time.');
$this->friendlyWarning('Recalculating native amounts for all objects. This may take some time!');
/** @var UserGroupRepositoryInterface $repository */
$repository = app(UserGroupRepositoryInterface::class);
/** @var UserGroup $userGroup */
foreach ($repository->getAll() as $userGroup) {
$this->recalculateForGroup($userGroup);
}
$this->friendlyInfo('Recalculated all native amounts.');
return 0;
}
private function recalculateForGroup(UserGroup $userGroup): void
{
Log::debug(sprintf('Now recalculating for user group #%d', $userGroup->id));
$this->recalculateAccounts($userGroup);
// do a check with the group's currency so we can skip some stuff.
Preferences::mark();
$currency = app('amount')->getDefaultCurrencyByUserGroup($userGroup);
$this->recalculatePiggyBanks($userGroup, $currency);
$this->recalculateBudgets($userGroup, $currency);
$this->recalculateAvailableBudgets($userGroup, $currency);
$this->recalculateBills($userGroup, $currency);
$this->calculateTransactions($userGroup, $currency);
}
private function recalculateAccounts(UserGroup $userGroup): void
{
$set = $userGroup->accounts()->where(function (EloquentBuilder $q): void {
$q->whereNotNull('virtual_balance');
$q->orWhere('virtual_balance', '!=', '');
})->get();
/** @var Account $account */
foreach ($set as $account) {
$account->touch();
}
Log::debug(sprintf('Recalculated %d accounts', $set->count()));
}
private function recalculatePiggyBanks(UserGroup $userGroup, TransactionCurrency $currency): void
{
$converter = new ExchangeRateConverter();
$converter->setIgnoreSettings(true);
$repository = app(PiggyBankRepositoryInterface::class);
$repository->setUserGroup($userGroup);
$set = $repository->getPiggyBanks();
$set = $set->filter(
static function (PiggyBank $piggyBank) use ($currency) {
return $currency->id !== $piggyBank->transaction_currency_id;
}
);
foreach ($set as $piggyBank) {
$piggyBank->encrypted = false;
$piggyBank->save();
foreach ($piggyBank->accounts as $account) {
$account->pivot->native_current_amount = null;
if (0 !== bccomp($account->pivot->current_amount, '0')) {
$account->pivot->native_current_amount = $converter->convert($piggyBank->transactionCurrency, $currency, today(), $account->pivot->current_amount);
}
$account->pivot->save();
}
$this->recalculatePiggyBankEvents($piggyBank);
}
Log::debug(sprintf('Recalculated %d piggy banks.', $set->count()));
}
private function recalculatePiggyBankEvents(PiggyBank $piggyBank): void
{
$set = $piggyBank->piggyBankEvents()->get();
$set->each(
static function (PiggyBankEvent $event): void {
$event->touch();
}
);
Log::debug(sprintf('Recalculated %d piggy bank events.', $set->count()));
}
private function recalculateBudgets(UserGroup $userGroup, TransactionCurrency $currency): void
{
$set = $userGroup->budgets()->get();
/** @var Budget $budget */
foreach ($set as $budget) {
$this->recalculateBudgetLimits($budget, $currency);
$this->recalculateAutoBudgets($budget, $currency);
}
Log::debug(sprintf('Recalculated %d budgets.', $set->count()));
}
private function recalculateBudgetLimits(Budget $budget, TransactionCurrency $currency): void
{
$set = $budget->budgetlimits()->where('transaction_currency_id', '!=', $currency->id)->get();
/** @var BudgetLimit $limit */
foreach ($set as $limit) {
Log::debug(sprintf('Will now touch BL #%d', $limit->id));
$limit->touch();
Log::debug(sprintf('Done with touch BL #%d', $limit->id));
}
Log::debug(sprintf('Recalculated %d budget limits.', $set->count()));
}
private function recalculateAutoBudgets(Budget $budget, TransactionCurrency $currency): void
{
$set = $budget->autoBudgets()->where('transaction_currency_id', '!=', $currency->id)->get();
/** @var AutoBudget $autoBudget */
foreach ($set as $autoBudget) {
$autoBudget->touch();
}
Log::debug(sprintf('Recalculated %d auto budgets.', $set->count()));
}
private function recalculateBills(UserGroup $userGroup, TransactionCurrency $currency): void
{
$set = $userGroup->bills()->where('transaction_currency_id', '!=', $currency->id)->get();
/** @var Bill $bill */
foreach ($set as $bill) {
$bill->touch();
}
Log::debug(sprintf('Recalculated %d bills.', $set->count()));
}
private function recalculateAvailableBudgets(UserGroup $userGroup, TransactionCurrency $currency): void
{
Log::debug('Start with available budgets.');
$set = $userGroup->availableBudgets()->where('transaction_currency_id', '!=', $currency->id)->get();
/** @var AvailableBudget $budget */
foreach ($set as $budget) {
$budget->touch();
}
Log::debug(sprintf('Recalculated %d available budgets.', $set->count()));
}
private function calculateTransactions(UserGroup $userGroup, TransactionCurrency $currency): void
{
// custom query because of the potential size of this update.
$set = DB::table('transactions')
->join('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
->where('transaction_journals.user_group_id', $userGroup->id)
->where(static function (DatabaseBuilder $q) use ($currency): void {
$q->whereNot('transactions.transaction_currency_id', $currency->id)
->orWhereNot('transactions.foreign_currency_id', $currency->id)
;
})
->get(['transactions.id'])
;
TransactionObserver::$recalculate = false;
foreach ($set as $item) {
// here we are.
$transaction = Transaction::find($item->id);
$transaction->touch();
}
TransactionObserver::$recalculate = true;
Log::debug(sprintf('Recalculated %d transactions.', $set->count()));
}
}

View File

@@ -67,8 +67,8 @@ class AddTimezonesToDates extends Command
CurrencyExchangeRate::class => ['date'], // done
InvitedUser::class => ['expires'],
PiggyBankEvent::class => ['date'],
PiggyBankRepetition::class => ['startdate', 'targetdate'],
PiggyBank::class => ['startdate', 'targetdate'], // done
PiggyBankRepetition::class => ['start_date', 'target_date'],
PiggyBank::class => ['start_date', 'target_date'], // done
Recurrence::class => ['first_date', 'repeat_until', 'latest_date'],
Tag::class => ['date'],
TransactionJournal::class => ['date'],

View File

@@ -59,18 +59,22 @@ class ReportSum extends Command
/** @var User $user */
foreach ($userRepository->all() as $user) {
$sum = (string)$user->transactions()->selectRaw('SUM(amount) + SUM(foreign_amount) as total')->value('total');
if (!is_numeric($sum)) {
$message = sprintf('Error: Transactions for user #%d (%s) have an invalid sum ("%s").', $user->id, $user->email, $sum);
$sum = (string) $user->transactions()->selectRaw('SUM(amount) as total')->value('total');
$foreign = (string) $user->transactions()->selectRaw('SUM(foreign_amount) as total')->value('total');
$sum = '' === $sum ? '0' : $sum;
$foreign = '' === $foreign ? '0' : $foreign;
$total = bcadd($sum, $foreign);
if (!is_numeric($total)) {
$message = sprintf('Error: Transactions for user #%d (%s) have an invalid sum ("%s").', $user->id, $user->email, $total);
$this->friendlyError($message);
continue;
}
if (0 !== bccomp($sum, '0')) {
$message = sprintf('Error: Transactions for user #%d (%s) are off by %s!', $user->id, $user->email, $sum);
if (0 !== bccomp($total, '0')) {
$message = sprintf('Error: Transactions for user #%d (%s) are off by %s!', $user->id, $user->email, $total);
$this->friendlyError($message);
}
if (0 === bccomp($sum, '0')) {
if (0 === bccomp($total, '0')) {
$this->friendlyPositive(sprintf('Amount integrity OK for user #%d', $user->id));
}
}

View File

@@ -83,8 +83,8 @@ class ForceDecimalSize extends Command
'currency_exchange_rates' => ['rate', 'user_rate'],
'limit_repetitions' => ['amount'],
'piggy_bank_events' => ['amount'],
'piggy_bank_repetitions' => ['currentamount'],
'piggy_banks' => ['targetamount'],
'piggy_bank_repetitions' => ['current_amount'],
'piggy_banks' => ['target_amount'],
'recurrences_transactions' => ['amount', 'foreign_amount'],
'transactions' => ['amount', 'foreign_amount'],
];

View File

@@ -128,7 +128,7 @@ class ApplyRules extends Command
$ruleEngine->addOperator(['type' => 'account_id', 'value' => $list]);
// add the date as a filter:
$ruleEngine->addOperator(['type' => 'date_after', 'value' => $this->startDate->format('Y-m-d')]);
$ruleEngine->addOperator(['type' => 'date_after', 'value' => $this->start_date->format('Y-m-d')]);
$ruleEngine->addOperator(['type' => 'date_before', 'value' => $this->endDate->format('Y-m-d')]);
// start running rules.
@@ -265,8 +265,8 @@ class ApplyRules extends Command
private function verifyInputDates(): void
{
// parse start date.
$inputStart = today(config('app.timezone'))->startOfMonth();
$startString = $this->option('start_date');
$inputStart = today(config('app.timezone'))->startOfMonth();
$startString = $this->option('start_date');
if (null === $startString) {
/** @var JournalRepositoryInterface $repository */
$repository = app(JournalRepositoryInterface::class);
@@ -281,8 +281,8 @@ class ApplyRules extends Command
}
// parse end date
$inputEnd = today(config('app.timezone'));
$endString = $this->option('end_date');
$inputEnd = today(config('app.timezone'));
$endString = $this->option('end_date');
if (null !== $endString && '' !== $endString) {
$inputEnd = Carbon::createFromFormat('Y-m-d', $endString);
}
@@ -296,8 +296,8 @@ class ApplyRules extends Command
[$inputEnd, $inputStart] = [$inputStart, $inputEnd];
}
$this->startDate = $inputStart;
$this->endDate = $inputEnd;
$this->start_date = $inputStart;
$this->endDate = $inputEnd;
}
private function grabAllRules(): void

View File

@@ -72,6 +72,7 @@ class UpgradeDatabase extends Command
'firefly-iii:create-group-memberships',
'firefly-iii:upgrade-group-information',
'firefly-iii:upgrade-currency-preferences',
'firefly-iii:upgrade-multi-piggies',
'firefly-iii:correct-database',
];
$args = [];

View File

@@ -0,0 +1,112 @@
<?php
declare(strict_types=1);
/*
* UpgradeMultiPiggyBanks.php
* Copyright (c) 2024 james@firefly-iii.org.
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*/
namespace FireflyIII\Console\Commands\Upgrade;
use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use FireflyIII\Models\PiggyBank;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
class UpgradeMultiPiggyBanks extends Command
{
use ShowsFriendlyMessages;
public const string CONFIG_NAME = '620_make_multi_piggies';
protected $description = 'Upgrade piggybanks so they can use multiple accounts.';
protected $signature = 'firefly-iii:upgrade-multi-piggies {--F|force : Force the execution of this command.}';
private PiggyBankRepositoryInterface $repository;
private AccountRepositoryInterface $accountRepository;
/**
* Execute the console command.
*/
public function handle(): int
{
if ($this->isExecuted() && true !== $this->option('force')) {
$this->friendlyInfo('This command has already been executed.');
return 0;
}
$this->upgradePiggyBanks();
$this->friendlyInfo('Upgraded all piggy banks.');
$this->markAsExecuted();
return 0;
}
private function isExecuted(): bool
{
$configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false);
if (null !== $configVar) {
return (bool) $configVar->data;
}
return false;
}
private function markAsExecuted(): void
{
app('fireflyconfig')->set(self::CONFIG_NAME, true);
}
private function upgradePiggyBanks(): void
{
$this->repository = app(PiggyBankRepositoryInterface::class);
$this->accountRepository = app(AccountRepositoryInterface::class);
$set = PiggyBank::whereNotNull('account_id')->get();
Log::debug(sprintf('Will update %d piggy banks(s).', $set->count()));
/** @var PiggyBank $piggyBank */
foreach ($set as $piggyBank) {
$this->upgradePiggyBank($piggyBank);
}
}
private function upgradePiggyBank(PiggyBank $piggyBank): void
{
$this->repository->setUser($piggyBank->account->user);
$this->accountRepository->setUser($piggyBank->account->user);
$repetition = $this->repository->getRepetition($piggyBank, true);
$currency = $this->accountRepository->getAccountCurrency($piggyBank->account) ?? app('amount')->getDefaultCurrencyByUserGroup($piggyBank->account->user->userGroup);
// update piggy bank to have a currency.
$piggyBank->transaction_currency_id = $currency->id;
$piggyBank->saveQuietly();
// store current amount in account association.
$piggyBank->accounts()->sync([$piggyBank->account->id => ['current_amount' => $repetition->current_amount]]);
$piggyBank->account_id = null;
$piggyBank->saveQuietly();
// remove all repetitions (no longer used)
$piggyBank->piggyBankRepetitions()->delete();
}
}

View File

@@ -6,7 +6,6 @@ use Illuminate\Console\Command;
/**
* Class UpgradeSkeleton.
* TODO DONT FORGET TO ADD THIS TO THE DOCKER BUILD
*/
class UpgradeSkeleton extends Command
{

View File

@@ -0,0 +1,40 @@
<?php
/*
* Updated.php
* Copyright (c) 2024 james@firefly-iii.org.
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*/
declare(strict_types=1);
namespace FireflyIII\Events\Model\Account;
use FireflyIII\Models\Account;
use Illuminate\Queue\SerializesModels;
class Updated
{
use SerializesModels;
public Account $account;
public function __construct(Account $account)
{
$this->account = $account;
}
}

View File

@@ -25,6 +25,7 @@ declare(strict_types=1);
namespace FireflyIII\Events;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
/**
* Class NewVersionAvailable
@@ -40,6 +41,7 @@ class NewVersionAvailable extends Event
*/
public function __construct(string $message)
{
Log::debug(__METHOD__);
$this->message = $message;
}
}

View File

@@ -0,0 +1,43 @@
<?php
/*
* UserGroupChangedDefaultCurrency.php
* Copyright (c) 2024 james@firefly-iii.org.
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*/
declare(strict_types=1);
namespace FireflyIII\Events\Preferences;
use FireflyIII\Events\Event;
use FireflyIII\Models\UserGroup;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
class UserGroupChangedDefaultCurrency extends Event
{
use SerializesModels;
public UserGroup $userGroup;
public function __construct(UserGroup $userGroup)
{
Log::debug('User group changed default currency.');
$this->userGroup = $userGroup;
}
}

View File

@@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Events;
use FireflyIII\Notifications\Notifiables\OwnerNotifiable;
use FireflyIII\User;
use Illuminate\Queue\SerializesModels;
@@ -35,12 +36,14 @@ class RegisteredUser extends Event
use SerializesModels;
public User $user;
public OwnerNotifiable $owner;
/**
* Create a new event instance. This event is triggered when a new user registers.
*/
public function __construct(User $user)
public function __construct(OwnerNotifiable $owner, User $user)
{
$this->user = $user;
$this->user = $user;
$this->owner = $owner;
}
}

View File

@@ -0,0 +1,39 @@
<?php
/*
* UnknownUserAttemptedLogin.php
* Copyright (c) 2024 james@firefly-iii.org.
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*/
declare(strict_types=1);
namespace FireflyIII\Events\Security;
use Illuminate\Queue\SerializesModels;
class UnknownUserAttemptedLogin
{
use SerializesModels;
public string $address;
public function __construct(string $address)
{
$this->address = $address;
}
}

View File

@@ -0,0 +1,44 @@
<?php
/*
* UserAttemptedLogin.php
* Copyright (c) 2024 james@firefly-iii.org.
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*/
declare(strict_types=1);
namespace FireflyIII\Events\Security;
use FireflyIII\Events\Event;
use FireflyIII\User;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Queue\SerializesModels;
class UserAttemptedLogin extends Event
{
use SerializesModels;
public User $user;
public function __construct(null|Authenticatable|User $user)
{
if ($user instanceof User) {
$this->user = $user;
}
}
}

View File

@@ -0,0 +1,46 @@
<?php
/*
* TestEmailChannel.php
* Copyright (c) 2024 james@firefly-iii.org.
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*/
declare(strict_types=1);
namespace FireflyIII\Events\Test;
use FireflyIII\Notifications\Notifiables\OwnerNotifiable;
use Illuminate\Queue\SerializesModels;
class OwnerTestNotificationChannel
{
use SerializesModels;
public OwnerNotifiable $owner;
public string $channel;
/**
* Create a new event instance.
*/
public function __construct(string $channel, OwnerNotifiable $owner)
{
app('log')->debug(sprintf('Triggered OwnerTestNotificationChannel("%s")', $channel));
$this->owner = $owner;
$this->channel = $channel;
}
}

View File

@@ -1,8 +1,8 @@
<?php
/**
* AdminRequestedTestMessage.php
* Copyright (c) 2019 james@firefly-iii.org
/*
* TestEmailChannel.php
* Copyright (c) 2024 james@firefly-iii.org.
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
@@ -17,31 +17,30 @@
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
* along with this program. If not, see https://www.gnu.org/licenses/.
*/
declare(strict_types=1);
namespace FireflyIII\Events;
namespace FireflyIII\Events\Test;
use FireflyIII\User;
use Illuminate\Queue\SerializesModels;
/**
* Class AdminRequestedTestMessage.
*/
class AdminRequestedTestMessage extends Event
class UserTestNotificationChannel
{
use SerializesModels;
public User $user;
public User $user;
public string $channel;
/**
* Create a new event instance.
*/
public function __construct(User $user)
public function __construct(string $channel, User $user)
{
app('log')->debug(sprintf('Triggered AdminRequestedTestMessage for user #%d (%s)', $user->id, $user->email));
$this->user = $user;
app('log')->debug(sprintf('Triggered UserTestNotificationChannel("%s")', $channel));
$this->user = $user;
$this->channel = $channel;
}
}

View File

@@ -23,27 +23,118 @@ declare(strict_types=1);
namespace FireflyIII\Factory;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\PiggyBank;
use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Repositories\ObjectGroup\CreatesObjectGroups;
use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface;
use FireflyIII\User;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Log;
/**
* Class PiggyBankFactory
*/
class PiggyBankFactory
{
private User $user;
use CreatesObjectGroups;
public User $user {
set(User $value) {
$this->user = $value;
$this->currencyRepository->setUser($value);
$this->accountRepository->setUser($value);
$this->piggyBankRepository->setUser($value);
}
}
private CurrencyRepositoryInterface $currencyRepository;
private AccountRepositoryInterface $accountRepository;
private PiggyBankRepositoryInterface $piggyBankRepository;
public function __construct()
{
$this->currencyRepository = app(CurrencyRepositoryInterface::class);
$this->accountRepository = app(AccountRepositoryInterface::class);
$this->piggyBankRepository = app(PiggyBankRepositoryInterface::class);
}
/**
* Store a piggy bank or come back with an exception.
*
* @param array $data
*
* @return PiggyBank
*/
public function store(array $data): PiggyBank
{
$piggyBankData = $data;
// unset some fields
unset($piggyBankData['object_group_title'], $piggyBankData['transaction_currency_code'], $piggyBankData['transaction_currency_id'], $piggyBankData['accounts'], $piggyBankData['object_group_id'], $piggyBankData['notes']);
// validate amount:
if (array_key_exists('target_amount', $piggyBankData) && '' === (string) $piggyBankData['target_amount']) {
$piggyBankData['target_amount'] = '0';
}
$piggyBankData['start_date_tz'] = $piggyBankData['start_date']?->format('e');
$piggyBankData['target_date_tz'] = $piggyBankData['target_date']?->format('e');
$piggyBankData['account_id'] = null;
$piggyBankData['transaction_currency_id'] = $this->getCurrency($data)->id;
$piggyBankData['order'] = 131337;
try {
/** @var PiggyBank $piggyBank */
$piggyBank = PiggyBank::createQuietly($piggyBankData);
} catch (QueryException $e) {
app('log')->error(sprintf('Could not store piggy bank: %s', $e->getMessage()), $piggyBankData);
throw new FireflyException('400005: Could not store new piggy bank.', 0, $e);
}
$piggyBank = $this->setOrder($piggyBank, $data);
$this->linkToAccountIds($piggyBank, $data['accounts']);
$this->piggyBankRepository->updateNote($piggyBank, $data['notes']);
$objectGroupTitle = $data['object_group_title'] ?? '';
if ('' !== $objectGroupTitle) {
$objectGroup = $this->findOrCreateObjectGroup($objectGroupTitle);
if (null !== $objectGroup) {
$piggyBank->objectGroups()->sync([$objectGroup->id]);
}
}
// try also with ID
$objectGroupId = (int) ($data['object_group_id'] ?? 0);
if (0 !== $objectGroupId) {
$objectGroup = $this->findObjectGroupById($objectGroupId);
if (null !== $objectGroup) {
$piggyBank->objectGroups()->sync([$objectGroup->id]);
}
}
Log::debug('Touch piggy bank');
$piggyBank->encrypted = false;
$piggyBank->save();
$piggyBank->touch();
return $piggyBank;
}
public function find(?int $piggyBankId, ?string $piggyBankName): ?PiggyBank
{
$piggyBankId = (int)$piggyBankId;
$piggyBankName = (string)$piggyBankName;
$piggyBankId = (int) $piggyBankId;
$piggyBankName = (string) $piggyBankName;
if ('' === $piggyBankName && 0 === $piggyBankId) {
return null;
}
// first find by ID:
if ($piggyBankId > 0) {
/** @var null|PiggyBank $piggyBank */
$piggyBank = $this->user->piggyBanks()->find($piggyBankId);
$piggyBank = PiggyBank
::leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id')
->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id')
->where('accounts.user_id', $this->user->id)
->where('piggy_banks.id', $piggyBankId)
->first(['piggy_banks.*']);
if (null !== $piggyBank) {
return $piggyBank;
}
@@ -63,11 +154,107 @@ class PiggyBankFactory
public function findByName(string $name): ?PiggyBank
{
return $this->user->piggyBanks()->where('piggy_banks.name', $name)->first();
return PiggyBank
::leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id')
->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id')
->where('accounts.user_id', $this->user->id)
->where('piggy_banks.name', $name)
->first(['piggy_banks.*']);
}
public function setUser(User $user): void
private function getCurrency(array $data): TransactionCurrency
{
$this->user = $user;
// currency:
$defaultCurrency = app('amount')->getDefaultCurrency();
$currency = null;
if (array_key_exists('transaction_currency_code', $data)) {
$currency = $this->currencyRepository->findByCode((string) ($data['transaction_currency_code'] ?? ''));
}
if (array_key_exists('transaction_currency_id', $data)) {
$currency = $this->currencyRepository->find((int) ($data['transaction_currency_id'] ?? 0));
}
$currency ??= $defaultCurrency;
return $currency;
}
private function setOrder(PiggyBank $piggyBank, array $data): PiggyBank
{
$this->resetOrder();
$order = $this->getMaxOrder() + 1;
if (array_key_exists('order', $data)) {
$order = $data['order'];
}
$piggyBank->order = $order;
$piggyBank->saveQuietly();
return $piggyBank;
}
public function resetOrder(): void
{
// TODO duplicate code
$set = PiggyBank
::leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id')
->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id')
->where('accounts.user_id', $this->user->id)
->with(
[
'objectGroups',
]
)
->orderBy('piggy_banks.order', 'ASC')->get(['piggy_banks.*']);
$current = 1;
foreach ($set as $piggyBank) {
if ($piggyBank->order !== $current) {
app('log')->debug(sprintf('Piggy bank #%d ("%s") was at place %d but should be on %d', $piggyBank->id, $piggyBank->name, $piggyBank->order, $current));
$piggyBank->order = $current;
$piggyBank->save();
}
++$current;
}
}
private function getMaxOrder(): int
{
return (int) $this->piggyBankRepository->getPiggyBanks()->max('order');
}
public function linkToAccountIds(PiggyBank $piggyBank, array $accounts): void
{
Log::debug(sprintf('Linking piggy bank #%d to %d accounts.', $piggyBank->id, count($accounts)), $accounts);
// collect current current_amount so the sync does not remove them.
// TODO this is a tedious check. Feels like a hack.
$toBeLinked = [];
foreach($piggyBank->accounts as $account) {
foreach($accounts as $info) {
if($account->id === $info['account_id']) {
if(array_key_exists($account->id, $accounts)) {
$toBeLinked[$account->id] = ['current_amount' => $account->pivot->current_amount];
Log::debug(sprintf('Prefilled for account #%d with amount %s', $account->id, $account->pivot->current_amount));
}
}
}
}
/** @var array $info */
foreach ($accounts as $info) {
$account = $this->accountRepository->find((int) ($info['account_id'] ?? 0));
if (null === $account) {
continue;
}
if (array_key_exists('current_amount', $info)) {
$toBeLinked[$account->id] = ['current_amount' => $info['current_amount']];
Log::debug(sprintf('Will link account #%d with amount %s', $account->id, $account->pivot->current_amount));
}
if (!array_key_exists('current_amount', $info)) {
$toBeLinked[$account->id] ??= [];
Log::debug(sprintf('Will link account #%d with info: ', $account->id), $toBeLinked[$account->id]);
}
}
Log::debug(sprintf('Link information: %s', json_encode($toBeLinked)));
$piggyBank->accounts()->sync($toBeLinked);
}
}

View File

@@ -24,12 +24,18 @@ declare(strict_types=1);
namespace FireflyIII\Handlers\Events;
use FireflyIII\Events\Admin\InvitationCreated;
use FireflyIII\Events\AdminRequestedTestMessage;
use FireflyIII\Events\NewVersionAvailable;
use FireflyIII\Notifications\Admin\TestNotification;
use FireflyIII\Events\Security\UnknownUserAttemptedLogin;
use FireflyIII\Events\Test\OwnerTestNotificationChannel;
use FireflyIII\Notifications\Admin\UnknownUserLoginAttempt;
use FireflyIII\Notifications\Admin\UserInvitation;
use FireflyIII\Notifications\Admin\VersionCheckResult;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\Notifications\Notifiables\OwnerNotifiable;
use FireflyIII\Notifications\Test\OwnerTestNotificationEmail;
use FireflyIII\Notifications\Test\OwnerTestNotificationNtfy;
use FireflyIII\Notifications\Test\OwnerTestNotificationPushover;
use FireflyIII\Notifications\Test\OwnerTestNotificationSlack;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Notification;
/**
@@ -37,89 +43,11 @@ use Illuminate\Support\Facades\Notification;
*/
class AdminEventHandler
{
public function sendInvitationNotification(InvitationCreated $event): void
public function sendLoginAttemptNotification(UnknownUserAttemptedLogin $event): void
{
$sendMail = app('fireflyconfig')->get('notification_invite_created', true)->data;
if (false === $sendMail) {
return;
}
/** @var UserRepositoryInterface $repository */
$repository = app(UserRepositoryInterface::class);
$all = $repository->all();
foreach ($all as $user) {
if ($repository->hasRole($user, 'owner')) {
try {
Notification::send($user, new UserInvitation($event->invitee));
} catch (\Exception $e) { // @phpstan-ignore-line
$message = $e->getMessage();
if (str_contains($message, 'Bcc')) {
app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.');
return;
}
if (str_contains($message, 'RFC 2822')) {
app('log')->warning('[RFC] Could not send notification. Please validate your email settings, use the .env.example file as a guide.');
return;
}
app('log')->error($e->getMessage());
app('log')->error($e->getTraceAsString());
}
}
}
}
/**
* Send new version message to admin.
*/
public function sendNewVersion(NewVersionAvailable $event): void
{
$sendMail = app('fireflyconfig')->get('notification_new_version', true)->data;
if (false === $sendMail) {
return;
}
/** @var UserRepositoryInterface $repository */
$repository = app(UserRepositoryInterface::class);
$all = $repository->all();
foreach ($all as $user) {
if ($repository->hasRole($user, 'owner')) {
try {
Notification::send($user, new VersionCheckResult($event->message));
} catch (\Exception $e) {// @phpstan-ignore-line
$message = $e->getMessage();
if (str_contains($message, 'Bcc')) {
app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.');
return;
}
if (str_contains($message, 'RFC 2822')) {
app('log')->warning('[RFC] Could not send notification. Please validate your email settings, use the .env.example file as a guide.');
return;
}
app('log')->error($e->getMessage());
app('log')->error($e->getTraceAsString());
}
}
}
}
/**
* Sends a test message to an administrator.
*/
public function sendTestMessage(AdminRequestedTestMessage $event): void
{
/** @var UserRepositoryInterface $repository */
$repository = app(UserRepositoryInterface::class);
if (!$repository->hasRole($event->user, 'owner')) {
return;
}
try {
Notification::send($event->user, new TestNotification($event->user->email));
$owner = new OwnerNotifiable();
Notification::send($owner, new UnknownUserLoginAttempt($event->address));
} catch (\Exception $e) { // @phpstan-ignore-line
$message = $e->getMessage();
if (str_contains($message, 'Bcc')) {
@@ -136,4 +64,116 @@ class AdminEventHandler
app('log')->error($e->getTraceAsString());
}
}
public function sendInvitationNotification(InvitationCreated $event): void
{
$sendMail = app('fireflyconfig')->get('notification_invite_created', true)->data;
if (false === $sendMail) {
return;
}
try {
$owner = new OwnerNotifiable();
Notification::send($owner, new UserInvitation($owner, $event->invitee));
} catch (\Exception $e) { // @phpstan-ignore-line
$message = $e->getMessage();
if (str_contains($message, 'Bcc')) {
app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.');
return;
}
if (str_contains($message, 'RFC 2822')) {
app('log')->warning('[RFC] Could not send notification. Please validate your email settings, use the .env.example file as a guide.');
return;
}
app('log')->error($e->getMessage());
app('log')->error($e->getTraceAsString());
}
}
/**
* Send new version message to admin.
*/
public function sendNewVersion(NewVersionAvailable $event): void
{
$sendMail = app('fireflyconfig')->get('notification_new_version', true)->data;
if (false === $sendMail) {
return;
}
try {
$owner = new OwnerNotifiable();
Notification::send($owner, new VersionCheckResult($event->message));
} catch (\Exception $e) {// @phpstan-ignore-line
$message = $e->getMessage();
if (str_contains($message, 'Bcc')) {
app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.');
return;
}
if (str_contains($message, 'RFC 2822')) {
app('log')->warning('[RFC] Could not send notification. Please validate your email settings, use the .env.example file as a guide.');
return;
}
app('log')->error($e->getMessage());
app('log')->error($e->getTraceAsString());
}
}
/**
* Sends a test message to an administrator.
*/
public function sendTestNotification(OwnerTestNotificationChannel $event): void
{
Log::debug(sprintf('Now in sendTestNotification("%s")', $event->channel));
switch ($event->channel) {
case 'email':
$class = OwnerTestNotificationEmail::class;
break;
case 'slack':
$class = OwnerTestNotificationSlack::class;
break;
case 'ntfy':
$class = OwnerTestNotificationNtfy::class;
break;
case 'pushover':
$class = OwnerTestNotificationPushover::class;
break;
default:
app('log')->error(sprintf('Unknown channel "%s" in sendTestNotification method.', $event->channel));
return;
}
Log::debug(sprintf('Will send %s as a notification.', $class));
try {
Notification::send($event->owner, new $class($event->owner));
} catch (\Exception $e) { // @phpstan-ignore-line
$message = $e->getMessage();
if (str_contains($message, 'Bcc')) {
app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.');
return;
}
if (str_contains($message, 'RFC 2822')) {
app('log')->warning('[RFC] Could not send notification. Please validate your email settings, use the .env.example file as a guide.');
return;
}
app('log')->error($e->getMessage());
app('log')->error($e->getTraceAsString());
}
Log::debug(sprintf('If you see no errors above this line, test notification was sent over channel "%s"', $event->channel));
}
}

View File

@@ -0,0 +1,135 @@
<?php
/*
* PreferencesEventHandler.php
* Copyright (c) 2024 james@firefly-iii.org.
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*/
declare(strict_types=1);
namespace FireflyIII\Handlers\Events;
use FireflyIII\Events\Preferences\UserGroupChangedDefaultCurrency;
use FireflyIII\Models\Budget;
use FireflyIII\Models\PiggyBank;
use FireflyIII\Models\UserGroup;
use FireflyIII\Repositories\UserGroups\Budget\BudgetRepositoryInterface;
use FireflyIII\Repositories\UserGroups\PiggyBank\PiggyBankRepositoryInterface;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class PreferencesEventHandler
{
public function resetNativeAmounts(UserGroupChangedDefaultCurrency $event): void
{
// Reset the native amounts for all objects that have it.
Log::debug('Resetting native amounts for all objects.');
$tables = [
// !!! this array is also in the migration
'accounts' => ['native_virtual_balance'],
'available_budgets' => ['native_amount'],
'bills' => ['native_amount_min', 'native_amount_max'],
// 'transactions' => ['native_amount', 'native_foreign_amount']
];
foreach ($tables as $table => $columns) {
foreach ($columns as $column) {
Log::debug(sprintf('Resetting column %s in table %s.', $column, $table));
DB::table($table)->where('user_group_id', $event->userGroup->id)->update([$column => null]);
}
}
$this->resetPiggyBanks($event->userGroup);
$this->resetBudgets($event->userGroup);
$this->resetTransactions($event->userGroup);
}
private function resetPiggyBanks(UserGroup $userGroup): void
{
$repository = app(PiggyBankRepositoryInterface::class);
$repository->setUserGroup($userGroup);
$piggyBanks = $repository->getPiggyBanks();
/** @var PiggyBank $piggyBank */
foreach ($piggyBanks as $piggyBank) {
if (null !== $piggyBank->native_target_amount) {
Log::debug(sprintf('Resetting native_target_amount for piggy bank #%d.', $piggyBank->id));
$piggyBank->native_target_amount = null;
$piggyBank->saveQuietly();
}
foreach ($piggyBank->accounts as $account) {
if (null !== $account->pivot->native_current_amount) {
Log::debug(sprintf('Resetting native_current_amount for piggy bank #%d and account #%d.', $piggyBank->id, $account->id));
$account->pivot->native_current_amount = null;
$account->pivot->save();
}
}
foreach ($piggyBank->piggyBankEvents as $event) {
if (null !== $event->native_amount) {
Log::debug(sprintf('Resetting native_amount for piggy bank #%d and event #%d.', $piggyBank->id, $event->id));
$event->native_amount = null;
$event->saveQuietly();
}
}
}
}
private function resetBudgets(UserGroup $userGroup): void
{
$repository = app(BudgetRepositoryInterface::class);
$repository->setUserGroup($userGroup);
$set = $repository->getBudgets();
/** @var Budget $budget */
foreach ($set as $budget) {
foreach ($budget->autoBudgets as $autoBudget) {
if (null !== $autoBudget->native_amount) {
if (null !== $autoBudget->native_amount) {
Log::debug(sprintf('Resetting native_amount for budget #%d and auto budget #%d.', $budget->id, $autoBudget->id));
$autoBudget->native_amount = null;
$autoBudget->saveQuietly();
}
}
}
foreach ($budget->budgetlimits as $limit) {
if (null !== $limit->native_amount) {
Log::debug(sprintf('Resetting native_amount for budget #%d and budget limit #%d.', $budget->id, $limit->id));
$limit->native_amount = null;
$limit->saveQuietly();
}
}
}
}
private function resetTransactions(UserGroup $userGroup): void
{
// custom query because of the potential size of this update.
$success = DB::table('transactions')
->join('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
->where('transaction_journals.user_group_id', $userGroup->id)
->where(static function (Builder $q): void {
$q->whereNotNull('native_amount')
->orWhereNotNull('native_foreign_amount')
;
})
->update(['native_amount' => null, 'native_foreign_amount' => null])
;
Log::debug(sprintf('Updated %d transactions.', $success));
}
}

View File

@@ -31,6 +31,8 @@ use FireflyIII\Events\Admin\InvitationCreated;
use FireflyIII\Events\DetectedNewIPAddress;
use FireflyIII\Events\RegisteredUser;
use FireflyIII\Events\RequestedNewPassword;
use FireflyIII\Events\Security\UserAttemptedLogin;
use FireflyIII\Events\Test\UserTestNotificationChannel;
use FireflyIII\Events\UserChangedEmail;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Mail\ConfirmEmailChangeMail;
@@ -40,12 +42,18 @@ use FireflyIII\Models\GroupMembership;
use FireflyIII\Models\UserGroup;
use FireflyIII\Models\UserRole;
use FireflyIII\Notifications\Admin\UserRegistration as AdminRegistrationNotification;
use FireflyIII\Notifications\Security\UserFailedLoginAttempt;
use FireflyIII\Notifications\Test\UserTestNotificationEmail;
use FireflyIII\Notifications\Test\UserTestNotificationNtfy;
use FireflyIII\Notifications\Test\UserTestNotificationPushover;
use FireflyIII\Notifications\Test\UserTestNotificationSlack;
use FireflyIII\Notifications\User\UserLogin;
use FireflyIII\Notifications\User\UserNewPassword;
use FireflyIII\Notifications\User\UserRegistration as UserRegistrationNotification;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\User;
use Illuminate\Auth\Events\Login;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Notification;
use Mail;
@@ -220,31 +228,26 @@ class UserEventHandler
public function sendAdminRegistrationNotification(RegisteredUser $event): void
{
$sendMail = (bool)app('fireflyconfig')->get('notification_admin_new_reg', true)->data;
$sendMail = (bool) app('fireflyconfig')->get('notification_admin_new_reg', true)->data;
if ($sendMail) {
/** @var UserRepositoryInterface $repository */
$repository = app(UserRepositoryInterface::class);
$all = $repository->all();
foreach ($all as $user) {
if ($repository->hasRole($user, 'owner')) {
try {
Notification::send($user, new AdminRegistrationNotification($event->user));
} catch (\Exception $e) { // @phpstan-ignore-line
$message = $e->getMessage();
if (str_contains($message, 'Bcc')) {
app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.');
$owner = $event->owner;
return;
}
if (str_contains($message, 'RFC 2822')) {
app('log')->warning('[RFC] Could not send notification. Please validate your email settings, use the .env.example file as a guide.');
try {
Notification::send($owner, new AdminRegistrationNotification($event->owner, $event->user));
} catch (\Exception $e) { // @phpstan-ignore-line
$message = $e->getMessage();
if (str_contains($message, 'Bcc')) {
app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.');
return;
}
app('log')->error($e->getMessage());
app('log')->error($e->getTraceAsString());
}
return;
}
if (str_contains($message, 'RFC 2822')) {
app('log')->warning('[RFC] Could not send notification. Please validate your email settings, use the .env.example file as a guide.');
return;
}
app('log')->error($e->getMessage());
app('log')->error($e->getTraceAsString());
}
}
}
@@ -285,7 +288,7 @@ class UserEventHandler
$oldEmail = $event->oldEmail;
$user = $event->user;
$token = app('preferences')->getForUser($user, 'email_change_undo_token', 'invalid');
$hashed = hash('sha256', sprintf('%s%s', (string)config('app.key'), $oldEmail));
$hashed = hash('sha256', sprintf('%s%s', (string) config('app.key'), $oldEmail));
$url = route('profile.undo-email-change', [$token->data, $hashed]);
try {
@@ -347,7 +350,7 @@ class UserEventHandler
*/
public function sendRegistrationMail(RegisteredUser $event): void
{
$sendMail = (bool)app('fireflyconfig')->get('notification_user_new_reg', true)->data;
$sendMail = (bool) app('fireflyconfig')->get('notification_user_new_reg', true)->data;
if ($sendMail) {
try {
Notification::send($event->user, new UserRegistrationNotification());
@@ -428,4 +431,80 @@ class UserEventHandler
event(new DetectedNewIPAddress($user, $ip));
}
}
public function sendLoginAttemptNotification(UserAttemptedLogin $event): void
{
try {
Notification::send($event->user, new UserFailedLoginAttempt($event->user));
} catch (\Exception $e) { // @phpstan-ignore-line
$message = $e->getMessage();
if (str_contains($message, 'Bcc')) {
app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.');
return;
}
if (str_contains($message, 'RFC 2822')) {
app('log')->warning('[RFC] Could not send notification. Please validate your email settings, use the .env.example file as a guide.');
return;
}
app('log')->error($e->getMessage());
app('log')->error($e->getTraceAsString());
}
}
/**
* Sends a test message to an administrator.
*/
public function sendTestNotification(UserTestNotificationChannel $event): void
{
Log::debug(sprintf('Now in (user) sendTestNotification("%s")', $event->channel));
switch ($event->channel) {
case 'email':
$class = UserTestNotificationEmail::class;
break;
case 'slack':
$class = UserTestNotificationSlack::class;
break;
case 'ntfy':
$class = UserTestNotificationNtfy::class;
break;
case 'pushover':
$class = UserTestNotificationPushover::class;
break;
default:
app('log')->error(sprintf('Unknown channel "%s" in (user) sendTestNotification method.', $event->channel));
return;
}
Log::debug(sprintf('Will send %s as a notification.', $class));
try {
Notification::send($event->user, new $class($event->user));
} catch (\Exception $e) { // @phpstan-ignore-line
$message = $e->getMessage();
if (str_contains($message, 'Bcc')) {
app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.');
return;
}
if (str_contains($message, 'RFC 2822')) {
app('log')->warning('[RFC] Could not send notification. Please validate your email settings, use the .env.example file as a guide.');
return;
}
app('log')->error($e->getMessage());
app('log')->error($e->getTraceAsString());
}
Log::debug(sprintf('If you see no errors above this line, test notification was sent over channel "%s"', $event->channel));
}
}

View File

@@ -25,6 +25,10 @@ declare(strict_types=1);
namespace FireflyIII\Handlers\Observer;
use FireflyIII\Models\Account;
use FireflyIII\Models\PiggyBank;
use FireflyIII\Repositories\UserGroups\Account\AccountRepositoryInterface;
use FireflyIII\Support\Http\Api\ExchangeRateConverter;
use Illuminate\Support\Facades\Log;
/**
* Class AccountObserver
@@ -38,8 +42,10 @@ class AccountObserver
{
app('log')->debug('Observe "deleting" of an account.');
$account->accountMeta()->delete();
/** @var PiggyBank $piggy */
foreach ($account->piggyBanks()->get() as $piggy) {
$piggy->delete();
$piggy->accounts()->detach($account);
}
foreach ($account->attachments()->get() as $attachment) {
$attachment->delete();
@@ -50,4 +56,35 @@ class AccountObserver
$account->notes()->delete();
$account->locations()->delete();
}
public function created(Account $account): void
{
Log::debug('Observe "created" of an account.');
$this->updateNativeAmount($account);
}
public function updated(Account $account): void
{
Log::debug('Observe "updated" of an account.');
$this->updateNativeAmount($account);
}
private function updateNativeAmount(Account $account): void
{
$userCurrency = app('amount')->getDefaultCurrencyByUserGroup($account->user->userGroup);
$repository = app(AccountRepositoryInterface::class);
$currency = $repository->getAccountCurrency($account);
if (null !== $currency && $currency->id !== $userCurrency->id && '' !== (string) $account->virtual_balance && 0 !== bccomp($account->virtual_balance, '0')) {
$converter = new ExchangeRateConverter();
$converter->setIgnoreSettings(true);
$account->native_virtual_balance = $converter->convert($currency, $userCurrency, today(), $account->virtual_balance);
}
if ('' === (string) $account->virtual_balance || ('' !== (string) $account->virtual_balance && 0 === bccomp($account->virtual_balance, '0'))) {
$account->virtual_balance = null;
$account->native_virtual_balance = null;
}
$account->saveQuietly();
Log::debug('Account native virtual balance is updated.');
}
}

View File

@@ -0,0 +1,57 @@
<?php
/*
* AutoBudgetObserver.php
* Copyright (c) 2024 james@firefly-iii.org.
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*/
declare(strict_types=1);
namespace FireflyIII\Handlers\Observer;
use FireflyIII\Models\AutoBudget;
use FireflyIII\Support\Http\Api\ExchangeRateConverter;
use Illuminate\Support\Facades\Log;
class AutoBudgetObserver
{
public function updated(AutoBudget $autoBudget): void
{
Log::debug('Observe "updated" of an auto budget.');
$this->updateNativeAmount($autoBudget);
}
public function created(AutoBudget $autoBudget): void
{
Log::debug('Observe "created" of an auto budget.');
$this->updateNativeAmount($autoBudget);
}
private function updateNativeAmount(AutoBudget $autoBudget): void
{
$userCurrency = app('amount')->getDefaultCurrencyByUserGroup($autoBudget->budget->user->userGroup);
$autoBudget->native_amount = null;
if ($autoBudget->transactionCurrency->id !== $userCurrency->id) {
$converter = new ExchangeRateConverter();
$converter->setIgnoreSettings(true);
$autoBudget->native_amount = $converter->convert($autoBudget->transactionCurrency, $userCurrency, today(), $autoBudget->amount);
}
$autoBudget->saveQuietly();
Log::debug('Auto budget native amount is updated.');
}
}

View File

@@ -0,0 +1,57 @@
<?php
/*
* AutoBudgetObserver.php
* Copyright (c) 2024 james@firefly-iii.org.
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*/
declare(strict_types=1);
namespace FireflyIII\Handlers\Observer;
use FireflyIII\Models\AvailableBudget;
use FireflyIII\Support\Http\Api\ExchangeRateConverter;
use Illuminate\Support\Facades\Log;
class AvailableBudgetObserver
{
public function updated(AvailableBudget $availableBudget): void
{
Log::debug('Observe "updated" of an available budget.');
$this->updateNativeAmount($availableBudget);
}
public function created(AvailableBudget $availableBudget): void
{
Log::debug('Observe "created" of an available budget.');
$this->updateNativeAmount($availableBudget);
}
private function updateNativeAmount(AvailableBudget $availableBudget): void
{
$userCurrency = app('amount')->getDefaultCurrencyByUserGroup($availableBudget->user->userGroup);
$availableBudget->native_amount = null;
if ($availableBudget->transactionCurrency->id !== $userCurrency->id) {
$converter = new ExchangeRateConverter();
$converter->setIgnoreSettings(true);
$availableBudget->native_amount = $converter->convert($availableBudget->transactionCurrency, $userCurrency, today(), $availableBudget->amount);
}
$availableBudget->saveQuietly();
Log::debug('Available budget native amount is updated.');
}
}

View File

@@ -24,6 +24,8 @@ declare(strict_types=1);
namespace FireflyIII\Handlers\Observer;
use FireflyIII\Models\Bill;
use FireflyIII\Support\Http\Api\ExchangeRateConverter;
use Illuminate\Support\Facades\Log;
/**
* Class BillObserver
@@ -38,4 +40,31 @@ class BillObserver
}
$bill->notes()->delete();
}
public function updated(Bill $bill): void
{
Log::debug('Observe "updated" of a bill.');
$this->updateNativeAmount($bill);
}
public function created(Bill $bill): void
{
Log::debug('Observe "created" of a bill.');
$this->updateNativeAmount($bill);
}
private function updateNativeAmount(Bill $bill): void
{
$userCurrency = app('amount')->getDefaultCurrencyByUserGroup($bill->user->userGroup);
$bill->native_amount_min = null;
$bill->native_amount_max = null;
if ($bill->transactionCurrency->id !== $userCurrency->id) {
$converter = new ExchangeRateConverter();
$converter->setIgnoreSettings(true);
$bill->native_amount_min = $converter->convert($bill->transactionCurrency, $userCurrency, today(), $bill->amount_min);
$bill->native_amount_max = $converter->convert($bill->transactionCurrency, $userCurrency, today(), $bill->amount_max);
}
$bill->saveQuietly();
Log::debug('Bill native amounts are updated.');
}
}

View File

@@ -0,0 +1,57 @@
<?php
/*
* BudgetLimitObserver.php
* Copyright (c) 2024 james@firefly-iii.org.
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*/
declare(strict_types=1);
namespace FireflyIII\Handlers\Observer;
use FireflyIII\Models\BudgetLimit;
use FireflyIII\Support\Http\Api\ExchangeRateConverter;
use Illuminate\Support\Facades\Log;
class BudgetLimitObserver
{
public function updated(BudgetLimit $budgetLimit): void
{
Log::debug('Observe "updated" of a budget limit.');
$this->updateNativeAmount($budgetLimit);
}
public function created(BudgetLimit $budgetLimit): void
{
Log::debug('Observe "created" of a budget limit.');
$this->updateNativeAmount($budgetLimit);
}
private function updateNativeAmount(BudgetLimit $budgetLimit): void
{
$userCurrency = app('amount')->getDefaultCurrencyByUserGroup($budgetLimit->budget->user->userGroup);
$budgetLimit->native_amount = null;
if ($budgetLimit->transactionCurrency->id !== $userCurrency->id) {
$converter = new ExchangeRateConverter();
$converter->setIgnoreSettings(true);
$budgetLimit->native_amount = $converter->convert($budgetLimit->transactionCurrency, $userCurrency, today(), $budgetLimit->amount);
}
$budgetLimit->saveQuietly();
Log::debug('Budget limit native amounts are updated.');
}
}

View File

@@ -0,0 +1,57 @@
<?php
/*
* AutoBudgetObserver.php
* Copyright (c) 2024 james@firefly-iii.org.
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*/
declare(strict_types=1);
namespace FireflyIII\Handlers\Observer;
use FireflyIII\Models\PiggyBankEvent;
use FireflyIII\Support\Http\Api\ExchangeRateConverter;
use Illuminate\Support\Facades\Log;
class PiggyBankEventObserver
{
public function updated(PiggyBankEvent $event): void
{
Log::debug('Observe "updated" of a piggy bank event.');
$this->updateNativeAmount($event);
}
public function created(PiggyBankEvent $event): void
{
Log::debug('Observe "created" of a piggy bank event.');
$this->updateNativeAmount($event);
}
private function updateNativeAmount(PiggyBankEvent $event): void
{
$userCurrency = app('amount')->getDefaultCurrencyByUserGroup($event->piggyBank->accounts()->first()->user->userGroup);
$event->native_amount = null;
if ($event->piggyBank->transactionCurrency->id !== $userCurrency->id) {
$converter = new ExchangeRateConverter();
$converter->setIgnoreSettings(true);
$event->native_amount = $converter->convert($event->piggyBank->transactionCurrency, $userCurrency, today(), $event->amount);
}
$event->saveQuietly();
Log::debug('Piggy bank event native amount is updated.');
}
}

View File

@@ -25,24 +25,46 @@ declare(strict_types=1);
namespace FireflyIII\Handlers\Observer;
use FireflyIII\Models\PiggyBank;
use FireflyIII\Models\PiggyBankRepetition;
use FireflyIII\Support\Http\Api\ExchangeRateConverter;
use Illuminate\Support\Facades\Log;
/**
* Class PiggyBankObserver
*/
class PiggyBankObserver
{
public function updated(PiggyBank $piggyBank): void
{
Log::debug('Observe "updated" of a piggy bank.');
$this->updateNativeAmount($piggyBank);
}
public function created(PiggyBank $piggyBank): void
{
app('log')->debug('Observe "created" of a piggy bank.');
$repetition = new PiggyBankRepetition();
$repetition->piggyBank()->associate($piggyBank);
$repetition->startdate = $piggyBank->startdate;
$repetition->startdate_tz = $piggyBank->startdate->format('e');
$repetition->targetdate = $piggyBank->targetdate;
$repetition->targetdate_tz = $piggyBank->targetdate?->format('e');
$repetition->currentamount = '0';
$repetition->save();
Log::debug('Observe "created" of a piggy bank.');
$this->updateNativeAmount($piggyBank);
}
private function updateNativeAmount(PiggyBank $piggyBank): void
{
$group = $piggyBank->accounts()->first()?->user->userGroup;
if (null === $group) {
Log::debug(sprintf('No account(s) yet for piggy bank #%d.', $piggyBank->id));
return;
}
$userCurrency = app('amount')->getDefaultCurrencyByUserGroup($group);
if (null === $userCurrency) {
return;
}
$piggyBank->native_target_amount = null;
if ($piggyBank->transactionCurrency->id !== $userCurrency->id) {
$converter = new ExchangeRateConverter();
$converter->setIgnoreSettings(true);
$piggyBank->native_target_amount = $converter->convert($piggyBank->transactionCurrency, $userCurrency, today(), $piggyBank->target_amount);
}
$piggyBank->saveQuietly();
Log::debug('Piggy bank native target amount is updated.');
}
/**

View File

@@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Handlers\Observer;
use FireflyIII\Models\Transaction;
use FireflyIII\Support\Http\Api\ExchangeRateConverter;
use FireflyIII\Support\Models\AccountBalanceCalculator;
use Illuminate\Support\Facades\Log;
@@ -32,6 +33,8 @@ use Illuminate\Support\Facades\Log;
*/
class TransactionObserver
{
public static bool $recalculate = true;
public function deleting(?Transaction $transaction): void
{
app('log')->debug('Observe "deleting" of a transaction.');
@@ -41,18 +44,46 @@ class TransactionObserver
public function updated(Transaction $transaction): void
{
Log::debug('Observe "updated" of a transaction.');
if (1 === bccomp($transaction->amount, '0')) {
Log::debug('Trigger recalculateForJournal');
AccountBalanceCalculator::recalculateForJournal($transaction->transactionJournal);
if (config('firefly.feature_flags.running_balance_column') && self::$recalculate) {
if (1 === bccomp($transaction->amount, '0')) {
Log::debug('Trigger recalculateForJournal');
AccountBalanceCalculator::recalculateForJournal($transaction->transactionJournal);
}
}
$this->updateNativeAmount($transaction);
}
public function created(Transaction $transaction): void
{
Log::debug('Observe "created" of a transaction.');
if (1 === bccomp($transaction->amount, '0')) {
Log::debug('Trigger recalculateForJournal');
AccountBalanceCalculator::recalculateForJournal($transaction->transactionJournal);
if (config('firefly.feature_flags.running_balance_column')) {
if (1 === bccomp($transaction->amount, '0') && self::$recalculate) {
Log::debug('Trigger recalculateForJournal');
AccountBalanceCalculator::recalculateForJournal($transaction->transactionJournal);
}
}
$this->updateNativeAmount($transaction);
}
private function updateNativeAmount(Transaction $transaction): void
{
$userCurrency = app('amount')->getDefaultCurrencyByUserGroup($transaction->transactionJournal->user->userGroup);
$transaction->native_amount = null;
$transaction->native_foreign_amount = null;
// first normal amount
if ($transaction->transactionCurrency->id !== $userCurrency->id) {
$converter = new ExchangeRateConverter();
$converter->setIgnoreSettings(true);
$transaction->native_amount = $converter->convert($transaction->transactionCurrency, $userCurrency, $transaction->transactionJournal->date, $transaction->amount);
}
// then foreign amount
if ($transaction->foreignCurrency?->id !== $userCurrency->id && null !== $transaction->foreign_amount && null !== $transaction->foreignCurrency) {
$converter = new ExchangeRateConverter();
$converter->setIgnoreSettings(true);
$transaction->native_foreign_amount = $converter->convert($transaction->foreignCurrency, $userCurrency, $transaction->transactionJournal->date, $transaction->foreign_amount);
}
$transaction->saveQuietly();
Log::debug('Transaction native amounts are updated.');
}
}

View File

@@ -463,7 +463,6 @@ class GroupCollector implements GroupCollectorInterface
$this->query->orWhereIn('transaction_journals.transaction_group_id', $groupIds);
}
$result = $this->query->get($this->fields);
// now to parse this into an array.
$collection = $this->parseArray($result);
@@ -1049,6 +1048,7 @@ class GroupCollector implements GroupCollectorInterface
->whereNull('transaction_groups.deleted_at')
->whereNull('transaction_journals.deleted_at')
->whereNull('source.deleted_at')
->whereNotNull('transaction_groups.id')
->whereNull('destination.deleted_at')
->orderBy('transaction_journals.date', 'DESC')
->orderBy('transaction_journals.order', 'ASC')

View File

@@ -23,15 +23,9 @@ declare(strict_types=1);
namespace FireflyIII\Http\Controllers\Admin;
use FireflyIII\Events\AdminRequestedTestMessage;
use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Http\Middleware\IsDemoUser;
use FireflyIII\Support\Notifications\UrlValidator;
use FireflyIII\User;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;
@@ -65,53 +59,6 @@ class HomeController extends Controller
$email = $pref->data;
}
// admin notification settings:
$notifications = [];
foreach (config('firefly.admin_notifications') as $item) {
$notifications[$item] = app('fireflyconfig')->get(sprintf('notification_%s', $item), true)->data;
}
$slackUrl = app('fireflyconfig')->get('slack_webhook_url', '')->data;
return view('admin.index', compact('title', 'mainTitleIcon', 'email', 'notifications', 'slackUrl'));
}
public function notifications(Request $request): RedirectResponse
{
foreach (config('firefly.admin_notifications') as $item) {
$value = false;
if ($request->has(sprintf('notification_%s', $item))) {
$value = true;
}
app('fireflyconfig')->set(sprintf('notification_%s', $item), $value);
}
$url = (string)$request->get('slackUrl');
if ('' === $url) {
app('fireflyconfig')->delete('slack_webhook_url');
}
if (UrlValidator::isValidWebhookURL($url)) {
app('fireflyconfig')->set('slack_webhook_url', $url);
}
session()->flash('success', (string)trans('firefly.notification_settings_saved'));
return redirect(route('admin.index'));
}
/**
* Send a test message to the admin.
*
* @return Redirector|RedirectResponse
*/
public function testMessage()
{
Log::channel('audit')->info('User sends test message.');
/** @var User $user */
$user = auth()->user();
app('log')->debug('Now in testMessage() controller.');
event(new AdminRequestedTestMessage($user));
session()->flash('info', (string)trans('firefly.send_test_triggered'));
return redirect(route('admin.index'));
return view('admin.index', compact('title', 'mainTitleIcon', 'email'));
}
}

View File

@@ -0,0 +1,144 @@
<?php
/*
* NotificationController.php
* Copyright (c) 2024 james@firefly-iii.org.
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*/
declare(strict_types=1);
namespace FireflyIII\Http\Controllers\Admin;
use FireflyIII\Events\Test\OwnerTestNotificationChannel;
use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Http\Requests\NotificationRequest;
use FireflyIII\Notifications\Notifiables\OwnerNotifiable;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
class NotificationController extends Controller
{
public function index()
{
Log::channel('audit')->info('User visits notifications index.');
$title = (string) trans('firefly.administration');
$mainTitleIcon = 'fa-hand-spock-o';
$subTitle = (string) trans('firefly.title_owner_notifications');
$subTitleIcon = 'envelope-o';
// notification settings:
$slackUrl = app('fireflyconfig')->getEncrypted('slack_webhook_url', '')->data;
$pushoverAppToken = app('fireflyconfig')->getEncrypted('pushover_app_token', '')->data;
$pushoverUserToken = app('fireflyconfig')->getEncrypted('pushover_user_token', '')->data;
$ntfyServer = app('fireflyconfig')->getEncrypted('ntfy_server', 'https://ntfy.sh')->data;
$ntfyTopic = app('fireflyconfig')->getEncrypted('ntfy_topic', '')->data;
$ntfyAuth = app('fireflyconfig')->get('ntfy_auth', false)->data;
$ntfyUser = app('fireflyconfig')->getEncrypted('ntfy_user', '')->data;
$ntfyPass = app('fireflyconfig')->getEncrypted('ntfy_pass', '')->data;
$channels = config('notifications.channels');
$forcedAvailability = [];
// admin notification settings:
$notifications = [];
foreach (config('notifications.notifications.owner') as $key => $info) {
if ($info['enabled']) {
$notifications[$key] = app('fireflyconfig')->get(sprintf('notification_%s', $key), true)->data;
}
}
// loop all channels to see if they are available.
foreach ($channels as $channel => $info) {
$forcedAvailability[$channel] = true;
}
$forcedAvailability['ntfy'] = '' !== $ntfyTopic;
$forcedAvailability['pushover'] = '' !== $pushoverAppToken && '' !== $pushoverUserToken;
return view(
'admin.notifications.index',
compact(
'title',
'subTitle',
'forcedAvailability',
'mainTitleIcon',
'subTitleIcon',
'channels',
'slackUrl',
'notifications',
'pushoverAppToken',
'pushoverUserToken',
'ntfyServer',
'ntfyTopic',
'ntfyAuth',
'ntfyUser',
'ntfyPass'
)
);
}
public function postIndex(NotificationRequest $request): RedirectResponse
{
$all = $request->getAll();
foreach (config('notifications.notifications.owner') as $key => $info) {
if (array_key_exists($key, $all)) {
app('fireflyconfig')->set(sprintf('notification_%s', $key), $all[$key]);
}
}
$variables = ['slack_webhook_url', 'pushover_app_token', 'pushover_user_token', 'ntfy_server', 'ntfy_topic', 'ntfy_user', 'ntfy_pass'];
foreach ($variables as $variable) {
if ('' === $all[$variable]) {
app('fireflyconfig')->delete($variable);
}
if ('' !== $all[$variable]) {
app('fireflyconfig')->setEncrypted($variable, $all[$variable]);
}
}
app('fireflyconfig')->set('ntfy_auth', $all['ntfy_auth'] ?? false);
session()->flash('success', (string) trans('firefly.notification_settings_saved'));
return redirect(route('admin.notification.index'));
}
public function testNotification(Request $request): RedirectResponse
{
$all = $request->all();
$channel = $all['test_submit'] ?? '';
switch ($channel) {
default:
session()->flash('error', (string) trans('firefly.notification_test_failed', ['channel' => $channel]));
break;
case 'email':
case 'slack':
case 'pushover':
case 'ntfy':
$owner = new OwnerNotifiable();
app('log')->debug(sprintf('Now in testNotification("%s") controller.', $channel));
event(new OwnerTestNotificationChannel($channel, $owner));
session()->flash('success', (string) trans('firefly.notification_test_executed', ['channel' => $channel]));
}
return redirect(route('admin.notification.index'));
}
}

View File

@@ -25,9 +25,12 @@ namespace FireflyIII\Http\Controllers\Auth;
use Cookie;
use FireflyIII\Events\ActuallyLoggedIn;
use FireflyIII\Events\Security\UnknownUserAttemptedLogin;
use FireflyIII\Events\Security\UserAttemptedLogin;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Providers\RouteServiceProvider;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\View\Factory;
use Illuminate\Contracts\View\View;
@@ -57,6 +60,7 @@ class LoginController extends Controller
* Where to redirect users after login.
*/
protected string $redirectTo = RouteServiceProvider::HOME;
private UserRepositoryInterface $repository;
private string $username;
@@ -66,8 +70,9 @@ class LoginController extends Controller
public function __construct()
{
parent::__construct();
$this->username = 'email';
$this->username = 'email';
$this->middleware('guest')->except('logout');
$this->repository = app(UserRepositoryInterface::class);
}
/**
@@ -122,6 +127,15 @@ class LoginController extends Controller
return $this->sendLoginResponse($request);
}
app('log')->warning('Login attempt failed.');
$username = (string) $request->get($this->username());
$user = $this->repository->findByEmail($username);
if (null === $user) {
// send event to owner.
event(new UnknownUserAttemptedLogin($username));
}
if (null !== $user) {
event(new UserAttemptedLogin($user));
}
// Copied directly from AuthenticatesUsers, but with logging added:
// If the login attempt was unsuccessful we will increment the number of attempts

View File

@@ -26,6 +26,7 @@ namespace FireflyIII\Http\Controllers\Auth;
use FireflyIII\Events\RegisteredUser;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Notifications\Notifiables\OwnerNotifiable;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\Support\Http\Controllers\CreateStuff;
use FireflyIII\User;
@@ -94,7 +95,8 @@ class RegisterController extends Controller
$this->validator($request->all())->validate();
$user = $this->createUser($request->all());
app('log')->info(sprintf('Registered new user %s', $user->email));
event(new RegisteredUser($user));
$owner = new OwnerNotifiable();
event(new RegisteredUser($owner, $user));
$this->guard()->login($user);

View File

@@ -63,7 +63,7 @@ class BudgetLimitController extends Controller
parent::__construct();
$this->middleware(
function ($request, $next) {
app('view')->share('title', (string)trans('firefly.budgets'));
app('view')->share('title', (string) trans('firefly.budgets'));
app('view')->share('mainTitleIcon', 'fa-pie-chart');
$this->repository = app(BudgetRepositoryInterface::class);
$this->opsRepository = app(OperationsRepositoryInterface::class);
@@ -101,6 +101,26 @@ class BudgetLimitController extends Controller
return view('budgets.budget-limits.create', compact('start', 'end', 'currencies', 'budget'));
}
/**
* @return Factory|View
*/
public function show(BudgetLimit $budgetLimit)
{
$notes = $this->blRepository->getNoteText($budgetLimit);
return view('budgets.budget-limits.show', compact('budgetLimit', 'notes'));
}
/**
* @return Factory|View
*/
public function edit(BudgetLimit $budgetLimit)
{
$notes = $this->blRepository->getNoteText($budgetLimit);
return view('budgets.budget-limits.edit', compact('budgetLimit', 'notes'));
}
/**
* @return Redirector|RedirectResponse
*/
@@ -121,8 +141,8 @@ class BudgetLimitController extends Controller
{
app('log')->debug('Going to store new budget-limit.', $request->all());
// first search for existing one and update it if necessary.
$currency = $this->currencyRepos->find((int)$request->get('transaction_currency_id'));
$budget = $this->repository->find((int)$request->get('budget_id'));
$currency = $this->currencyRepos->find((int) $request->get('transaction_currency_id'));
$budget = $this->repository->find((int) $request->get('budget_id'));
if (null === $currency || null === $budget) {
throw new FireflyException('No valid currency or budget.');
}
@@ -133,7 +153,7 @@ class BudgetLimitController extends Controller
return response()->json([]);
}
$amount = (string)$request->get('amount');
$amount = (string) $request->get('amount');
$start->startOfDay();
$end->startOfDay();
@@ -154,7 +174,7 @@ class BudgetLimitController extends Controller
// return empty=ish array:
return response()->json([]);
}
if ((int)$amount > 268435456) { // intentional cast to integer
if ((int) $amount > 268435456) { // intentional cast to integer
$amount = '268435456';
}
if (-1 === bccomp($amount, '0')) {
@@ -169,13 +189,16 @@ class BudgetLimitController extends Controller
$limit = $this->blRepository->store(
[
'budget_id' => $request->get('budget_id'),
'currency_id' => (int)$request->get('transaction_currency_id'),
'currency_id' => (int) $request->get('transaction_currency_id'),
'start_date' => $start,
'end_date' => $end,
'amount' => $amount,
]
);
}
// parse notes, if any.
$notes = (string) $request->get('notes');
$this->blRepository->setNoteText($limit, $notes);
if ($request->expectsJson()) {
$array = $limit->toArray();
@@ -184,26 +207,29 @@ class BudgetLimitController extends Controller
$array['spent'] = $spentArr[$currency->id]['sum'] ?? '0';
$array['left_formatted'] = app('amount')->formatAnything($limit->transactionCurrency, bcadd($array['spent'], $array['amount']));
$array['amount_formatted'] = app('amount')->formatAnything($limit->transactionCurrency, $limit['amount']);
$array['days_left'] = (string)$this->activeDaysLeft($start, $end);
$array['days_left'] = (string) $this->activeDaysLeft($start, $end);
// left per day:
$array['left_per_day'] = 0 === bccomp('0', $array['days_left']) ? bcadd($array['spent'], $array['amount']) : bcdiv(bcadd($array['spent'], $array['amount']), $array['days_left']);
// left per day formatted.
$array['left_per_day_formatted'] = app('amount')->formatAnything($limit->transactionCurrency, $array['left_per_day']);
// notes:
$array['notes'] = $this->blRepository->getNoteText($limit);
return response()->json($array);
}
return redirect(route('budgets.index'));
}
public function update(Request $request, BudgetLimit $budgetLimit): JsonResponse
public function update(Request $request, BudgetLimit $budgetLimit): JsonResponse|RedirectResponse
{
$amount = (string)$request->get('amount');
$amount = (string) $request->get('amount');
if ('' === $amount) {
$amount = '0';
}
if ((int)$amount > 268435456) { // 268 million, intentional integer
if ((int) $amount > 268435456) { // 268 million, intentional integer
$amount = '268435456';
}
// sanity check on amount:
@@ -224,8 +250,13 @@ class BudgetLimitController extends Controller
if (-1 === bccomp($amount, '0')) {
$amount = bcmul($amount, '-1');
}
$notes = (string)$request->get('notes');
if (strlen($notes) > 32768) {
$notes = substr($notes, 0, 32768);
}
$limit = $this->blRepository->update($budgetLimit, ['amount' => $amount]);
$limit = $this->blRepository->update($budgetLimit, ['amount' => $amount, 'notes' => $notes]);
app('preferences')->mark();
$array = $limit->toArray();
@@ -240,12 +271,15 @@ class BudgetLimitController extends Controller
$array['spent'] = $spentArr[$budgetLimit->transactionCurrency->id]['sum'] ?? '0';
$array['left_formatted'] = app('amount')->formatAnything($limit->transactionCurrency, bcadd($array['spent'], $array['amount']));
$array['amount_formatted'] = app('amount')->formatAnything($limit->transactionCurrency, $limit['amount']);
$array['days_left'] = (string)$daysLeft;
$array['days_left'] = (string) $daysLeft;
$array['left_per_day'] = 0 === $daysLeft ? bcadd($array['spent'], $array['amount']) : bcdiv(bcadd($array['spent'], $array['amount']), $array['days_left']);
// left per day formatted.
$array['amount'] = app('steam')->bcround($limit['amount'], $limit->transactionCurrency->decimal_places);
$array['left_per_day_formatted'] = app('amount')->formatAnything($limit->transactionCurrency, $array['left_per_day']);
if ('true' === $request->get('redirect')) {
return redirect(route('budgets.index'));
}
return response()->json($array);
}

View File

@@ -213,6 +213,7 @@ class IndexController extends Controller
$array['budgeted'][] = [
'id' => $limit->id,
'amount' => $amount,
'notes' => $this->blRepository->getNoteText($limit),
'start_date' => $limit->start_date->isoFormat($this->monthAndDayFormat),
'end_date' => $limit->end_date->isoFormat($this->monthAndDayFormat),
'in_range' => $limit->start_date->isSameDay($start) && $limit->end_date->isSameDay($end),

View File

@@ -75,7 +75,7 @@ class PiggyBankController extends Controller
$locale = app('steam')->getLocale();
// get first event or start date of piggy bank or today
$startDate = $piggyBank->startdate ?? today(config('app.timezone'));
$startDate = $piggyBank->start_date ?? today(config('app.timezone'));
/** @var null|PiggyBankEvent $firstEvent */
$firstEvent = $set->first();

View File

@@ -44,6 +44,9 @@ abstract class Controller extends BaseController
use UserNavigation;
use ValidatesRequests;
// fails on PHP < 8.4
public protected(set) string $name;
protected string $dateTimeFormat;
protected string $monthAndDayFormat;
protected string $monthFormat;

View File

@@ -30,6 +30,7 @@ use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Http\Middleware\IsDemoUser;
use FireflyIII\Models\AccountType;
use FireflyIII\Models\TransactionType;
use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface;
use FireflyIII\Support\Http\Controllers\GetConfigurationData;
use FireflyIII\Support\Models\AccountBalanceCalculator;
use FireflyIII\User;
@@ -280,10 +281,10 @@ class DebugController extends Controller
private function getUserFlags(): string
{
$flags = [];
$flags = [];
/** @var User $user */
$user = auth()->user();
$user = auth()->user();
// has liabilities
if ($user->accounts()->accountTypeIn([AccountType::DEBT, AccountType::LOAN, AccountType::MORTGAGE])->count() > 0) {
@@ -291,12 +292,15 @@ class DebugController extends Controller
}
// has piggies
if ($user->piggyBanks()->count() > 0) {
$repository = app(PiggyBankRepositoryInterface::class);
$repository->setUser($user);
if ($repository->getPiggyBanks()->count() > 0) {
$flags[] = '<span title="Has piggy banks">:pig:</span>';
}
// has stored reconciliations
$type = TransactionType::whereType(TransactionType::RECONCILIATION)->first();
$type = TransactionType::whereType(TransactionType::RECONCILIATION)->first();
if ($user->transactionJournals()->where('transaction_type_id', $type->id)->count() > 0) {
$flags[] = '<span title="Has reconciled">:ledger:</span>';
}

View File

@@ -120,6 +120,7 @@ class HomeController extends Controller
*/
public function index(AccountRepositoryInterface $repository): mixed
{
$types = config('firefly.accountTypesByIdentifier.asset');
$count = $repository->count($types);
Log::channel('audit')->info('User visits homepage.');

View File

@@ -50,15 +50,15 @@ class FrontpageController extends Controller
if (1 === bccomp($amount, '0')) {
// percentage!
$pct = 0;
if (0 !== bccomp($piggyBank->targetamount, '0')) {
$pct = (int)bcmul(bcdiv($amount, $piggyBank->targetamount), '100');
if (0 !== bccomp($piggyBank->target_amount, '0')) {
$pct = (int)bcmul(bcdiv($amount, $piggyBank->target_amount), '100');
}
$entry = [
'id' => $piggyBank->id,
'name' => $piggyBank->name,
'amount' => $amount,
'target' => $piggyBank->targetamount,
'target' => $piggyBank->target_amount,
'percentage' => $pct,
];

View File

@@ -26,12 +26,14 @@ namespace FireflyIII\Http\Controllers\PiggyBank;
use Carbon\Carbon;
use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Models\Account;
use FireflyIII\Models\PiggyBank;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;
/**
@@ -51,7 +53,7 @@ class AmountController extends Controller
$this->middleware(
function ($request, $next) {
app('view')->share('title', (string)trans('firefly.piggyBanks'));
app('view')->share('title', (string) trans('firefly.piggyBanks'));
app('view')->share('mainTitleIcon', 'fa-bullseye');
$this->piggyRepos = app(PiggyBankRepositoryInterface::class);
@@ -69,16 +71,26 @@ class AmountController extends Controller
*/
public function add(PiggyBank $piggyBank)
{
$leftOnAccount = $this->piggyRepos->leftOnAccount($piggyBank, today(config('app.timezone')));
$savedSoFar = $this->piggyRepos->getCurrentAmount($piggyBank);
$maxAmount = $leftOnAccount;
if (0 !== bccomp($piggyBank->targetamount, '0')) {
$leftToSave = bcsub($piggyBank->targetamount, $savedSoFar);
$maxAmount = min($leftOnAccount, $leftToSave);
$accounts = [];
$total = '0';
$totalSaved = $this->piggyRepos->getCurrentAmount($piggyBank);
$leftToSave = bcsub($piggyBank->target_amount, $totalSaved);
foreach ($piggyBank->accounts as $account) {
$leftOnAccount = $this->piggyRepos->leftOnAccount($piggyBank, $account, today(config('app.timezone'))->endOfDay());
$savedSoFar = $this->piggyRepos->getCurrentAmount($piggyBank, $account);
$maxAmount = 0 === bccomp($piggyBank->target_amount, '0') ? $leftToSave : min($leftOnAccount, $leftToSave);
$accounts[] = [
'account' => $account,
'left_on_account' => $leftOnAccount,
'saved_so_far' => $savedSoFar,
'left_to_save' => $leftToSave,
'max_amount' => $maxAmount,
];
$total = bcadd($total, $leftOnAccount);
}
$currency = $this->accountRepos->getAccountCurrency($piggyBank->account) ?? app('amount')->getDefaultCurrency();
$total = (float) $total; // intentional float.
return view('piggy-banks.add', compact('piggyBank', 'maxAmount', 'currency'));
return view('piggy-banks.add', compact('piggyBank', 'accounts', 'total'));
}
/**
@@ -89,18 +101,24 @@ class AmountController extends Controller
public function addMobile(PiggyBank $piggyBank)
{
/** @var Carbon $date */
$date = session('end', today(config('app.timezone')));
$leftOnAccount = $this->piggyRepos->leftOnAccount($piggyBank, $date);
$savedSoFar = $this->piggyRepos->getCurrentAmount($piggyBank);
$maxAmount = $leftOnAccount;
if (0 !== bccomp($piggyBank->targetamount, '0')) {
$leftToSave = bcsub($piggyBank->targetamount, $savedSoFar);
$maxAmount = min($leftOnAccount, $leftToSave);
$date = session('end', today(config('app.timezone')));
$accounts = [];
$total = '0';
foreach ($piggyBank->accounts as $account) {
$leftOnAccount = $this->piggyRepos->leftOnAccount($piggyBank, $account, $date);
$savedSoFar = $this->piggyRepos->getCurrentAmount($piggyBank, $account);
$leftToSave = bcsub($piggyBank->target_amount, $savedSoFar);
$accounts[] = [
'account' => $account,
'left_on_account' => $leftOnAccount,
'saved_so_far' => $savedSoFar,
'left_to_save' => $leftToSave,
'max_amount' => 0 === bccomp($piggyBank->target_amount, '0') ? $leftOnAccount : min($leftOnAccount, $leftToSave),
];
$total = bcadd($total, $leftOnAccount);
}
$currency = $this->accountRepos->getAccountCurrency($piggyBank->account) ?? app('amount')->getDefaultCurrency();
return view('piggy-banks.add-mobile', compact('piggyBank', 'maxAmount', 'currency'));
return view('piggy-banks.add-mobile', compact('piggyBank', 'total', 'accounts'));
}
/**
@@ -108,32 +126,48 @@ class AmountController extends Controller
*/
public function postAdd(Request $request, PiggyBank $piggyBank): RedirectResponse
{
$amount = $request->get('amount') ?? '0';
$currency = $this->accountRepos->getAccountCurrency($piggyBank->account) ?? app('amount')->getDefaultCurrency();
// if amount is negative, make positive and continue:
if (-1 === bccomp($amount, '0')) {
$amount = bcmul($amount, '-1');
$data = $request->all();
$amounts = $data['amount'] ?? [];
$total = '0';
Log::debug('Start with loop.');
/** @var Account $account */
foreach ($piggyBank->accounts as $account) {
$amount = (string) ($amounts[$account->id] ?? '0');
if ('' === $amount || 0 === bccomp($amount, '0')) {
continue;
}
if (-1 === bccomp($amount, '0')) {
$amount = bcmul($amount, '-1');
}
// small check to see if the $amount is not more than the total "left to save" value
$currentAmount = $this->piggyRepos->getCurrentAmount($piggyBank);
$leftToSave = 0 === bccomp($piggyBank->target_amount, '0') ? '0' : bcsub($piggyBank->target_amount, $currentAmount);
if (bccomp($amount, $leftToSave) > 0 && 0 !== bccomp($leftToSave, '0')) {
Log::debug(sprintf('Amount "%s" is more than left to save "%s". Using left to save.', $amount, $leftToSave));
$amount = $leftToSave;
}
$canAddAmount = $this->piggyRepos->canAddAmount($piggyBank, $account, $amount);
if ($canAddAmount) {
$this->piggyRepos->addAmount($piggyBank, $account, $amount);
$total = bcadd($total, $amount);
}
$piggyBank->refresh();
}
if ($this->piggyRepos->canAddAmount($piggyBank, $amount)) {
$this->piggyRepos->addAmount($piggyBank, $amount);
session()->flash(
'success',
(string)trans(
'firefly.added_amount_to_piggy',
['amount' => app('amount')->formatAnything($currency, $amount, false), 'name' => $piggyBank->name]
)
);
if (0 !== bccomp($total, '0')) {
session()->flash('success', (string) trans('firefly.added_amount_to_piggy', ['amount' => app('amount')->formatAnything($piggyBank->transactionCurrency, $total, false), 'name' => $piggyBank->name]));
app('preferences')->mark();
return redirect(route('piggy-banks.index'));
}
app('log')->error('Cannot add '.$amount.' because canAddAmount returned false.');
app('log')->error(sprintf('Cannot add %s because canAddAmount returned false.', $total));
session()->flash(
'error',
(string)trans(
(string) trans(
'firefly.cannot_add_amount_piggy',
['amount' => app('amount')->formatAnything($currency, $amount, false), 'name' => e($piggyBank->name)]
['amount' => app('amount')->formatAnything($piggyBank->transactionCurrency, $total, false), 'name' => e($piggyBank->name)]
)
);
@@ -145,32 +179,44 @@ class AmountController extends Controller
*/
public function postRemove(Request $request, PiggyBank $piggyBank): RedirectResponse
{
$amount = $request->get('amount') ?? '0';
$currency = $this->accountRepos->getAccountCurrency($piggyBank->account) ?? app('amount')->getDefaultCurrency();
// if amount is negative, make positive and continue:
if (-1 === bccomp($amount, '0')) {
$amount = bcmul($amount, '-1');
$amounts = $request->get('amount') ?? [];
if (!is_array($amounts)) {
$amounts = [];
}
if ($this->piggyRepos->canRemoveAmount($piggyBank, $amount)) {
$this->piggyRepos->removeAmount($piggyBank, $amount);
$total = '0';
/** @var Account $account */
foreach ($piggyBank->accounts as $account) {
$amount = (string) ($amounts[$account->id] ?? '0');
if ('' === $amount || 0 === bccomp($amount, '0')) {
continue;
}
if (-1 === bccomp($amount, '0')) {
$amount = bcmul($amount, '-1');
}
if ($this->piggyRepos->canRemoveAmount($piggyBank, $account, $amount)) {
$this->piggyRepos->removeAmount($piggyBank, $account, $amount);
$total = bcadd($total, $amount);
}
}
if (0 !== bccomp($total, '0')) {
session()->flash(
'success',
(string)trans(
(string) trans(
'firefly.removed_amount_from_piggy',
['amount' => app('amount')->formatAnything($currency, $amount, false), 'name' => $piggyBank->name]
['amount' => app('amount')->formatAnything($piggyBank->transactionCurrency, $total, false), 'name' => $piggyBank->name]
)
);
app('preferences')->mark();
return redirect(route('piggy-banks.index'));
}
$amount = (string)$request->get('amount');
session()->flash(
'error',
(string)trans(
(string) trans(
'firefly.cannot_remove_from_piggy',
['amount' => app('amount')->formatAnything($currency, $amount, false), 'name' => e($piggyBank->name)]
['amount' => app('amount')->formatAnything($piggyBank->transactionCurrency, $total, false), 'name' => e($piggyBank->name)]
)
);
@@ -184,10 +230,15 @@ class AmountController extends Controller
*/
public function remove(PiggyBank $piggyBank)
{
$repetition = $this->piggyRepos->getRepetition($piggyBank);
$currency = $this->accountRepos->getAccountCurrency($piggyBank->account) ?? app('amount')->getDefaultCurrency();
$accounts = [];
foreach ($piggyBank->accounts as $account) {
$accounts[] = [
'account' => $account,
'saved_so_far' => $this->piggyRepos->getCurrentAmount($piggyBank, $account),
];
}
return view('piggy-banks.remove', compact('piggyBank', 'repetition', 'currency'));
return view('piggy-banks.remove', compact('piggyBank', 'accounts'));
}
/**
@@ -197,9 +248,14 @@ class AmountController extends Controller
*/
public function removeMobile(PiggyBank $piggyBank)
{
$repetition = $this->piggyRepos->getRepetition($piggyBank);
$currency = $this->accountRepos->getAccountCurrency($piggyBank->account) ?? app('amount')->getDefaultCurrency();
$accounts = [];
foreach ($piggyBank->accounts as $account) {
$accounts[] = [
'account' => $account,
'saved_so_far' => $this->piggyRepos->getCurrentAmount($piggyBank, $account),
];
}
return view('piggy-banks.remove-mobile', compact('piggyBank', 'repetition', 'currency'));
return view('piggy-banks.remove-mobile', compact('piggyBank', 'accounts'));
}
}

View File

@@ -31,6 +31,7 @@ use FireflyIII\Http\Requests\PiggyBankStoreRequest;
use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;
@@ -52,7 +53,7 @@ class CreateController extends Controller
$this->middleware(
function ($request, $next) {
app('view')->share('title', (string)trans('firefly.piggyBanks'));
app('view')->share('title', (string) trans('firefly.piggyBanks'));
app('view')->share('mainTitleIcon', 'fa-bullseye');
$this->attachments = app(AttachmentHelperInterface::class);
@@ -68,10 +69,12 @@ class CreateController extends Controller
*
* @return Factory|View
*/
public function create()
public function create(Request $request)
{
$subTitle = (string)trans('firefly.new_piggy_bank');
$subTitle = (string) trans('firefly.new_piggy_bank');
$subTitleIcon = 'fa-plus';
$hasOldInput = null !== $request->old('_token');
$preFilled = $request->old();
// put previous url in session if not redirect from store (not "create another").
if (true !== session('piggy-banks.create.fromStore')) {
@@ -79,7 +82,7 @@ class CreateController extends Controller
}
session()->forget('piggy-banks.create.fromStore');
return view('piggy-banks.create', compact('subTitle', 'subTitleIcon'));
return view('piggy-banks.create', compact('subTitle', 'subTitleIcon', 'preFilled'));
}
/**
@@ -92,12 +95,14 @@ class CreateController extends Controller
public function store(PiggyBankStoreRequest $request)
{
$data = $request->getPiggyBankData();
if (null === $data['startdate']) {
$data['startdate'] = today(config('app.timezone'));
if (null === $data['start_date']) {
$data['start_date'] = today(config('app.timezone'));
}
$piggyBank = $this->piggyRepos->store($data);
session()->flash('success', (string)trans('firefly.stored_piggy_bank', ['name' => $piggyBank->name]));
session()->flash('success', (string) trans('firefly.stored_piggy_bank', ['name' => $piggyBank->name]));
session()->flash('success_url', route('piggy-banks.show', [$piggyBank->id]));
app('preferences')->mark();
// store attachment(s):
@@ -108,7 +113,7 @@ class CreateController extends Controller
}
if (null !== $files && auth()->user()->hasRole('demo')) {
Log::channel('audit')->warning(sprintf('The demo user is trying to upload attachments in %s.', __METHOD__));
session()->flash('info', (string)trans('firefly.no_att_demo_user'));
session()->flash('info', (string) trans('firefly.no_att_demo_user'));
}
if (count($this->attachments->getMessages()->get('attachments')) > 0) {
@@ -116,7 +121,7 @@ class CreateController extends Controller
}
$redirect = redirect($this->getPreviousUrl('piggy-banks.create.url'));
if (1 === (int)$request->get('create_another')) {
if (1 === (int) $request->get('create_another')) {
session()->put('piggy-banks.create.fromStore', true);
$redirect = redirect(route('piggy-banks.create'))->withInput();

View File

@@ -77,24 +77,23 @@ class EditController extends Controller
$subTitleIcon = 'fa-pencil';
$note = $piggyBank->notes()->first();
// Flash some data to fill the form.
$targetDate = $piggyBank->targetdate?->format('Y-m-d');
$startDate = $piggyBank->startdate?->format('Y-m-d');
$currency = $this->accountRepository->getAccountCurrency($piggyBank->account);
if (null === $currency) {
$currency = app('amount')->getDefaultCurrency();
}
$targetDate = $piggyBank->target_date?->format('Y-m-d');
$startDate = $piggyBank->start_date?->format('Y-m-d');
$preFilled = [
'name' => $piggyBank->name,
'account_id' => $piggyBank->account_id,
'targetamount' => app('steam')->bcround($piggyBank->targetamount, $currency->decimal_places),
'targetdate' => $targetDate,
'startdate' => $startDate,
'object_group' => null !== $piggyBank->objectGroups->first() ? $piggyBank->objectGroups->first()->title : '',
'notes' => null === $note ? '' : $note->text,
'name' => $piggyBank->name,
'target_amount' => app('steam')->bcround($piggyBank->target_amount, $piggyBank->transactionCurrency->decimal_places),
'target_date' => $targetDate,
'start_date' => $startDate,
'accounts' => [],
'object_group' => null !== $piggyBank->objectGroups->first() ? $piggyBank->objectGroups->first()->title : '',
'notes' => null === $note ? '' : $note->text,
];
if (0 === bccomp($piggyBank->targetamount, '0')) {
$preFilled['targetamount'] = '';
foreach ($piggyBank->accounts as $account) {
$preFilled['accounts'][] = $account->id;
}
if (0 === bccomp($piggyBank->target_amount, '0')) {
$preFilled['target_amount'] = '';
}
session()->flash('preFilled', $preFilled);

View File

@@ -27,6 +27,7 @@ namespace FireflyIII\Http\Controllers\PiggyBank;
use Carbon\Carbon;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Models\Account;
use FireflyIII\Models\PiggyBank;
use FireflyIII\Repositories\ObjectGroup\OrganisesObjectGroups;
use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface;
@@ -35,6 +36,7 @@ use FireflyIII\Transformers\PiggyBankTransformer;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\View\View;
use Symfony\Component\HttpFoundation\ParameterBag;
@@ -56,7 +58,7 @@ class IndexController extends Controller
$this->middleware(
function ($request, $next) {
app('view')->share('title', (string)trans('firefly.piggyBanks'));
app('view')->share('title', (string) trans('firefly.piggyBanks'));
app('view')->share('mainTitleIcon', 'fa-bullseye');
$this->piggyRepos = app(PiggyBankRepositoryInterface::class);
@@ -80,7 +82,6 @@ class IndexController extends Controller
$this->cleanupObjectGroups();
$this->piggyRepos->resetOrder();
$collection = $this->piggyRepos->getPiggyBanks();
$accounts = [];
/** @var Carbon $end */
$end = session('end', today(config('app.timezone'))->endOfMonth());
@@ -89,51 +90,15 @@ class IndexController extends Controller
$parameters = new ParameterBag();
$parameters->set('end', $end);
// make piggy bank groups:
$piggyBanks = [];
/** @var PiggyBankTransformer $transformer */
$transformer = app(PiggyBankTransformer::class);
$transformer->setParameters(new ParameterBag());
/** @var AccountTransformer $accountTransformer */
$accountTransformer = app(AccountTransformer::class);
$accountTransformer->setParameters($parameters);
/** @var PiggyBank $piggy */
foreach ($collection as $piggy) {
$array = $transformer->transform($piggy);
$groupOrder = (int)$array['object_group_order'];
// make group array if necessary:
$piggyBanks[$groupOrder] ??= [
'object_group_id' => $array['object_group_id'] ?? 0,
'object_group_title' => $array['object_group_title'] ?? trans('firefly.default_group_title_name'),
'piggy_banks' => [],
];
$account = $accountTransformer->transform($piggy->account);
$accountId = (int)$account['id'];
$array['attachments'] = $this->piggyRepos->getAttachments($piggy);
if (!array_key_exists($accountId, $accounts)) {
// create new:
$accounts[$accountId] = $account;
// add some interesting details:
$accounts[$accountId]['left'] = $accounts[$accountId]['current_balance'];
$accounts[$accountId]['saved'] = 0;
$accounts[$accountId]['target'] = 0;
$accounts[$accountId]['to_save'] = 0;
}
// calculate new interesting fields:
$accounts[$accountId]['left'] -= $array['current_amount'];
$accounts[$accountId]['saved'] += $array['current_amount'];
$accounts[$accountId]['target'] += $array['target_amount'];
$accounts[$accountId]['to_save'] += ($array['target_amount'] - $array['current_amount']);
$array['account_name'] = $account['name'];
$piggyBanks[$groupOrder]['piggy_banks'][] = $array;
}
// do a bunch of summaries.
// data
$piggyBanks = $this->groupPiggyBanks($collection);
$accounts = $this->collectAccounts($collection);
$accounts = $this->mergeAccountsAndPiggies($piggyBanks, $accounts);
$piggyBanks = $this->makeSums($piggyBanks);
ksort($piggyBanks);
@@ -162,10 +127,10 @@ class IndexController extends Controller
// current_amount
// left_to_save
// save_per_month
$sums[$groupId][$currencyId]['target'] = bcadd($sums[$groupId][$currencyId]['target'], (string)$piggy['target_amount']);
$sums[$groupId][$currencyId]['saved'] = bcadd($sums[$groupId][$currencyId]['saved'], (string)$piggy['current_amount']);
$sums[$groupId][$currencyId]['left_to_save'] = bcadd($sums[$groupId][$currencyId]['left_to_save'], (string)$piggy['left_to_save']);
$sums[$groupId][$currencyId]['save_per_month'] = bcadd($sums[$groupId][$currencyId]['save_per_month'], (string)$piggy['save_per_month']);
$sums[$groupId][$currencyId]['target'] = bcadd($sums[$groupId][$currencyId]['target'], (string) $piggy['target_amount']);
$sums[$groupId][$currencyId]['saved'] = bcadd($sums[$groupId][$currencyId]['saved'], (string) $piggy['current_amount']);
$sums[$groupId][$currencyId]['left_to_save'] = bcadd($sums[$groupId][$currencyId]['left_to_save'], (string) $piggy['left_to_save']);
$sums[$groupId][$currencyId]['save_per_month'] = bcadd($sums[$groupId][$currencyId]['save_per_month'], (string) $piggy['save_per_month']);
}
}
foreach ($piggyBanks as $groupOrder => $group) {
@@ -181,8 +146,8 @@ class IndexController extends Controller
*/
public function setOrder(Request $request, PiggyBank $piggyBank): JsonResponse
{
$objectGroupTitle = (string)$request->get('objectGroupTitle');
$newOrder = (int)$request->get('order');
$objectGroupTitle = (string) $request->get('objectGroupTitle');
$newOrder = (int) $request->get('order');
$this->piggyRepos->setOrder($piggyBank, $newOrder);
if ('' !== $objectGroupTitle) {
$this->piggyRepos->setObjectGroup($piggyBank, $objectGroupTitle);
@@ -193,4 +158,97 @@ class IndexController extends Controller
return response()->json(['data' => 'OK']);
}
private function groupPiggyBanks(Collection $collection): array
{
/** @var PiggyBankTransformer $transformer */
$transformer = app(PiggyBankTransformer::class);
$transformer->setParameters(new ParameterBag());
$piggyBanks = [];
/** @var PiggyBank $piggy */
foreach ($collection as $piggy) {
$array = $transformer->transform($piggy);
$groupOrder = (int) $array['object_group_order'];
$piggyBanks[$groupOrder] ??= [
'object_group_id' => $array['object_group_id'] ?? 0,
'object_group_title' => $array['object_group_title'] ?? trans('firefly.default_group_title_name'),
'piggy_banks' => [],
];
$array['attachments'] = $this->piggyRepos->getAttachments($piggy);
// sum the total amount for the index.
$piggyBanks[$groupOrder]['piggy_banks'][] = $array;
}
return $piggyBanks;
}
private function collectAccounts(Collection $collection): array
{
/** @var Carbon $end */
$end = session('end', today(config('app.timezone'))->endOfMonth());
// transform piggies using the transformer:
$parameters = new ParameterBag();
$parameters->set('end', $end);
/** @var AccountTransformer $accountTransformer */
$accountTransformer = app(AccountTransformer::class);
$accountTransformer->setParameters($parameters);
$return = [];
/** @var PiggyBank $piggy */
foreach ($collection as $piggy) {
$accounts = $piggy->accounts;
/** @var Account $account */
foreach ($accounts as $account) {
$array = $accountTransformer->transform($account);
$accountId = (int) $array['id'];
if (!array_key_exists($accountId, $return)) {
$return[$accountId] = $array;
// add some interesting details:
$return[$accountId]['left'] = $return[$accountId]['current_balance'];
$return[$accountId]['saved'] = '0';
$return[$accountId]['target'] = '0';
$return[$accountId]['to_save'] = '0';
}
// calculate new interesting fields:
// $return[$accountId]['left'] -= $array['current_amount'];
// $return[$accountId]['saved'] += $array['current_amount'];
// $return[$accountId]['target'] += $array['target_amount'];
// $return[$accountId]['to_save'] += ($array['target_amount'] - $array['current_amount']);
// $return['account_name'] = $account['name'];
}
}
return $return;
}
private function mergeAccountsAndPiggies(array $piggyBanks, array $accounts): array
{
// @var array $piggyBank
foreach ($piggyBanks as $group) {
foreach ($group['piggy_banks'] as $piggyBank) {
// loop all accounts in this piggy bank subtract the current amount from "left to save" in the $accounts array.
/** @var array $piggyAccount */
foreach ($piggyBank['accounts'] as $piggyAccount) {
$accountId = $piggyAccount['id'];
if (array_key_exists($accountId, $accounts)) {
$accounts[$accountId]['left'] = bcsub($accounts[$accountId]['left'], $piggyAccount['current_amount']);
$accounts[$accountId]['saved'] = bcadd($accounts[$accountId]['saved'], $piggyAccount['current_amount']);
$accounts[$accountId]['target'] = bcadd($accounts[$accountId]['target'], $piggyBank['target_amount']);
$accounts[$accountId]['to_save'] = bcadd($accounts[$accountId]['to_save'], bcsub($piggyBank['target_amount'], $piggyAccount['current_amount']));
}
}
}
}
return $accounts;
}
}

View File

@@ -83,6 +83,7 @@ class ShowController extends Controller
$subTitle = $piggyBank->name;
$attachments = $this->piggyRepos->getAttachments($piggyBank);
return view('piggy-banks.show', compact('piggyBank', 'events', 'subTitle', 'piggy', 'attachments'));
}
}

View File

@@ -23,12 +23,14 @@ declare(strict_types=1);
namespace FireflyIII\Http\Controllers;
use FireflyIII\Events\Test\UserTestNotificationChannel;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Http\Requests\PreferencesRequest;
use FireflyIII\Models\Account;
use FireflyIII\Models\AccountType;
use FireflyIII\Models\Preference;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Support\Notifications\UrlValidator;
use FireflyIII\User;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
@@ -49,7 +51,7 @@ class PreferencesController extends Controller
$this->middleware(
static function ($request, $next) {
app('view')->share('title', (string)trans('firefly.preferences'));
app('view')->share('title', (string) trans('firefly.preferences'));
app('view')->share('mainTitleIcon', 'fa-gear');
return $next($request);
@@ -66,14 +68,14 @@ class PreferencesController extends Controller
*/
public function index(AccountRepositoryInterface $repository)
{
$accounts = $repository->getAccountsByType([AccountType::DEFAULT, AccountType::ASSET, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE]);
$isDocker = env('IS_DOCKER', false);
$groupedAccounts = [];
$accounts = $repository->getAccountsByType([AccountType::DEFAULT, AccountType::ASSET, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE]);
$isDocker = env('IS_DOCKER', false);
$groupedAccounts = [];
/** @var Account $account */
foreach ($accounts as $account) {
$type = $account->accountType->type;
$role = sprintf('opt_group_%s', $repository->getMetaValue($account, 'account_role'));
$type = $account->accountType->type;
$role = sprintf('opt_group_%s', $repository->getMetaValue($account, 'account_role'));
if (in_array($type, [AccountType::MORTGAGE, AccountType::DEBT, AccountType::LOAN], true)) {
$role = sprintf('opt_group_l_%s', $type);
@@ -82,64 +84,119 @@ class PreferencesController extends Controller
if ('opt_group_' === $role) {
$role = 'opt_group_defaultAsset';
}
$groupedAccounts[(string)trans(sprintf('firefly.%s', $role))][$account->id] = $account->name;
$groupedAccounts[(string) trans(sprintf('firefly.%s', $role))][$account->id] = $account->name;
}
ksort($groupedAccounts);
/** @var array<int, int> $accountIds */
$accountIds = $accounts->pluck('id')->toArray();
$viewRange = app('navigation')->getViewRange(false);
$frontpageAccountsPref = app('preferences')->get('frontpageAccounts', $accountIds);
$frontpageAccounts = $frontpageAccountsPref->data;
$accountIds = $accounts->pluck('id')->toArray();
$viewRange = app('navigation')->getViewRange(false);
$frontpageAccountsPref = app('preferences')->get('frontpageAccounts', $accountIds);
$frontpageAccounts = $frontpageAccountsPref->data;
if (!is_array($frontpageAccounts)) {
$frontpageAccounts = $accountIds;
}
$language = app('steam')->getLanguage();
$languages = config('firefly.languages');
$locale = app('preferences')->get('locale', config('firefly.default_locale', 'equal'))->data;
$listPageSize = app('preferences')->get('listPageSize', 50)->data;
$darkMode = app('preferences')->get('darkMode', 'browser')->data;
$slackUrl = app('preferences')->get('slack_webhook_url', '')->data;
$customFiscalYear = app('preferences')->get('customFiscalYear', 0)->data;
$fiscalYearStartStr = app('preferences')->get('fiscalYearStart', '01-01')->data;
$language = app('steam')->getLanguage();
$languages = config('firefly.languages');
$locale = app('preferences')->get('locale', config('firefly.default_locale', 'equal'))->data;
$listPageSize = app('preferences')->get('listPageSize', 50)->data;
$darkMode = app('preferences')->get('darkMode', 'browser')->data;
$customFiscalYear = app('preferences')->get('customFiscalYear', 0)->data;
$fiscalYearStartStr = app('preferences')->get('fiscalYearStart', '01-01')->data;
if (is_array($fiscalYearStartStr)) {
$fiscalYearStartStr = '01-01';
}
$fiscalYearStart = sprintf('%s-%s', date('Y'), (string)$fiscalYearStartStr);
$tjOptionalFields = app('preferences')->get('transaction_journal_optional_fields', [])->data;
$availableDarkModes = config('firefly.available_dark_modes');
$fiscalYearStart = sprintf('%s-%s', date('Y'), (string) $fiscalYearStartStr);
$tjOptionalFields = app('preferences')->get('transaction_journal_optional_fields', [])->data;
$availableDarkModes = config('firefly.available_dark_modes');
// notification preferences (single value for each):
$notifications = [];
foreach (config('firefly.available_notifications') as $notification) {
$notifications[$notification] = app('preferences')->get(sprintf('notification_%s', $notification), true)->data;
// notifications settings
$slackUrl = app('preferences')->getEncrypted('slack_webhook_url', '')->data;
$pushoverAppToken = (string) app('preferences')->getEncrypted('pushover_app_token', '')->data;
$pushoverUserToken = (string) app('preferences')->getEncrypted('pushover_user_token', '')->data;
$ntfyServer = app('preferences')->getEncrypted('ntfy_server', 'https://ntfy.sh')->data;
$ntfyTopic = (string) app('preferences')->getEncrypted('ntfy_topic', '')->data;
$ntfyAuth = app('preferences')->get('ntfy_auth', false)->data;
$ntfyUser = app('preferences')->getEncrypted('ntfy_user', '')->data;
$ntfyPass = (string) app('preferences')->getEncrypted('ntfy_pass', '')->data;
$channels = config('notifications.channels');
$forcedAvailability = [];
// notification preferences
$notifications = [];
foreach (config('notifications.notifications.user') as $key => $info) {
if ($info['enabled']) {
$notifications[$key]
= [
'enabled' => app('preferences')->get(sprintf('notification_%s', $key), true)->data,
'configurable' => $info['configurable'],
];
}
}
// loop all channels to see if they are available.
foreach ($channels as $channel => $info) {
$forcedAvailability[$channel] = true;
}
$forcedAvailability['ntfy'] = '' !== $ntfyTopic;
$forcedAvailability['pushover'] = '' !== $pushoverAppToken && '' !== $pushoverUserToken;
ksort($languages);
// list of locales also has "equal" which makes it equal to whatever the language is.
try {
$locales = json_decode((string)file_get_contents(resource_path(sprintf('locales/%s/locales.json', $language))), true, 512, JSON_THROW_ON_ERROR);
$locales = json_decode((string) file_get_contents(resource_path(sprintf('locales/%s/locales.json', $language))), true, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
app('log')->error($e->getMessage());
$locales = [];
}
$locales = ['equal' => (string)trans('firefly.equal_to_language')] + $locales;
$locales = ['equal' => (string) trans('firefly.equal_to_language')] + $locales;
// an important fallback is that the frontPageAccount array gets refilled automatically
// when it turns up empty.
if (0 === count($frontpageAccounts)) {
$frontpageAccounts = $accountIds;
}
// for the demo user, the slackUrl is automatically emptied.
// this isn't really secure, but it means that the demo site has a semi-secret
// slackUrl.
// for the demo user, the notification settings are automatically emptied.
// this isn't really secure, but it means that the demo site has semi-secret notification settings.
if (auth()->user()->hasRole('demo')) {
$slackUrl = '';
$slackUrl = '';
$pushoverAppToken = '';
$pushoverUserToken = '';
$ntfyServer = '';
$ntfyTopic = '';
$ntfyAuth = false;
$ntfyUser = '';
$ntfyPass = '';
}
return view('preferences.index', compact('language', 'groupedAccounts', 'isDocker', 'frontpageAccounts', 'languages', 'darkMode', 'availableDarkModes', 'notifications', 'slackUrl', 'locales', 'locale', 'tjOptionalFields', 'viewRange', 'customFiscalYear', 'listPageSize', 'fiscalYearStart'));
return view('preferences.index', compact(
'language',
'pushoverAppToken',
'pushoverUserToken',
'ntfyServer',
'ntfyTopic',
'ntfyAuth',
'channels',
'ntfyUser',
'forcedAvailability',
'ntfyPass',
'groupedAccounts',
'isDocker',
'frontpageAccounts',
'languages',
'darkMode',
'availableDarkModes',
'notifications',
'slackUrl',
'locales',
'locale',
'tjOptionalFields',
'viewRange',
'customFiscalYear',
'listPageSize',
'fiscalYearStart'
));
}
/**
@@ -152,21 +209,21 @@ class PreferencesController extends Controller
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function postIndex(Request $request)
public function postIndex(PreferencesRequest $request)
{
// front page accounts
$frontpageAccounts = [];
if (is_array($request->get('frontpageAccounts')) && count($request->get('frontpageAccounts')) > 0) {
foreach ($request->get('frontpageAccounts') as $id) {
$frontpageAccounts[] = (int)$id;
$frontpageAccounts[] = (int) $id;
}
app('preferences')->set('frontpageAccounts', $frontpageAccounts);
}
// extract notifications:
$all = $request->all();
foreach (config('firefly.available_notifications') as $option) {
$key = sprintf('notification_%s', $option);
foreach (config('notifications.notifications.user') as $key => $info) {
$key = sprintf('notification_%s', $key);
if (array_key_exists($key, $all)) {
app('preferences')->set($key, true);
}
@@ -182,20 +239,24 @@ class PreferencesController extends Controller
session()->forget('end');
session()->forget('range');
// slack URL:
// notification settings, cannot be set by the demo user.
if (!auth()->user()->hasRole('demo')) {
$url = (string)$request->get('slackUrl');
if (UrlValidator::isValidWebhookURL($url)) {
app('preferences')->set('slack_webhook_url', $url);
}
if ('' === $url) {
app('preferences')->delete('slack_webhook_url');
$variables = ['slack_webhook_url', 'pushover_app_token', 'pushover_user_token', 'ntfy_server', 'ntfy_topic', 'ntfy_user', 'ntfy_pass'];
foreach ($variables as $variable) {
if ('' === $all[$variable]) {
app('preferences')->delete($variable);
}
if ('' !== $all[$variable]) {
app('preferences')->setEncrypted($variable, $all[$variable]);
}
}
app('preferences')->set('ntfy_auth', $all['ntfy_auth'] ?? false);
}
// custom fiscal year
$customFiscalYear = 1 === (int)$request->get('customFiscalYear');
$string = strtotime((string)$request->get('fiscalYearStart'));
$customFiscalYear = 1 === (int) $request->get('customFiscalYear');
$string = strtotime((string) $request->get('fiscalYearStart'));
if (false !== $string) {
$fiscalYearStart = date('m-d', $string);
app('preferences')->set('customFiscalYear', $customFiscalYear);
@@ -204,7 +265,7 @@ class PreferencesController extends Controller
// save page size:
app('preferences')->set('listPageSize', 50);
$listPageSize = (int)$request->get('listPageSize');
$listPageSize = (int) $request->get('listPageSize');
if ($listPageSize > 0 && $listPageSize < 1337) {
app('preferences')->set('listPageSize', $listPageSize);
}
@@ -252,9 +313,35 @@ class PreferencesController extends Controller
app('preferences')->set('darkMode', $darkMode);
}
session()->flash('success', (string)trans('firefly.saved_preferences'));
session()->flash('success', (string) trans('firefly.saved_preferences'));
app('preferences')->mark();
return redirect(route('preferences.index'));
}
public function testNotification(Request $request): mixed
{
$all = $request->all();
$channel = $all['channel'] ?? '';
switch ($channel) {
default:
session()->flash('error', (string) trans('firefly.notification_test_failed', ['channel' => $channel]));
break;
case 'email':
case 'slack':
case 'pushover':
case 'ntfy':
/** @var User $user */
$user = auth()->user();
app('log')->debug(sprintf('Now in testNotification("%s") controller.', $channel));
event(new UserTestNotificationChannel($channel, $user));
session()->flash('success', (string) trans('firefly.notification_test_executed', ['channel' => $channel]));
}
return '';
}
}

View File

@@ -70,10 +70,8 @@ class IndexController extends Controller
$page = 0 === (int)$request->get('page') ? 1 : (int)$request->get('page');
$pageSize = (int)app('preferences')->get('listPageSize', 50)->data;
$collection = $this->repository->getAll();
$total = $collection->count();
$collection = $collection->slice(($page - 1) * $pageSize, $pageSize);
// order so default is on top:
// order so default and enabled are on top:
$collection = $collection->sortBy(
static function (TransactionCurrency $currency) {
$default = true === $currency->userGroupDefault ? 0 : 1;
@@ -82,6 +80,8 @@ class IndexController extends Controller
return sprintf('%s-%s-%s', $default, $enabled, $currency->code);
}
);
$total = $collection->count();
$collection = $collection->slice(($page - 1) * $pageSize, $pageSize);
$currencies = new LengthAwarePaginator($collection, $total, $pageSize, $page);
$currencies->setPath(route('currencies.index'));

View File

@@ -0,0 +1,78 @@
<?php
/*
* NotificationRequest.php
* Copyright (c) 2024 james@firefly-iii.org.
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*/
declare(strict_types=1);
namespace FireflyIII\Http\Requests;
use FireflyIII\Rules\Admin\IsValidSlackOrDiscordUrl;
use FireflyIII\Support\Request\ChecksLogin;
use FireflyIII\Support\Request\ConvertsDataTypes;
use Illuminate\Foundation\Http\FormRequest;
class NotificationRequest extends FormRequest
{
use ChecksLogin;
use ConvertsDataTypes;
public function getAll(): array
{
$return = [];
foreach (config('notifications.notifications.owner') as $key => $info) {
$value = false;
if ($this->has(sprintf('notification_%s', $key))) {
$value = true;
}
$return[$key] = $value;
}
$return['slack_webhook_url'] = $this->convertString('slack_webhook_url');
$return['pushover_app_token'] = $this->convertString('pushover_app_token');
$return['pushover_user_token'] = $this->convertString('pushover_user_token');
$return['ntfy_server'] = $this->convertString('ntfy_server');
$return['ntfy_topic'] = $this->convertString('ntfy_topic');
$return['ntfy_auth'] = $this->convertBoolean($this->get('ntfy_auth'));
$return['ntfy_user'] = $this->convertString('ntfy_user');
$return['ntfy_pass'] = $this->convertString('ntfy_pass');
return $return;
}
/**
* Rules for this request.
*/
public function rules(): array
{
$rules = [
'slack_webhook_url' => ['nullable', 'url', 'min:1', new IsValidSlackOrDiscordUrl()],
'ntfy_server' => ['nullable', 'url', 'min:1'],
'ntfy_user' => ['required_with:ntfy_pass,ntfy_auth', 'nullable', 'string', 'min:1'],
'ntfy_pass' => ['required_with:ntfy_user,ntfy_auth', 'nullable', 'string', 'min:1'],
];
foreach (config('notifications.notifications.owner') as $key => $info) {
$rules[sprintf('notification_%s', $key)] = 'in:0,1';
}
return $rules;
}
}

View File

@@ -23,6 +23,8 @@ declare(strict_types=1);
namespace FireflyIII\Http\Requests;
use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Rules\IsValidPositiveAmount;
use FireflyIII\Support\Request\ChecksLogin;
use FireflyIII\Support\Request\ConvertsDataTypes;
@@ -43,15 +45,24 @@ class PiggyBankStoreRequest extends FormRequest
*/
public function getPiggyBankData(): array
{
return [
'name' => $this->convertString('name'),
'startdate' => $this->getCarbonDate('startdate'),
'account_id' => $this->convertInteger('account_id'),
'targetamount' => $this->convertString('targetamount'),
'targetdate' => $this->getCarbonDate('targetdate'),
'notes' => $this->stringWithNewlines('notes'),
'object_group_title' => $this->convertString('object_group'),
$accounts = $this->get('accounts');
$data = [
'name' => $this->convertString('name'),
'start_date' => $this->getCarbonDate('start_date'),
'target_amount' => $this->convertString('target_amount'),
'transaction_currency_id' => $this->convertInteger('transaction_currency_id'),
'target_date' => $this->getCarbonDate('target_date'),
'notes' => $this->stringWithNewlines('notes'),
'object_group_title' => $this->convertString('object_group'),
];
if (!is_array($accounts)) {
$accounts = [];
}
foreach ($accounts as $item) {
$data['accounts'][] = ['account_id' => (int) $item];
}
return $data;
}
/**
@@ -60,21 +71,63 @@ class PiggyBankStoreRequest extends FormRequest
public function rules(): array
{
return [
'name' => 'required|min:1|max:255|uniquePiggyBankForUser',
'account_id' => 'required|belongsToUser:accounts',
'targetamount' => ['nullable', new IsValidPositiveAmount()],
'startdate' => 'date',
'targetdate' => 'date|nullable',
'order' => 'integer|min:1',
'object_group' => 'min:0|max:255',
'notes' => 'min:1|max:32768|nullable',
'name' => 'required|min:1|max:255|uniquePiggyBankForUser',
'accounts' => 'required|array',
'accounts.*' => 'required|belongsToUser:accounts',
'target_amount' => ['nullable', new IsValidPositiveAmount()],
'start_date' => 'date',
'target_date' => 'date|nullable',
'order' => 'integer|min:1',
'object_group' => 'min:0|max:255',
'notes' => 'min:1|max:32768|nullable',
];
}
public function withValidator(Validator $validator): void
{
// need to have more than one account.
// accounts need to have the same currency or be multi-currency(?).
$validator->after(
function (Validator $validator): void {
// validate start before end only if both are there.
$data = $validator->getData();
$currency = $this->getCurrencyFromData($data);
if (array_key_exists('accounts', $data) && is_array($data['accounts'])) {
$repository = app(AccountRepositoryInterface::class);
$types = config('firefly.piggy_bank_account_types');
foreach ($data['accounts'] as $value) {
$accountId = (int) $value;
$account = $repository->find($accountId);
if (null !== $account) {
// check currency here.
$accountCurrency = $repository->getAccountCurrency($account);
$isMultiCurrency = $repository->getMetaValue($account, 'is_multi_currency');
if ($accountCurrency->id !== $currency->id && 'true' !== $isMultiCurrency) {
$validator->errors()->add('accounts', trans('validation.invalid_account_currency'));
}
$type = $account->accountType->type;
if (!in_array($type, $types, true)) {
$validator->errors()->add('accounts', trans('validation.invalid_account_type'));
}
}
}
}
}
);
if ($validator->fails()) {
Log::channel('audit')->error(sprintf('Validation errors in %s', __CLASS__), $validator->errors()->toArray());
}
}
private function getCurrencyFromData(array $data): TransactionCurrency
{
$currencyId = (int) ($data['transaction_currency_id'] ?? 0);
$currency = TransactionCurrency::find($currencyId);
if (null === $currency) {
return app('amount')->getDefaultCurrency();
}
return $currency;
}
}

View File

@@ -24,6 +24,8 @@ declare(strict_types=1);
namespace FireflyIII\Http\Requests;
use FireflyIII\Models\PiggyBank;
use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Rules\IsValidPositiveAmount;
use FireflyIII\Support\Request\ChecksLogin;
use FireflyIII\Support\Request\ConvertsDataTypes;
@@ -44,15 +46,23 @@ class PiggyBankUpdateRequest extends FormRequest
*/
public function getPiggyBankData(): array
{
return [
$accounts = $this->get('accounts');
$data = [
'name' => $this->convertString('name'),
'startdate' => $this->getCarbonDate('startdate'),
'account_id' => $this->convertInteger('account_id'),
'targetamount' => trim($this->convertString('targetamount')),
'targetdate' => $this->getCarbonDate('targetdate'),
'start_date' => $this->getCarbonDate('start_date'),
'target_amount' => trim($this->convertString('target_amount')),
'target_date' => $this->getCarbonDate('target_date'),
'notes' => $this->stringWithNewlines('notes'),
'object_group_title' => $this->convertString('object_group'),
];
if (!is_array($accounts)) {
$accounts = [];
}
foreach ($accounts as $item) {
$data['accounts'][] = ['account_id' => (int) $item];
}
return $data;
}
/**
@@ -64,21 +74,63 @@ class PiggyBankUpdateRequest extends FormRequest
$piggy = $this->route()->parameter('piggyBank');
return [
'name' => sprintf('required|min:1|max:255|uniquePiggyBankForUser:%d', $piggy->id),
'account_id' => 'required|belongsToUser:accounts',
'targetamount' => ['nullable', new IsValidPositiveAmount()],
'startdate' => 'date',
'targetdate' => 'date|nullable',
'order' => 'integer|max:32768|min:1',
'object_group' => 'min:0|max:255',
'notes' => 'min:1|max:32768|nullable',
'name' => sprintf('required|min:1|max:255|uniquePiggyBankForUser:%d', $piggy->id),
'accounts' => 'required|array',
'accounts.*' => 'required|belongsToUser:accounts',
'target_amount' => ['nullable', new IsValidPositiveAmount()],
'start_date' => 'date',
'target_date' => 'date|nullable',
'order' => 'integer|max:32768|min:1',
'object_group' => 'min:0|max:255',
'notes' => 'min:1|max:32768|nullable',
];
}
public function withValidator(Validator $validator): void
{
{ // need to have more than one account.
// accounts need to have the same currency or be multi-currency(?).
$validator->after(
function (Validator $validator): void {
// validate start before end only if both are there.
$data = $validator->getData();
$currency = $this->getCurrencyFromData($data);
if (array_key_exists('accounts', $data) && is_array($data['accounts'])) {
$repository = app(AccountRepositoryInterface::class);
$types = config('firefly.piggy_bank_account_types');
foreach ($data['accounts'] as $value) {
$accountId = (int) $value;
$account = $repository->find($accountId);
if (null !== $account) {
// check currency here.
$accountCurrency = $repository->getAccountCurrency($account);
$isMultiCurrency = $repository->getMetaValue($account, 'is_multi_currency');
if ($accountCurrency->id !== $currency->id && 'true' !== $isMultiCurrency) {
$validator->errors()->add('accounts', trans('validation.invalid_account_currency'));
}
$type = $account->accountType->type;
if (!in_array($type, $types, true)) {
$validator->errors()->add('accounts', trans('validation.invalid_account_type'));
}
}
}
}
}
);
if ($validator->fails()) {
Log::channel('audit')->error(sprintf('Validation errors in %s', __CLASS__), $validator->errors()->toArray());
}
}
private function getCurrencyFromData(array $data): TransactionCurrency
{
$currencyId = (int) ($data['transaction_currency_id'] ?? 0);
$currency = TransactionCurrency::find($currencyId);
if (null === $currency) {
return app('amount')->getDefaultCurrency();
}
return $currency;
}
}

View File

@@ -0,0 +1,52 @@
<?php
/*
* PreferencesRequest.php
* Copyright (c) 2024 james@firefly-iii.org.
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*/
declare(strict_types=1);
namespace FireflyIII\Http\Requests;
use FireflyIII\Rules\Admin\IsValidSlackOrDiscordUrl;
use FireflyIII\Support\Request\ChecksLogin;
use Illuminate\Foundation\Http\FormRequest;
class PreferencesRequest extends FormRequest
{
use ChecksLogin;
/**
* Rules for this request.
*/
public function rules(): array
{
$rules = [
'slack_webhook_url' => ['nullable', 'url', 'min:1', new IsValidSlackOrDiscordUrl()],
'ntfy_server' => ['nullable', 'url', 'min:1'],
'ntfy_user' => ['required_with:ntfy_pass,ntfy_auth', 'nullable', 'string', 'min:1'],
'ntfy_pass' => ['required_with:ntfy_user,ntfy_auth', 'nullable', 'string', 'min:1'],
];
foreach (config('notifications.notifications.user') as $key => $info) {
$rules[sprintf('notification_%s', $key)] = 'in:0,1';
}
return $rules;
}
}

View File

@@ -144,7 +144,7 @@ class RuleFormRequest extends FormRequest
'description' => 'min:1|max:32768|nullable',
'stop_processing' => 'boolean',
'rule_group_id' => 'required|belongsToUser:rule_groups',
'trigger' => 'required|in:store-journal,update-journal',
'trigger' => 'required|in:store-journal,update-journal,manual-activation',
'triggers.*.type' => 'required|in:'.implode(',', $validTriggers),
'triggers.*.value' => sprintf('required_if:triggers.*.type,%s|max:1024|min:1|ruleTriggerValue', $contextTriggers),
'actions.*.type' => 'required|in:'.implode(',', $validActions),

View File

@@ -32,6 +32,7 @@ use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
@@ -144,7 +145,7 @@ class Account extends Model
}
/**
* Get all of the notes.
* Get all the notes.
*/
public function notes(): MorphMany
{
@@ -159,9 +160,9 @@ class Account extends Model
return $this->morphToMany(ObjectGroup::class, 'object_groupable');
}
public function piggyBanks(): HasMany
public function piggyBanks(): BelongsToMany
{
return $this->hasMany(PiggyBank::class);
return $this->belongsToMany(PiggyBank::class);
}
public function scopeAccountTypeIn(EloquentBuilder $query, array $types): void

View File

@@ -35,46 +35,46 @@ class AccountType extends Model
{
use ReturnsIntegerIdTrait;
/** @deprecated */
#[\Deprecated] /** @deprecated */
public const string ASSET = 'Asset account';
/** @deprecated */
#[\Deprecated] /** @deprecated */
public const string BENEFICIARY = 'Beneficiary account';
/** @deprecated */
#[\Deprecated] /** @deprecated */
public const string CASH = 'Cash account';
/** @deprecated */
#[\Deprecated] /** @deprecated */
public const string CREDITCARD = 'Credit card';
/** @deprecated */
#[\Deprecated] /** @deprecated */
public const string DEBT = 'Debt';
/** @deprecated */
#[\Deprecated] /** @deprecated */
public const string DEFAULT = 'Default account';
/** @deprecated */
#[\Deprecated] /** @deprecated */
public const string EXPENSE = 'Expense account';
/** @deprecated */
#[\Deprecated] /** @deprecated */
public const string IMPORT = 'Import account';
/** @deprecated */
#[\Deprecated] /** @deprecated */
public const string INITIAL_BALANCE = 'Initial balance account';
/** @deprecated */
#[\Deprecated] /** @deprecated */
public const string LIABILITY_CREDIT = 'Liability credit account';
/** @deprecated */
#[\Deprecated] /** @deprecated */
public const string LOAN = 'Loan';
/** @deprecated */
#[\Deprecated] /** @deprecated */
public const string MORTGAGE = 'Mortgage';
/** @deprecated */
#[\Deprecated] /** @deprecated */
public const string RECONCILIATION = 'Reconciliation account';
/** @deprecated */
#[\Deprecated] /** @deprecated */
public const string REVENUE = 'Revenue account';
protected $casts

View File

@@ -39,13 +39,13 @@ class AutoBudget extends Model
use ReturnsIntegerIdTrait;
use SoftDeletes;
/** @deprecated */
#[\Deprecated]
public const int AUTO_BUDGET_ADJUSTED = 3;
/** @deprecated */
#[\Deprecated]
public const int AUTO_BUDGET_RESET = 1;
/** @deprecated */
#[\Deprecated]
public const int AUTO_BUDGET_ROLLOVER = 2;
protected $fillable = ['budget_id', 'amount', 'period'];

View File

@@ -31,6 +31,7 @@ use FireflyIII\Support\Models\ReturnsIntegerIdTrait;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/**
@@ -90,6 +91,14 @@ class BudgetLimit extends Model
return $this->belongsTo(TransactionCurrency::class);
}
/**
* Get all the notes.
*/
public function notes(): MorphMany
{
return $this->morphMany(Note::class, 'noteable');
}
/**
* Get the amount
*/

View File

@@ -27,6 +27,7 @@ use FireflyIII\Support\Models\ReturnsIntegerIdTrait;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
@@ -43,20 +44,18 @@ class PiggyBank extends Model
protected $casts
= [
'created_at' => 'datetime',
'updated_at' => 'datetime',
'deleted_at' => 'datetime',
'startdate' => 'date',
'targetdate' => 'date',
'order' => 'int',
'active' => 'boolean',
'encrypted' => 'boolean',
'targetamount' => 'string',
'created_at' => 'datetime',
'updated_at' => 'datetime',
'deleted_at' => 'datetime',
'start_date' => 'date',
'target_date' => 'date',
'order' => 'int',
'active' => 'boolean',
'encrypted' => 'boolean',
'target_amount' => 'string',
];
protected $fillable = ['name', 'account_id', 'order', 'targetamount', 'startdate', 'startdate_tz', 'targetdate', 'targetdate_tz', 'active'];
protected $hidden = ['targetamount_encrypted', 'encrypted'];
protected $fillable = ['name', 'order', 'target_amount', 'start_date', 'start_date_tz', 'target_date', 'target_date_tz', 'active', 'transaction_currency_id'];
/**
* Route binder. Converts the key in the URL to the specified object (or throw 404).
@@ -68,7 +67,8 @@ class PiggyBank extends Model
if (auth()->check()) {
$piggyBankId = (int)$value;
$piggyBank = self::where('piggy_banks.id', $piggyBankId)
->leftJoin('accounts', 'accounts.id', '=', 'piggy_banks.account_id')
->leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id')
->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id')
->where('accounts.user_id', auth()->user()->id)->first(['piggy_banks.*'])
;
if (null !== $piggyBank) {
@@ -79,6 +79,11 @@ class PiggyBank extends Model
throw new NotFoundHttpException();
}
public function transactionCurrency(): BelongsTo
{
return $this->belongsTo(TransactionCurrency::class);
}
public function account(): BelongsTo
{
return $this->belongsTo(Account::class);
@@ -110,6 +115,11 @@ class PiggyBank extends Model
return $this->hasMany(PiggyBankEvent::class);
}
public function accounts(): BelongsToMany
{
return $this->belongsToMany(Account::class)->withPivot(['current_amount', 'native_current_amount']);
}
public function piggyBankRepetitions(): HasMany
{
return $this->hasMany(PiggyBankRepetition::class);
@@ -118,9 +128,9 @@ class PiggyBank extends Model
/**
* @param mixed $value
*/
public function setTargetamountAttribute($value): void
public function setTargetAmountAttribute($value): void
{
$this->attributes['targetamount'] = (string)$value;
$this->attributes['target_amount'] = (string)$value;
}
protected function accountId(): Attribute
@@ -140,7 +150,7 @@ class PiggyBank extends Model
/**
* Get the max amount
*/
protected function targetamount(): Attribute
protected function targetAmount(): Attribute
{
return Attribute::make(
get: static fn ($value) => (string)$value,

View File

@@ -40,14 +40,14 @@ class PiggyBankRepetition extends Model
protected $casts
= [
'created_at' => 'datetime',
'updated_at' => 'datetime',
'startdate' => SeparateTimezoneCaster::class,
'targetdate' => SeparateTimezoneCaster::class,
'virtual_balance' => 'string',
'created_at' => 'datetime',
'updated_at' => 'datetime',
'start_date' => SeparateTimezoneCaster::class,
'target_date' => SeparateTimezoneCaster::class,
'virtual_balance' => 'string',
];
protected $fillable = ['piggy_bank_id', 'startdate', 'startdate_tz', 'targetdate', 'targetdate_tz', 'currentamount'];
protected $fillable = ['piggy_bank_id', 'start_date', 'start_date_tz', 'target_date', 'target_date_tz', 'current_amount'];
public function piggyBank(): BelongsTo
{
@@ -56,7 +56,7 @@ class PiggyBankRepetition extends Model
public function scopeOnDates(EloquentBuilder $query, Carbon $start, Carbon $target): EloquentBuilder
{
return $query->where('startdate', $start->format('Y-m-d'))->where('targetdate', $target->format('Y-m-d'));
return $query->where('start_date', $start->format('Y-m-d'))->where('target_date', $target->format('Y-m-d'));
}
/**
@@ -66,14 +66,14 @@ class PiggyBankRepetition extends Model
{
return $query->where(
static function (EloquentBuilder $q) use ($date): void {
$q->where('startdate', '<=', $date->format('Y-m-d 00:00:00'));
$q->orWhereNull('startdate');
$q->where('start_date', '<=', $date->format('Y-m-d 00:00:00'));
$q->orWhereNull('start_date');
}
)
->where(
static function (EloquentBuilder $q) use ($date): void {
$q->where('targetdate', '>=', $date->format('Y-m-d 00:00:00'));
$q->orWhereNull('targetdate');
$q->where('target_date', '>=', $date->format('Y-m-d 00:00:00'));
$q->orWhereNull('target_date');
}
)
;
@@ -82,15 +82,15 @@ class PiggyBankRepetition extends Model
/**
* @param mixed $value
*/
public function setCurrentamountAttribute($value): void
public function setCurrentAmountAttribute($value): void
{
$this->attributes['currentamount'] = (string)$value;
$this->attributes['current_amount'] = (string)$value;
}
/**
* Get the amount
*/
protected function currentamount(): Attribute
protected function currentAmount(): Attribute
{
return Attribute::make(
get: static fn ($value) => (string)$value,

View File

@@ -39,16 +39,16 @@ class RecurrenceRepetition extends Model
use ReturnsIntegerIdTrait;
use SoftDeletes;
/** @deprecated */
#[\Deprecated]
public const int WEEKEND_DO_NOTHING = 1;
/** @deprecated */
#[\Deprecated]
public const int WEEKEND_SKIP_CREATION = 2;
/** @deprecated */
#[\Deprecated]
public const int WEEKEND_TO_FRIDAY = 3;
/** @deprecated */
#[\Deprecated]
public const int WEEKEND_TO_MONDAY = 4;
protected $casts

View File

@@ -38,7 +38,6 @@ use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/**
@@ -170,15 +169,11 @@ class TransactionJournal extends Model
public function scopeAfter(EloquentBuilder $query, Carbon $date): EloquentBuilder
{
Log::debug(sprintf('scopeAfter("%s")', $date->format('Y-m-d H:i:s')));
return $query->where('transaction_journals.date', '>=', $date->format('Y-m-d H:i:s'));
}
public function scopeBefore(EloquentBuilder $query, Carbon $date): EloquentBuilder
{
Log::debug(sprintf('scopeBefore("%s")', $date->format('Y-m-d H:i:s')));
return $query->where('transaction_journals.date', '<=', $date->format('Y-m-d H:i:s'));
}

View File

@@ -38,25 +38,25 @@ class TransactionType extends Model
use ReturnsIntegerIdTrait;
use SoftDeletes;
/** @deprecated */
#[\Deprecated]
public const string DEPOSIT = 'Deposit';
/** @deprecated */
#[\Deprecated]
public const string INVALID = 'Invalid';
/** @deprecated */
#[\Deprecated]
public const string LIABILITY_CREDIT = 'Liability credit';
/** @deprecated */
#[\Deprecated]
public const string OPENING_BALANCE = 'Opening balance';
/** @deprecated */
#[\Deprecated]
public const string RECONCILIATION = 'Reconciliation';
/** @deprecated */
#[\Deprecated]
public const string TRANSFER = 'Transfer';
/** @deprecated */
#[\Deprecated]
public const string WITHDRAWAL = 'Withdrawal';
protected $casts

View File

@@ -25,6 +25,7 @@ declare(strict_types=1);
namespace FireflyIII\Models;
use FireflyIII\Enums\UserRoleEnum;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Support\Models\ReturnsIntegerIdTrait;
use FireflyIII\User;
use Illuminate\Database\Eloquent\Model;
@@ -150,7 +151,7 @@ class UserGroup extends Model
*/
public function piggyBanks(): HasManyThrough
{
return $this->hasManyThrough(PiggyBank::class, Account::class);
throw new FireflyException('This user group method is EOL.');
}
public function recurrences(): HasMany

View File

@@ -1,114 +0,0 @@
<?php
/*
* TestNotification.php
* Copyright (c) 2022 james@firefly-iii.org
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace FireflyIII\Notifications\Admin;
use FireflyIII\Support\Notifications\UrlValidator;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;
/**
* Class TestNotification
*/
class TestNotification extends Notification
{
use Queueable;
private string $address;
/**
* Create a new notification instance.
*/
public function __construct(string $address)
{
$this->address = $address;
}
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*
* @return array
*/
public function toArray($notifiable)
{
return [
];
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*
* @return MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage())
->markdown('emails.admin-test', ['email' => $this->address])
->subject((string)trans('email.admin_test_subject'))
;
}
/**
* Get the Slack representation of the notification.
*
* @param mixed $notifiable
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*
* @return SlackMessage
*/
public function toSlack($notifiable)
{
return (new SlackMessage())->content((string)trans('email.admin_test_subject'));
}
/**
* Get the notification's delivery channels.
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*
* @param mixed $notifiable
*
* @return array
*/
public function via($notifiable)
{
$slackUrl = app('fireflyconfig')->get('slack_webhook_url', '')->data;
if (UrlValidator::isValidWebhookURL($slackUrl)) {
return ['mail', 'slack'];
}
return ['mail'];
}
}

View File

@@ -0,0 +1,109 @@
<?php
/*
* UnknownUserLoginAttempt.php
* Copyright (c) 2024 james@firefly-iii.org.
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*/
declare(strict_types=1);
namespace FireflyIII\Notifications\Admin;
use FireflyIII\Notifications\Notifiables\OwnerNotifiable;
use FireflyIII\Notifications\ReturnsAvailableChannels;
use FireflyIII\Notifications\ReturnsSettings;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;
use NotificationChannels\Pushover\PushoverMessage;
use Ntfy\Message;
class UnknownUserLoginAttempt extends Notification
{
use Queueable;
private string $address;
public function __construct(string $address)
{
$this->address = $address;
}
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toArray(OwnerNotifiable $notifiable)
{
return [
];
}
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toMail(OwnerNotifiable $notifiable): MailMessage
{
return new MailMessage()
->markdown('emails.owner.unknown-user', ['address' => $this->address])
->subject((string) trans('email.unknown_user_subject'))
;
}
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toNtfy(OwnerNotifiable $notifiable): Message
{
$settings = ReturnsSettings::getSettings('ntfy', 'owner', null);
$message = new Message();
$message->topic($settings['ntfy_topic']);
$message->title((string) trans('email.unknown_user_subject'));
$message->body((string) trans('email.unknown_user_message', ['address' => $this->address]));
return $message;
}
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toPushover(OwnerNotifiable $notifiable): PushoverMessage
{
return PushoverMessage::create((string) trans('email.unknown_user_message', ['address' => $this->address]))
->title((string) trans('email.unknown_user_subject'))
;
}
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toSlack(OwnerNotifiable $notifiable): SlackMessage
{
return new SlackMessage()->content(
(string) trans('email.unknown_user_body', ['address' => $this->address])
);
}
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function via(OwnerNotifiable $notifiable)
{
return ReturnsAvailableChannels::returnChannels('owner');
}
}

View File

@@ -25,11 +25,16 @@ declare(strict_types=1);
namespace FireflyIII\Notifications\Admin;
use FireflyIII\Models\InvitedUser;
use FireflyIII\Support\Notifications\UrlValidator;
use FireflyIII\Notifications\Notifiables\OwnerNotifiable;
use FireflyIII\Notifications\ReturnsAvailableChannels;
use FireflyIII\Notifications\ReturnsSettings;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Log;
use NotificationChannels\Pushover\PushoverMessage;
use Ntfy\Message;
/**
* Class UserInvitation
@@ -38,80 +43,77 @@ class UserInvitation extends Notification
{
use Queueable;
private InvitedUser $invitee;
private InvitedUser $invitee;
private OwnerNotifiable $owner;
/**
* Create a new notification instance.
*/
public function __construct(InvitedUser $invitee)
public function __construct(OwnerNotifiable $owner, InvitedUser $invitee)
{
$this->invitee = $invitee;
$this->owner = $owner;
}
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
*
* @return array
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toArray($notifiable)
public function toArray(OwnerNotifiable $notifiable)
{
return [
];
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
*
* @return MailMessage
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toMail($notifiable)
public function toMail(OwnerNotifiable $notifiable)
{
return (new MailMessage())
->markdown('emails.invitation-created', ['email' => $this->invitee->user->email, 'invitee' => $this->invitee->email])
->subject((string)trans('email.invitation_created_subject'))
->subject((string) trans('email.invitation_created_subject'))
;
}
/**
* Get the Slack representation of the notification.
*
* @param mixed $notifiable
*
* @return SlackMessage
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toSlack($notifiable)
public function toNtfy(OwnerNotifiable $notifiable): Message
{
return (new SlackMessage())->content(
(string)trans('email.invitation_created_body', ['email' => $this->invitee->user->email, 'invitee' => $this->invitee->email])
Log::debug('Now in toNtfy() for UserInvitation');
$settings = ReturnsSettings::getSettings('ntfy', 'owner', null);
$message = new Message();
$message->topic($settings['ntfy_topic']);
$message->title((string) trans('email.invitation_created_subject'));
$message->body((string) trans('email.invitation_created_body', ['email' => $this->invitee->user->email, 'invitee' => $this->invitee->email]));
return $message;
}
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toPushover(OwnerNotifiable $notifiable): PushoverMessage
{
Log::debug('Now in toPushover() for UserInvitation');
return PushoverMessage::create((string) trans('email.invitation_created_body', ['email' => $this->invitee->user->email, 'invitee' => $this->invitee->email]))
->title((string) trans('email.invitation_created_subject'))
;
}
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toSlack(OwnerNotifiable $notifiable)
{
return new SlackMessage()->content(
(string) trans('email.invitation_created_body', ['email' => $this->invitee->user->email, 'invitee' => $this->invitee->email])
);
}
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
*
* @return array
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function via($notifiable)
public function via(OwnerNotifiable $notifiable)
{
$slackUrl = app('fireflyconfig')->get('slack_webhook_url', '')->data;
if (UrlValidator::isValidWebhookURL($slackUrl)) {
return ['mail', 'slack'];
}
return ['mail'];
return ReturnsAvailableChannels::returnChannels('owner');
}
}

View File

@@ -24,12 +24,17 @@ declare(strict_types=1);
namespace FireflyIII\Notifications\Admin;
use FireflyIII\Support\Notifications\UrlValidator;
use FireflyIII\Notifications\Notifiables\OwnerNotifiable;
use FireflyIII\Notifications\ReturnsAvailableChannels;
use FireflyIII\Notifications\ReturnsSettings;
use FireflyIII\User;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Log;
use NotificationChannels\Pushover\PushoverMessage;
use Ntfy\Message;
/**
* Class UserRegistration
@@ -38,78 +43,75 @@ class UserRegistration extends Notification
{
use Queueable;
private User $user;
private OwnerNotifiable $owner;
private User $user;
/**
* Create a new notification instance.
*/
public function __construct(User $user)
public function __construct(OwnerNotifiable $owner, User $user)
{
$this->user = $user;
$this->user = $user;
$this->owner = $owner;
}
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
*
* @return array
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toArray($notifiable)
public function toArray(OwnerNotifiable $notifiable)
{
return [
];
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
*
* @return MailMessage
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toMail($notifiable)
public function toMail(OwnerNotifiable $notifiable)
{
return (new MailMessage())
->markdown('emails.registered-admin', ['email' => $this->user->email, 'id' => $this->user->id])
->subject((string)trans('email.registered_subject_admin'))
->subject((string) trans('email.registered_subject_admin'))
;
}
/**
* Get the Slack representation of the notification.
*
* @param mixed $notifiable
*
* @return SlackMessage
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toSlack($notifiable)
public function toNtfy(OwnerNotifiable $notifiable): Message
{
return (new SlackMessage())->content((string)trans('email.admin_new_user_registered', ['email' => $this->user->email, 'id' => $this->user->id]));
Log::debug('Now in toNtfy() for (Admin) UserRegistration');
$settings = ReturnsSettings::getSettings('ntfy', 'owner', null);
$message = new Message();
$message->topic($settings['ntfy_topic']);
$message->title((string) trans('email.registered_subject_admin'));
$message->body((string) trans('email.admin_new_user_registered', ['email' => $this->user->email, 'invitee' => $this->user->email]));
return $message;
}
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
*
* @return array
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function via($notifiable)
public function toPushover(OwnerNotifiable $notifiable): PushoverMessage
{
$slackUrl = app('fireflyconfig')->get('slack_webhook_url', '')->data;
if (UrlValidator::isValidWebhookURL($slackUrl)) {
return ['mail', 'slack'];
}
Log::debug('Now in toPushover() for UserRegistration');
return ['mail'];
return PushoverMessage::create((string) trans('email.admin_new_user_registered', ['email' => $this->user->email, 'invitee' => $this->user->email]))
->title((string) trans('email.registered_subject_admin'))
;
}
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toSlack(OwnerNotifiable $notifiable)
{
return new SlackMessage()->content((string) trans('email.admin_new_user_registered', ['email' => $this->user->email, 'id' => $this->user->id]));
}
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function via(OwnerNotifiable $notifiable)
{
return ReturnsAvailableChannels::returnChannels('owner');
}
}

View File

@@ -24,11 +24,16 @@ declare(strict_types=1);
namespace FireflyIII\Notifications\Admin;
use FireflyIII\Support\Notifications\UrlValidator;
use FireflyIII\Notifications\Notifiables\OwnerNotifiable;
use FireflyIII\Notifications\ReturnsAvailableChannels;
use FireflyIII\Notifications\ReturnsSettings;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Log;
use NotificationChannels\Pushover\PushoverMessage;
use Ntfy\Message;
/**
* Class VersionCheckResult
@@ -39,58 +44,64 @@ class VersionCheckResult extends Notification
private string $message;
/**
* Create a new notification instance.
*/
public function __construct(string $message)
{
$this->message = $message;
}
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
*
* @return array
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toArray($notifiable)
public function toArray(OwnerNotifiable $notifiable)
{
return [
];
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
*
* @return MailMessage
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toMail($notifiable)
public function toMail(OwnerNotifiable $notifiable)
{
return (new MailMessage())
->markdown('emails.new-version', ['message' => $this->message])
->subject((string)trans('email.new_version_email_subject'))
->subject((string) trans('email.new_version_email_subject'))
;
}
/**
* Get the Slack representation of the notification.
*
* @param mixed $notifiable
*
* @return SlackMessage
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toSlack($notifiable)
public function toNtfy(OwnerNotifiable $notifiable): Message
{
return (new SlackMessage())->content($this->message)
Log::debug('Now in toNtfy() for VersionCheckResult');
$settings = ReturnsSettings::getSettings('ntfy', 'owner', null);
$message = new Message();
$message->topic($settings['ntfy_topic']);
$message->title((string) trans('email.new_version_email_subject'));
$message->body($this->message);
return $message;
}
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toPushover(OwnerNotifiable $notifiable): PushoverMessage
{
Log::debug('Now in toPushover() for VersionCheckResult');
return PushoverMessage::create($this->message)
->title((string) trans('email.new_version_email_subject'))
;
}
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toSlack(OwnerNotifiable $notifiable)
{
return new SlackMessage()->content($this->message)
->attachment(static function ($attachment): void {
$attachment->title('Firefly III @ GitHub', 'https://github.com/firefly-iii/firefly-iii/releases');
})
@@ -98,21 +109,10 @@ class VersionCheckResult extends Notification
}
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
*
* @return array
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function via($notifiable)
public function via(OwnerNotifiable $notifiable)
{
$slackUrl = app('fireflyconfig')->get('slack_webhook_url', '')->data;
if (UrlValidator::isValidWebhookURL($slackUrl)) {
return ['mail', 'slack'];
}
return ['mail'];
return ReturnsAvailableChannels::returnChannels('owner');
}
}

View File

@@ -0,0 +1,78 @@
<?php
/*
* AdminNotifiable.php
* Copyright (c) 2024 james@firefly-iii.org.
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*/
declare(strict_types=1);
namespace FireflyIII\Notifications\Notifiables;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use NotificationChannels\Pushover\PushoverReceiver;
class OwnerNotifiable
{
/**
* Get the notification routing information for the given driver.
*
* @param string $driver
* @param null|Notification $notification
*
* @return mixed
*/
public function routeNotificationFor($driver, $notification = null)
{
$method = 'routeNotificationFor'.Str::studly($driver);
if (method_exists($this, $method)) {
Log::debug(sprintf('Redirect for settings to "%s".', $method));
return $this->{$method}($notification); // @phpstan-ignore-line
}
Log::debug(sprintf('No method "%s" found, return generic settings.', $method));
return match ($driver) {
'mail' => (string) config('firefly.site_owner'),
default => null,
};
}
public function routeNotificationForPushover()
{
Log::debug('Return settings for routeNotificationForPushover');
$pushoverAppToken = (string) app('fireflyconfig')->getEncrypted('pushover_app_token', '')->data;
$pushoverUserToken = (string) app('fireflyconfig')->getEncrypted('pushover_user_token', '')->data;
return PushoverReceiver::withUserKey($pushoverUserToken)
->withApplicationToken($pushoverAppToken)
;
}
public function routeNotificationForSlack(): string
{
$res = app('fireflyconfig')->getEncrypted('slack_webhook_url', '')->data;
if (is_array($res)) {
$res = '';
}
return (string) $res;
}
}

View File

@@ -0,0 +1,117 @@
<?php
/*
* ReturnsAvailableChannels.php
* Copyright (c) 2024 james@firefly-iii.org.
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*/
declare(strict_types=1);
namespace FireflyIII\Notifications;
use FireflyIII\Support\Notifications\UrlValidator;
use FireflyIII\User;
use Illuminate\Support\Facades\Log;
use NotificationChannels\Pushover\PushoverChannel;
use Wijourdil\NtfyNotificationChannel\Channels\NtfyChannel;
class ReturnsAvailableChannels
{
public static function returnChannels(string $type, ?User $user = null): array
{
$channels = ['mail'];
if ('owner' === $type) {
return self::returnOwnerChannels();
}
if ('user' === $type && null !== $user) {
return self::returnUserChannels($user);
}
return $channels;
}
private static function returnOwnerChannels(): array
{
$channels = ['mail'];
$slackUrl = app('fireflyconfig')->getEncrypted('slack_webhook_url', '')->data;
if (UrlValidator::isValidWebhookURL($slackUrl)) {
$channels[] = 'slack';
}
// validate presence of of Ntfy settings.
if ('' !== (string) app('fireflyconfig')->getEncrypted('ntfy_topic', '')->data) {
Log::debug('Enabled ntfy.');
$channels[] = NtfyChannel::class;
}
if ('' === (string) app('fireflyconfig')->getEncrypted('ntfy_topic', '')->data) {
Log::warning('No topic name for Ntfy, channel is disabled.');
}
// pushover
$pushoverAppToken = (string) app('fireflyconfig')->getEncrypted('pushover_app_token', '')->data;
$pushoverUserToken = (string) app('fireflyconfig')->getEncrypted('pushover_user_token', '')->data;
if ('' === $pushoverAppToken || '' === $pushoverUserToken) {
Log::warning('[b] No Pushover token, channel is disabled.');
}
if ('' !== $pushoverAppToken && '' !== $pushoverUserToken) {
Log::debug('Enabled pushover.');
$channels[] = PushoverChannel::class;
}
Log::debug(sprintf('Final channel set in ReturnsAvailableChannels: %s ', implode(', ', $channels)));
return $channels;
}
private static function returnUserChannels(User $user): array
{
$channels = ['mail'];
$slackUrl = app('preferences')->getEncryptedForUser($user, 'slack_webhook_url', '')->data;
if (UrlValidator::isValidWebhookURL($slackUrl)) {
$channels[] = 'slack';
}
// validate presence of of Ntfy settings.
if ('' !== (string) app('preferences')->getEncryptedForUser($user, 'ntfy_topic', '')->data) {
Log::debug('Enabled ntfy.');
$channels[] = NtfyChannel::class;
}
if ('' === (string) app('preferences')->getEncryptedForUser($user, 'ntfy_topic', '')->data) {
Log::warning('No topic name for Ntfy, channel is disabled.');
}
// pushover
$pushoverAppToken = (string) app('preferences')->getEncryptedForUser($user, 'pushover_app_token', '')->data;
$pushoverUserToken = (string) app('preferences')->getEncryptedForUser($user, 'pushover_user_token', '')->data;
if ('' === $pushoverAppToken || '' === $pushoverUserToken) {
Log::warning('[b] No Pushover token, channel is disabled.');
}
if ('' !== $pushoverAppToken && '' !== $pushoverUserToken) {
Log::debug('Enabled pushover.');
$channels[] = PushoverChannel::class;
}
Log::debug(sprintf('Final channel set in ReturnsAvailableChannels (user): %s ', implode(', ', $channels)));
// only the owner can get notifications over
return $channels;
}
}

View File

@@ -0,0 +1,81 @@
<?php
/*
* ReturnsSettings.php
* Copyright (c) 2024 james@firefly-iii.org.
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*/
declare(strict_types=1);
namespace FireflyIII\Notifications;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Support\Facades\FireflyConfig;
use FireflyIII\Support\Facades\Preferences;
use FireflyIII\User;
class ReturnsSettings
{
public static function getSettings(string $channel, string $type, ?User $user): array
{
if ('ntfy' === $channel) {
return self::getNtfySettings($type, $user);
}
throw new FireflyException(sprintf('Cannot handle channel "%s"', $channel));
}
private static function getNtfySettings(string $type, ?User $user)
{
$settings = [
'ntfy_server' => 'https://ntfy.sh',
'ntfy_topic' => '',
'ntfy_auth' => false,
'ntfy_user' => '',
'ntfy_pass' => '',
];
if ('user' === $type && null !== $user) {
$settings['ntfy_server'] = Preferences::getEncryptedForUser($user, 'ntfy_server', 'https://ntfy.sh')->data;
$settings['ntfy_topic'] = Preferences::getEncryptedForUser($user, 'ntfy_topic', '')->data;
$settings['ntfy_auth'] = Preferences::getForUser($user, 'ntfy_auth', false)->data;
$settings['ntfy_user'] = Preferences::getEncryptedForUser($user, 'ntfy_user', '')->data;
$settings['ntfy_pass'] = Preferences::getEncryptedForUser($user, 'ntfy_pass', '')->data;
}
if ('owner' === $type) {
$settings['ntfy_server'] = FireflyConfig::getEncrypted('ntfy_server', 'https://ntfy.sh')->data;
$settings['ntfy_topic'] = FireflyConfig::getEncrypted('ntfy_topic', '')->data;
$settings['ntfy_auth'] = FireflyConfig::get('ntfy_auth', false)->data;
$settings['ntfy_user'] = FireflyConfig::getEncrypted('ntfy_user', '')->data;
$settings['ntfy_pass'] = FireflyConfig::getEncrypted('ntfy_pass', '')->data;
}
// overrule config.
config(['ntfy-notification-channel.server' => $settings['ntfy_server']]);
config(['ntfy-notification-channel.topic' => $settings['ntfy_topic']]);
if ($settings['ntfy_auth']) {
// overrule auth as well.
config(['ntfy-notification-channel.authentication.enabled' => true]);
config(['ntfy-notification-channel.authentication.username' => $settings['ntfy_user']]);
config(['ntfy-notification-channel.authentication.password' => $settings['ntfy_pass']]);
}
return $settings;
}
}

View File

@@ -24,95 +24,82 @@ declare(strict_types=1);
namespace FireflyIII\Notifications\Security;
use FireflyIII\Support\Notifications\UrlValidator;
use FireflyIII\Notifications\ReturnsAvailableChannels;
use FireflyIII\Notifications\ReturnsSettings;
use FireflyIII\User;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;
use NotificationChannels\Pushover\PushoverMessage;
use Ntfy\Message;
class DisabledMFANotification extends Notification
{
use Queueable;
private User $user;
private User $user;
/**
* Create a new notification instance.
*/
public function __construct(User $user)
{
$this->user = $user;
}
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
*
* @return array
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toArray($notifiable)
public function toArray(User $notifiable)
{
return [
];
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
*
* @return MailMessage
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toMail($notifiable)
public function toMail(User $notifiable)
{
$subject = (string)trans('email.disabled_mfa_subject');
$subject = (string) trans('email.disabled_mfa_subject');
return (new MailMessage())->markdown('emails.security.disabled-mfa', ['user' => $this->user])->subject($subject);
}
/**
* Get the Slack representation of the notification.
*
* @param mixed $notifiable
*
* @return SlackMessage
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toSlack($notifiable)
public function toNtfy(User $notifiable): Message
{
$message = (string)trans('email.disabled_mfa_slack', ['email' => $this->user->email]);
$settings = ReturnsSettings::getSettings('ntfy', 'user', $notifiable);
$message = new Message();
$message->topic($settings['ntfy_topic']);
$message->title((string) trans('email.disabled_mfa_subject'));
$message->body((string) trans('email.disabled_mfa_slack', ['email' => $this->user->email]));
return (new SlackMessage())->content($message);
return $message;
}
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
*
* @return array
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function via($notifiable)
public function toPushover(User $notifiable): PushoverMessage
{
/** @var null|User $user */
$user = auth()->user();
$slackUrl = null === $user ? '' : app('preferences')->getForUser(auth()->user(), 'slack_webhook_url', '')->data;
if (is_array($slackUrl)) {
$slackUrl = '';
}
if (UrlValidator::isValidWebhookURL((string)$slackUrl)) {
return ['mail', 'slack'];
}
return PushoverMessage::create((string) trans('email.disabled_mfa_slack', ['email' => $this->user->email]))
->title((string) trans('email.disabled_mfa_subject'))
;
}
return ['mail'];
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toSlack(User $notifiable)
{
$message = (string) trans('email.disabled_mfa_slack', ['email' => $this->user->email]);
return new SlackMessage()->content($message);
}
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function via(User $notifiable)
{
return ReturnsAvailableChannels::returnChannels('user', $notifiable);
}
}

View File

@@ -24,95 +24,82 @@ declare(strict_types=1);
namespace FireflyIII\Notifications\Security;
use FireflyIII\Support\Notifications\UrlValidator;
use FireflyIII\Notifications\ReturnsAvailableChannels;
use FireflyIII\Notifications\ReturnsSettings;
use FireflyIII\User;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;
use NotificationChannels\Pushover\PushoverMessage;
use Ntfy\Message;
class EnabledMFANotification extends Notification
{
use Queueable;
private User $user;
private User $user;
/**
* Create a new notification instance.
*/
public function __construct(User $user)
{
$this->user = $user;
}
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
*
* @return array
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toArray($notifiable)
public function toArray(User $notifiable)
{
return [
];
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
*
* @return MailMessage
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toMail($notifiable)
public function toMail(User $notifiable)
{
$subject = (string)trans('email.enabled_mfa_subject');
$subject = (string) trans('email.enabled_mfa_subject');
return (new MailMessage())->markdown('emails.security.enabled-mfa', ['user' => $this->user])->subject($subject);
}
/**
* Get the Slack representation of the notification.
*
* @param mixed $notifiable
*
* @return SlackMessage
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toSlack($notifiable)
public function toNtfy(User $notifiable): Message
{
$message = (string)trans('email.enabled_mfa_slack', ['email' => $this->user->email]);
$settings = ReturnsSettings::getSettings('ntfy', 'user', $notifiable);
$message = new Message();
$message->topic($settings['ntfy_topic']);
$message->title((string) trans('email.enabled_mfa_subject'));
$message->body((string) trans('email.enabled_mfa_slack', ['email' => $this->user->email]));
return (new SlackMessage())->content($message);
return $message;
}
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
*
* @return array
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function via($notifiable)
public function toPushover(User $notifiable): PushoverMessage
{
/** @var null|User $user */
$user = auth()->user();
$slackUrl = null === $user ? '' : app('preferences')->getForUser(auth()->user(), 'slack_webhook_url', '')->data;
if (is_array($slackUrl)) {
$slackUrl = '';
}
if (UrlValidator::isValidWebhookURL((string)$slackUrl)) {
return ['mail', 'slack'];
}
return PushoverMessage::create((string) trans('email.enabled_mfa_slack', ['email' => $this->user->email]))
->title((string) trans('email.enabled_mfa_subject'))
;
}
return ['mail'];
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toSlack(User $notifiable)
{
$message = (string) trans('email.enabled_mfa_slack', ['email' => $this->user->email]);
return new SlackMessage()->content($message);
}
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function via(User $notifiable)
{
return ReturnsAvailableChannels::returnChannels('user', $notifiable);
}
}

View File

@@ -24,23 +24,23 @@ declare(strict_types=1);
namespace FireflyIII\Notifications\Security;
use FireflyIII\Support\Notifications\UrlValidator;
use FireflyIII\Notifications\ReturnsAvailableChannels;
use FireflyIII\Notifications\ReturnsSettings;
use FireflyIII\User;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;
use NotificationChannels\Pushover\PushoverMessage;
use Ntfy\Message;
class MFABackupFewLeftNotification extends Notification
{
use Queueable;
private User $user;
private int $count;
private int $count;
private User $user;
/**
* Create a new notification instance.
*/
public function __construct(User $user, int $count)
{
$this->user = $user;
@@ -48,73 +48,60 @@ class MFABackupFewLeftNotification extends Notification
}
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
*
* @return array
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toArray($notifiable)
public function toArray(User $notifiable)
{
return [
];
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
*
* @return MailMessage
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toMail($notifiable)
public function toMail(User $notifiable)
{
$subject = (string)trans('email.mfa_few_backups_left_subject', ['count' => $this->count]);
$subject = (string) trans('email.mfa_few_backups_left_subject', ['count' => $this->count]);
return (new MailMessage())->markdown('emails.security.few-backup-codes', ['user' => $this->user, 'count' => $this->count])->subject($subject);
}
/**
* Get the Slack representation of the notification.
*
* @param mixed $notifiable
*
* @return SlackMessage
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toSlack($notifiable)
public function toSlack(User $notifiable)
{
$message = (string)trans('email.mfa_few_backups_left_slack', ['email' => $this->user->email, 'count' => $this->count]);
$message = (string) trans('email.mfa_few_backups_left_slack', ['email' => $this->user->email, 'count' => $this->count]);
return (new SlackMessage())->content($message);
return new SlackMessage()->content($message);
}
public function toNtfy(User $notifiable): Message
{
$settings = ReturnsSettings::getSettings('ntfy', 'user', $notifiable);
$message = new Message();
$message->topic($settings['ntfy_topic']);
$message->title((string) trans('email.mfa_few_backups_left_subject'));
$message->body((string) trans('email.mfa_few_backups_left_slack', ['email' => $this->user->email, 'count' => $this->count]));
return $message;
}
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
*
* @return array
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function via($notifiable)
public function toPushover(User $notifiable): PushoverMessage
{
/** @var null|User $user */
$user = auth()->user();
$slackUrl = null === $user ? '' : app('preferences')->getForUser(auth()->user(), 'slack_webhook_url', '')->data;
if (is_array($slackUrl)) {
$slackUrl = '';
}
if (UrlValidator::isValidWebhookURL((string)$slackUrl)) {
return ['mail', 'slack'];
}
return PushoverMessage::create((string) trans('email.mfa_few_backups_left_slack', ['email' => $this->user->email, 'count' => $this->count]))
->title((string) trans('email.mfa_few_backups_left_subject'))
;
}
return ['mail'];
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function via(User $notifiable)
{
return ReturnsAvailableChannels::returnChannels('user', $notifiable);
}
}

View File

@@ -24,95 +24,82 @@ declare(strict_types=1);
namespace FireflyIII\Notifications\Security;
use FireflyIII\Support\Notifications\UrlValidator;
use FireflyIII\Notifications\ReturnsAvailableChannels;
use FireflyIII\Notifications\ReturnsSettings;
use FireflyIII\User;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;
use NotificationChannels\Pushover\PushoverMessage;
use Ntfy\Message;
class MFABackupNoLeftNotification extends Notification
{
use Queueable;
private User $user;
private User $user;
/**
* Create a new notification instance.
*/
public function __construct(User $user)
{
$this->user = $user;
}
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
*
* @return array
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toArray($notifiable)
public function toArray(User $notifiable)
{
return [
];
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
*
* @return MailMessage
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toMail($notifiable)
public function toMail(User $notifiable)
{
$subject = (string)trans('email.mfa_no_backups_left_subject');
$subject = (string) trans('email.mfa_no_backups_left_subject');
return (new MailMessage())->markdown('emails.security.no-backup-codes', ['user' => $this->user])->subject($subject);
}
/**
* Get the Slack representation of the notification.
*
* @param mixed $notifiable
*
* @return SlackMessage
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toSlack($notifiable)
public function toSlack(User $notifiable)
{
$message = (string)trans('email.mfa_no_backups_left_slack', ['email' => $this->user->email]);
$message = (string) trans('email.mfa_no_backups_left_slack', ['email' => $this->user->email]);
return (new SlackMessage())->content($message);
return new SlackMessage()->content($message);
}
public function toNtfy(User $notifiable): Message
{
$settings = ReturnsSettings::getSettings('ntfy', 'user', $notifiable);
$message = new Message();
$message->topic($settings['ntfy_topic']);
$message->title((string) trans('email.mfa_no_backups_left_subject'));
$message->body((string) trans('email.mfa_no_backups_left_slack', ['email' => $this->user->email]));
return $message;
}
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
*
* @return array
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function via($notifiable)
public function toPushover(User $notifiable): PushoverMessage
{
/** @var null|User $user */
$user = auth()->user();
$slackUrl = null === $user ? '' : app('preferences')->getForUser(auth()->user(), 'slack_webhook_url', '')->data;
if (is_array($slackUrl)) {
$slackUrl = '';
}
if (UrlValidator::isValidWebhookURL((string)$slackUrl)) {
return ['mail', 'slack'];
}
return PushoverMessage::create((string) trans('email.mfa_few_backups_left_slack', ['email' => $this->user->email]))
->title((string) trans('email.mfa_no_backups_left_slack'))
;
}
return ['mail'];
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function via(User $notifiable)
{
return ReturnsAvailableChannels::returnChannels('user', $notifiable);
}
}

View File

@@ -24,97 +24,81 @@ declare(strict_types=1);
namespace FireflyIII\Notifications\Security;
use FireflyIII\Support\Notifications\UrlValidator;
use FireflyIII\Notifications\ReturnsAvailableChannels;
use FireflyIII\Notifications\ReturnsSettings;
use FireflyIII\User;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;
use NotificationChannels\Pushover\PushoverMessage;
use Ntfy\Message;
class MFAManyFailedAttemptsNotification extends Notification
{
use Queueable;
private User $user;
private int $count;
private int $count;
private User $user;
/**
* Create a new notification instance.
*/
public function __construct(User $user, int $count)
{
$this->user = $user;
$this->count = $count;
}
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
*
* @return array
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toArray($notifiable)
public function toArray(User $notifiable)
{
return [
];
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
*
* @return MailMessage
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toMail($notifiable)
public function toMail(User $notifiable)
{
$subject = (string)trans('email.mfa_many_failed_subject', ['count' => $this->count]);
$subject = (string) trans('email.mfa_many_failed_subject', ['count' => $this->count]);
return (new MailMessage())->markdown('emails.security.many-failed-attempts', ['user' => $this->user, 'count' => $this->count])->subject($subject);
}
/**
* Get the Slack representation of the notification.
*
* @param mixed $notifiable
*
* @return SlackMessage
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toSlack($notifiable)
public function toSlack(User $notifiable)
{
$message = (string)trans('email.mfa_many_failed_slack', ['email' => $this->user->email, 'count' => $this->count]);
$message = (string) trans('email.mfa_many_failed_slack', ['email' => $this->user->email, 'count' => $this->count]);
return (new SlackMessage())->content($message);
return new SlackMessage()->content($message);
}
public function toNtfy(User $notifiable): Message
{
$settings = ReturnsSettings::getSettings('ntfy', 'user', $notifiable);
$message = new Message();
$message->topic($settings['ntfy_topic']);
$message->title((string) trans('email.mfa_many_failed_subject'));
$message->body((string) trans('email.mfa_many_failed_slack', ['email' => $this->user->email, 'count' => $this->count]));
return $message;
}
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
*
* @return array
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function via($notifiable)
public function toPushover(User $notifiable): PushoverMessage
{
/** @var null|User $user */
$user = auth()->user();
$slackUrl = null === $user ? '' : app('preferences')->getForUser(auth()->user(), 'slack_webhook_url', '')->data;
if (is_array($slackUrl)) {
$slackUrl = '';
}
if (UrlValidator::isValidWebhookURL((string)$slackUrl)) {
return ['mail', 'slack'];
}
return PushoverMessage::create((string) trans('email.mfa_many_failed_slack', ['email' => $this->user->email, 'count' => $this->count]))
->title((string) trans('email.mfa_many_failed_subject'))
;
}
return ['mail'];
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function via(User $notifiable)
{
return ReturnsAvailableChannels::returnChannels('user', $notifiable);
}
}

View File

@@ -24,95 +24,82 @@ declare(strict_types=1);
namespace FireflyIII\Notifications\Security;
use FireflyIII\Support\Notifications\UrlValidator;
use FireflyIII\Notifications\ReturnsAvailableChannels;
use FireflyIII\Notifications\ReturnsSettings;
use FireflyIII\User;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;
use NotificationChannels\Pushover\PushoverMessage;
use Ntfy\Message;
class MFAUsedBackupCodeNotification extends Notification
{
use Queueable;
private User $user;
private User $user;
/**
* Create a new notification instance.
*/
public function __construct(User $user)
{
$this->user = $user;
}
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
*
* @return array
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toArray($notifiable)
public function toArray(User $notifiable)
{
return [
];
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
*
* @return MailMessage
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toMail($notifiable)
public function toMail(User $notifiable)
{
$subject = (string)trans('email.used_backup_code_subject');
$subject = (string) trans('email.used_backup_code_subject');
return (new MailMessage())->markdown('emails.security.used-backup-code', ['user' => $this->user])->subject($subject);
}
/**
* Get the Slack representation of the notification.
*
* @param mixed $notifiable
*
* @return SlackMessage
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toSlack($notifiable)
public function toSlack(User $notifiable)
{
$message = (string)trans('email.used_backup_code_slack', ['email' => $this->user->email]);
$message = (string) trans('email.used_backup_code_slack', ['email' => $this->user->email]);
return (new SlackMessage())->content($message);
return new SlackMessage()->content($message);
}
public function toNtfy(User $notifiable): Message
{
$settings = ReturnsSettings::getSettings('ntfy', 'user', $notifiable);
$message = new Message();
$message->topic($settings['ntfy_topic']);
$message->title((string) trans('email.used_backup_code_subject'));
$message->body((string) trans('email.used_backup_code_slack', ['email' => $this->user->email]));
return $message;
}
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
*
* @return array
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function via($notifiable)
public function toPushover(User $notifiable): PushoverMessage
{
/** @var null|User $user */
$user = auth()->user();
$slackUrl = null === $user ? '' : app('preferences')->getForUser(auth()->user(), 'slack_webhook_url', '')->data;
if (is_array($slackUrl)) {
$slackUrl = '';
}
if (UrlValidator::isValidWebhookURL((string)$slackUrl)) {
return ['mail', 'slack'];
}
return PushoverMessage::create((string) trans('email.used_backup_code_slack', ['email' => $this->user->email]))
->title((string) trans('email.used_backup_code_subject'))
;
}
return ['mail'];
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function via(User $notifiable)
{
return ReturnsAvailableChannels::returnChannels('user', $notifiable);
}
}

View File

@@ -24,95 +24,82 @@ declare(strict_types=1);
namespace FireflyIII\Notifications\Security;
use FireflyIII\Support\Notifications\UrlValidator;
use FireflyIII\Notifications\ReturnsAvailableChannels;
use FireflyIII\Notifications\ReturnsSettings;
use FireflyIII\User;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;
use NotificationChannels\Pushover\PushoverMessage;
use Ntfy\Message;
class NewBackupCodesNotification extends Notification
{
use Queueable;
private User $user;
private User $user;
/**
* Create a new notification instance.
*/
public function __construct(User $user)
{
$this->user = $user;
}
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
*
* @return array
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toArray($notifiable)
public function toArray(User $notifiable)
{
return [
];
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
*
* @return MailMessage
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toMail($notifiable)
public function toMail(User $notifiable)
{
$subject = (string)trans('email.new_backup_codes_subject');
$subject = (string) trans('email.new_backup_codes_subject');
return (new MailMessage())->markdown('emails.security.new-backup-codes', ['user' => $this->user])->subject($subject);
}
/**
* Get the Slack representation of the notification.
*
* @param mixed $notifiable
*
* @return SlackMessage
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toSlack($notifiable)
public function toSlack(User $notifiable)
{
$message = (string)trans('email.new_backup_codes_slack', ['email' => $this->user->email]);
$message = (string) trans('email.new_backup_codes_slack', ['email' => $this->user->email]);
return (new SlackMessage())->content($message);
return new SlackMessage()->content($message);
}
public function toNtfy(User $notifiable): Message
{
$settings = ReturnsSettings::getSettings('ntfy', 'user', $notifiable);
$message = new Message();
$message->topic($settings['ntfy_topic']);
$message->title((string) trans('email.new_backup_codes_subject'));
$message->body((string) trans('email.new_backup_codes_slack', ['email' => $this->user->email]));
return $message;
}
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
*
* @return array
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function via($notifiable)
public function toPushover(User $notifiable): PushoverMessage
{
/** @var null|User $user */
$user = auth()->user();
$slackUrl = null === $user ? '' : app('preferences')->getForUser(auth()->user(), 'slack_webhook_url', '')->data;
if (is_array($slackUrl)) {
$slackUrl = '';
}
if (UrlValidator::isValidWebhookURL((string)$slackUrl)) {
return ['mail', 'slack'];
}
return PushoverMessage::create((string) trans('email.new_backup_codes_slack', ['email' => $this->user->email]))
->title((string) trans('email.new_backup_codes_subject'))
;
}
return ['mail'];
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function via(User $notifiable)
{
return ReturnsAvailableChannels::returnChannels('user', $notifiable);
}
}

View File

@@ -0,0 +1,102 @@
<?php
/*
* UserFailedLoginAttempt.php
* Copyright (c) 2024 james@firefly-iii.org.
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*/
declare(strict_types=1);
namespace FireflyIII\Notifications\Security;
use FireflyIII\Notifications\ReturnsAvailableChannels;
use FireflyIII\Notifications\ReturnsSettings;
use FireflyIII\User;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;
use NotificationChannels\Pushover\PushoverMessage;
use Ntfy\Message;
class UserFailedLoginAttempt extends Notification
{
use Queueable;
private User $user;
public function __construct(User $user)
{
$this->user = $user;
}
public function toArray(User $notifiable)
{
return [
];
}
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toMail(User $notifiable)
{
$subject = (string) trans('email.failed_login_subject');
return (new MailMessage())->markdown('emails.security.failed-login', ['user' => $this->user])->subject($subject);
}
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toSlack(User $notifiable)
{
$message = (string) trans('email.failed_login_message', ['email' => $this->user->email]);
return new SlackMessage()->content($message);
}
public function toNtfy(User $notifiable): Message
{
$settings = ReturnsSettings::getSettings('ntfy', 'user', $notifiable);
$message = new Message();
$message->topic($settings['ntfy_topic']);
$message->title((string) trans('email.failed_login_subject'));
$message->body((string) trans('email.failed_login_message', ['email' => $this->user->email]));
return $message;
}
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toPushover(User $notifiable): PushoverMessage
{
return PushoverMessage::create((string) trans('email.failed_login_message', ['email' => $this->user->email]))
->title((string) trans('email.failed_login_subject'))
;
}
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function via(User $notifiable)
{
return ReturnsAvailableChannels::returnChannels('user', $notifiable);
}
}

View File

@@ -0,0 +1,75 @@
<?php
/*
* TestNotification.php
* Copyright (c) 2022 james@firefly-iii.org
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace FireflyIII\Notifications\Test;
use FireflyIII\Notifications\Notifiables\OwnerNotifiable;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
/**
* Class TestNotification
*/
class OwnerTestNotificationEmail extends Notification
{
use Queueable;
private OwnerNotifiable $owner;
public function __construct(OwnerNotifiable $owner)
{
$this->owner = $owner;
}
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toArray(OwnerNotifiable $notifiable)
{
return [
];
}
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toMail(OwnerNotifiable $notifiable)
{
$address = (string) config('firefly.site_owner');
return (new MailMessage())
->markdown('emails.admin-test', ['email' => $address])
->subject((string) trans('email.admin_test_subject'))
;
}
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function via(OwnerNotifiable $notifiable)
{
return ['mail'];
}
}

View File

@@ -0,0 +1,83 @@
<?php
/*
* TestNotification.php
* Copyright (c) 2022 james@firefly-iii.org
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace FireflyIII\Notifications\Test;
use FireflyIII\Notifications\Notifiables\OwnerNotifiable;
use FireflyIII\Notifications\ReturnsSettings;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Ntfy\Message;
use Wijourdil\NtfyNotificationChannel\Channels\NtfyChannel;
// use Illuminate\Notifications\Slack\SlackMessage;
/**
* Class TestNotification
*/
class OwnerTestNotificationNtfy extends Notification
{
use Queueable;
public OwnerNotifiable $owner;
public function __construct(OwnerNotifiable $owner)
{
$this->owner = $owner;
}
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*
* @param mixed $notifiable
*/
public function toArray($notifiable)
{
return [
];
}
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toNtfy(OwnerNotifiable $notifiable): Message
{
$settings = ReturnsSettings::getSettings('ntfy', 'owner', null);
$message = new Message();
$message->topic($settings['ntfy_topic']);
$message->title((string) trans('email.admin_test_subject'));
$message->body((string) trans('email.admin_test_message', ['channel' => 'ntfy']));
$message->tags(['white_check_mark']);
return $message;
}
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function via(OwnerNotifiable $notifiable)
{
return [NtfyChannel::class];
}
}

View File

@@ -0,0 +1,78 @@
<?php
/*
* TestNotification.php
* Copyright (c) 2022 james@firefly-iii.org
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace FireflyIII\Notifications\Test;
use FireflyIII\Notifications\Notifiables\OwnerNotifiable;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Log;
use NotificationChannels\Pushover\PushoverChannel;
use NotificationChannels\Pushover\PushoverMessage;
// use Illuminate\Notifications\Slack\SlackMessage;
/**
* Class TestNotification
*/
class OwnerTestNotificationPushover extends Notification
{
use Queueable;
private OwnerNotifiable $owner;
public function __construct(OwnerNotifiable $owner)
{
$this->owner = $owner;
}
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toArray(OwnerNotifiable $notifiable)
{
return [
];
}
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toPushover(OwnerNotifiable $notifiable): PushoverMessage
{
Log::debug('Now in toPushover()');
return PushoverMessage::create((string) trans('email.admin_test_message', ['channel' => 'Pushover']))
->title((string) trans('email.admin_test_subject'))
;
}
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function via(OwnerNotifiable $notifiable)
{
return [PushoverChannel::class];
}
}

View File

@@ -0,0 +1,73 @@
<?php
/*
* TestNotification.php
* Copyright (c) 2022 james@firefly-iii.org
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace FireflyIII\Notifications\Test;
use FireflyIII\Notifications\Notifiables\OwnerNotifiable;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;
// use Illuminate\Notifications\Slack\SlackMessage;
/**
* Class TestNotification
*/
class OwnerTestNotificationSlack extends Notification
{
use Queueable;
private OwnerNotifiable $owner;
public function __construct(OwnerNotifiable $owner)
{
$this->owner = $owner;
}
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toArray(OwnerNotifiable $notifiable)
{
return [
];
}
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function toSlack(OwnerNotifiable $notifiable)
{
return new SlackMessage()->content((string) trans('email.admin_test_subject'));
// return new SlackMessage()->text((string) trans('email.admin_test_subject'))->to($url);
}
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function via(OwnerNotifiable $notifiable)
{
return ['slack'];
}
}

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