Compare commits

...

100 Commits
3.0.9 ... 4.3

Author SHA1 Message Date
Dennis Smink
52ef42a81d Merge pull request #41 from ploi/filament-v4-upgrade
Filament V4 upgrade
2026-01-14 08:16:01 +01:00
Dennis
e225499905 Assets fix 2026-01-14 08:15:15 +01:00
Dennis
9522b28b9d wip 2025-12-29 08:02:21 +01:00
Dennis
e3b944f450 updates 2025-10-28 13:34:34 +01:00
Dennis
e197a915b3 Add useragent 2025-10-28 13:31:05 +01:00
Dennis
db1240c43f Composer format & run action 2025-08-13 20:49:47 +02:00
Dennis
732ed7ea43 Merge branch 'master' of https://github.com/ploi/ploi-core 2025-08-13 20:46:37 +02:00
Dennis
e776ae299a Use Laravel prompts 💬 2025-08-13 20:46:33 +02:00
Dennis Smink
b8c07cde53 Merge pull request #38 from jelleroorda/fix-support-close-reopen
Fix closing and reopening of support tickets.
2025-08-13 20:24:23 +02:00
Dennis Smink
6eb36a84af Merge pull request #37 from jelleroorda/fix-support-ticket-mail
Use the proper route for in new ticket received mail.
2025-08-13 20:23:34 +02:00
Jelle Roorda
9622a08b74 Fix closing and reopening of support tickets. 2025-08-13 17:49:47 +02:00
Jelle Roorda
4d11e3939a Use the proper route for in new ticket received mail. 2025-08-13 17:41:15 +02:00
Dennis Smink
592bc2b0f6 Merge pull request #36 from ploi/prepare-open-source
Open Source 🔥
2025-08-12 11:39:15 +02:00
Dennis
33ccdd1b2d remove traces 2025-08-12 11:23:34 +02:00
Dennis
065773fb6f wip 2025-08-12 08:32:52 +02:00
Dennis
e26a7c2a50 Vite upgrade 2025-08-12 07:44:19 +02:00
Dennis
022caacb24 wip 2025-08-12 07:39:20 +02:00
Dennis
b5da1367d0 wip 2025-08-12 07:37:58 +02:00
Dennis
175134233b wip 2025-08-11 13:53:57 +02:00
Dennis
072018b122 wip 2025-04-11 09:10:21 +02:00
Dennis
694254cd21 prod mix 2025-01-07 10:34:38 +01:00
Dennis
8b5c5734c1 fixes 2025-01-07 10:31:44 +01:00
Dennis
528868c1df wip 2025-01-07 10:19:12 +01:00
Dennis
ba2b932bb8 wip 2025-01-07 10:15:19 +01:00
Dennis
a986d4316e wip 2024-12-19 10:06:01 +01:00
Dennis Smink
f05206f940 Merge pull request #30 from ploi/sm/71-darkmode-bug-2
Added darkmode support for ticket
2024-12-19 09:54:05 +01:00
Dennis Smink
2d6a5fa770 Merge pull request #29 from ploi/sm/72-allow-custom-name-package-webhosting-on-invoice
Changed package name in invoice pdf
2024-12-19 09:53:50 +01:00
Dennis Smink
cd29843a88 Merge pull request #28 from ploi/sm/update
Upgrade Laravel 11 + Vue upgrade
2024-12-19 09:53:17 +01:00
Stan Menten
5a6e742fd9 Added darkmode support for ticket 2024-12-18 16:50:51 +01:00
Stan Menten
6a991aa320 Changed package name in invoice pdf 2024-12-18 16:46:28 +01:00
Stan Menten
1a61a01628 Added necessary migrations 2024-12-18 13:45:00 +01:00
Stan Menten
896564990d Big version update 2024-12-18 13:41:08 +01:00
Dennis
3fa5bb7df9 Catch default errors 2024-04-04 14:44:34 +02:00
Dennis
6b6435f71b Fixes 2024-03-19 13:12:15 +01:00
Dennis
a838f1a1da fx 2024-02-16 14:57:00 +01:00
Dennis
9535f03ff1 Vite 5 upgrade 2024-02-16 14:01:09 +01:00
Dennis
879fe90f18 wip 2024-02-16 13:55:50 +01:00
Dennis
9e79b4d3c1 package updates 2024-02-16 13:45:06 +01:00
Dennis
f8929e5622 wip 2024-02-12 08:22:46 +01:00
Dennis
6556cf017a wip 2023-11-22 12:50:30 +01:00
Dennis
514c010804 fix 2023-11-20 10:12:21 +01:00
Dennis
b3a5624ad4 fx 2023-11-20 10:08:48 +01:00
Dennis
3857aa33d2 wip 2023-11-20 10:07:09 +01:00
Dennis
c625a5c967 rename this method 2023-11-20 10:06:19 +01:00
Dennis
b4d35adfb4 wip 2023-10-18 08:19:48 +02:00
Dennis
0c1d970a9c cleaning 2023-10-17 16:22:45 +02:00
Dennis
3df600bcda wip 2023-10-07 09:50:11 +02:00
Dennis Smink
c9e0bb3bda Merge pull request #24 from ploi/rjs/provider-plans-per-package
RJS/Assign provider plans to specific packages
2023-10-02 11:14:26 +02:00
Ralph J. Smit
3aae5068ce Simplify 2023-09-28 20:58:54 +02:00
Ralph J. Smit
255353763f Add clarifying comment 2023-09-28 20:57:58 +02:00
Ralph J. Smit
99a49848ca Translations 2023-09-28 20:55:20 +02:00
Ralph J. Smit
def9e3c722 Style 2023-09-28 20:50:07 +02:00
Ralph J. Smit
6cc46cf652 Allow limiting provider plans per package 2023-09-28 20:48:12 +02:00
Ralph J. Smit
9ac72ffda8 Fix headerActions package resource 2023-09-28 13:36:32 +02:00
Dennis
3f1bdb1d8e wip 2023-09-28 13:29:45 +02:00
Dennis
f3d2b0c71f wip 2023-09-28 13:28:51 +02:00
Dennis
4071ba6d49 wip 2023-09-28 13:25:32 +02:00
Dennis Smink
4ec50d7ca1 Merge pull request #23 from ploi/rjs/filament-v3
RJS/Filament V3 upgrade
2023-09-28 13:23:37 +02:00
Ralph J. Smit
51b7f28634 Style 2023-09-28 12:15:55 +02:00
Ralph J. Smit
7f6b59cd4f WIP 2023-09-28 12:15:33 +02:00
Ralph J. Smit
80b4428b72 Filament V3 2023-09-28 12:12:04 +02:00
Dennis
010ecd63ac Merge branch 'develop' of https://github.com/ploi/ploi-core into develop 2023-09-28 08:21:51 +02:00
Dennis
741104de05 wip 2023-09-28 08:21:44 +02:00
Dennis Smink
5254ca3ebe Merge pull request #22 from ploi/rjs/fix-laravel-data
RJS/Upgrade to Laravel 10 – Fix testsuite / Laravel Data implementation
2023-09-27 08:44:45 +02:00
Ralph J. Smit
aefbb5be33 Put attributes on single line 2023-09-26 23:48:48 +02:00
Ralph J. Smit
d22bb52f35 Apply style 2023-09-26 23:47:24 +02:00
Ralph J. Smit
088d951bea Fix Laravel Data/testsuite 2023-09-26 23:44:58 +02:00
Dennis
01fe642a9d wip 2023-08-31 08:18:14 +02:00
Dennis
258e7127f7 wip upgrade 2023-04-03 10:45:59 +02:00
Dennis
7e44db0e56 wip 2023-02-02 11:26:10 +01:00
Dennis Smink
e1c07d84df Merge pull request #21 from ploi-deploy/update-label-tickets
Update SupportTicketResource.php
2023-01-30 11:17:00 +01:00
Dennis Smink
145a4af407 Update SupportTicketResource.php 2023-01-30 11:15:37 +01:00
Dennis
d1a7b6002a wip 2023-01-28 20:06:06 +01:00
Dennis
a9c0bdee34 remove 2023-01-28 20:05:20 +01:00
Dennis
604b535895 wip 2023-01-28 20:04:55 +01:00
Dennis
c67546b949 Merge branch 'develop'
# Conflicts:
#	public/build/manifest.json
2023-01-28 20:00:31 +01:00
Dennis Smink
0a45a1c8b2 Merge pull request #19 from ploi-deploy/nzd-currency
NZD currency
2023-01-28 20:00:02 +01:00
Dennis
3cd83ad69c nzd 2023-01-28 19:57:43 +01:00
GitHub Actions
d27df25b3c Updated build assets 2023-01-25 12:26:54 +00:00
Dennis
e55e984f98 wip 2023-01-25 13:25:23 +01:00
Dennis
5fbc0e0a37 Merge branch 'develop'
# Conflicts:
#	public/build/manifest.json
2023-01-25 13:22:45 +01:00
Dennis Smink
3313786480 Merge pull request #17 from ploi-deploy/fix-user-creation-admin
Fix user creation admin
2023-01-25 13:22:16 +01:00
Dennis Smink
5ed532535b Merge pull request #16 from ploi-deploy/package-updates
Package updates
2023-01-25 13:21:58 +01:00
Dennis
a8361f7b22 force 2023-01-25 13:21:26 +01:00
Dennis
a190ccf8dc wip 2023-01-25 13:01:32 +01:00
GitHub Actions
3f927f9ec1 Updated build assets 2023-01-24 14:46:10 +00:00
Dennis
33692960ff Merge branch 'develop'
# Conflicts:
#	public/build/manifest.json
2023-01-24 15:44:24 +01:00
Dennis
1f79a4e790 bugfix textarea 2023-01-24 15:44:08 +01:00
GitHub Actions
903e1cccc6 Updated build assets 2023-01-12 10:47:05 +00:00
Dennis
3f7f6206bd Merge branch 'develop'
# Conflicts:
#	public/build/assets/403-e96763bb.js
#	public/build/assets/403.184d0b9c.js
#	public/build/assets/403.9643c546.js
#	public/build/assets/404-d9c28ef0.js
#	public/build/assets/404.178f769b.js
#	public/build/assets/404.6a0f48e1.js
#	public/build/assets/Aliases-a6c1e5ac.js
#	public/build/assets/Aliases.516d8088.js
#	public/build/assets/Aliases.5dffda98.js
#	public/build/assets/Apps-9ee57278.js
#	public/build/assets/Apps.68116a71.js
#	public/build/assets/Apps.cf8f7e35.js
#	public/build/assets/Article-aed7d8cd.js
#	public/build/assets/Article.225d2cc5.js
#	public/build/assets/Article.50ee5004.js
#	public/build/assets/Billing-0334c2dc.js
#	public/build/assets/Billing.e20f325d.js
#	public/build/assets/Billing.ffbd6b67.js
#	public/build/assets/BillingError-e18727e6.js
#	public/build/assets/BillingError.540cc4df.js
#	public/build/assets/BillingError.f97e8473.js
#	public/build/assets/Button-938c2a59.js
#	public/build/assets/Button.3d31b0b0.js
#	public/build/assets/Button.482f5d57.js
#	public/build/assets/Certificates-c17def4c.js
#	public/build/assets/Certificates.b2e8d10a.js
#	public/build/assets/Certificates.b7a467e5.js
#	public/build/assets/Closed-15ff2b19.js
#	public/build/assets/Closed.33434c56.js
#	public/build/assets/Closed.c034ca5a.js
#	public/build/assets/ConfirmTwoFactorAuthentication-1e147d31.js
#	public/build/assets/ConfirmTwoFactorAuthentication.227845fb.js
#	public/build/assets/ConfirmTwoFactorAuthentication.442d0995.js
#	public/build/assets/Container-45f4da93.js
#	public/build/assets/Container.44bb93ee.js
#	public/build/assets/Container.f0b4c619.js
#	public/build/assets/Cronjobs-b059a4eb.js
#	public/build/assets/Cronjobs.669e6bc0.js
#	public/build/assets/Cronjobs.686bc7da.js
#	public/build/assets/Databases-e9eba7f6.js
#	public/build/assets/Databases.602e1197.js
#	public/build/assets/Databases.92234ef8.js
#	public/build/assets/Dns-a10c5265.js
#	public/build/assets/Dns.2ab43d8b.js
#	public/build/assets/Dns.4bdaed9c.js
#	public/build/assets/DropdownListItemButton-7877064b.js
#	public/build/assets/DropdownListItemButton.573e0a20.js
#	public/build/assets/DropdownListItemButton.ef103e7c.js
#	public/build/assets/Email-79a8d6e5.js
#	public/build/assets/Email.2626d110.js
#	public/build/assets/Email.e0bd114e.js
#	public/build/assets/EmptyImage-db7f150d.js
#	public/build/assets/EmptyImage.090e8b16.js
#	public/build/assets/EmptyImage.e1281e10.js
#	public/build/assets/Form-125b83ab.js
#	public/build/assets/Form.55885a08.js
#	public/build/assets/Form.e3b24233.js
#	public/build/assets/FormInput-f09111c3.js
#	public/build/assets/FormInput.541a08d4.js
#	public/build/assets/FormInput.7a518a32.js
#	public/build/assets/FormSelect-f8b36700.js
#	public/build/assets/FormSelect.02de001d.js
#	public/build/assets/FormSelect.19ff5254.js
#	public/build/assets/FormTextarea-a69c36b6.js
#	public/build/assets/FormTextarea.d5ee4b96.js
#	public/build/assets/FormTextarea.f69b0fba.js
#	public/build/assets/IconArrowDown-8b1a8522.js
#	public/build/assets/IconArrowDown.262b4357.js
#	public/build/assets/IconArrowDown.ef2fcbd6.js
#	public/build/assets/IconStorage-18f5d16d.js
#	public/build/assets/IconStorage.9205bc74.js
#	public/build/assets/IconStorage.b8642876.js
#	public/build/assets/Index-50b7f2f7.js
#	public/build/assets/Index-65445bf1.js
#	public/build/assets/Index-ae22c003.js
#	public/build/assets/Index-b1914fc4.js
#	public/build/assets/Index-c2ad6517.js
#	public/build/assets/Index-ed2777d6.js
#	public/build/assets/Index.3aca5d17.js
#	public/build/assets/Index.42d835dc.js
#	public/build/assets/Index.4db47acb.js
#	public/build/assets/Index.6d9c51dd.js
#	public/build/assets/Index.76408cb7.js
#	public/build/assets/Index.91265e25.js
#	public/build/assets/Index.b8cdaa18.js
#	public/build/assets/Index.c4ee4e5b.js
#	public/build/assets/Index.c83252d6.js
#	public/build/assets/Index.cdf5b851.js
#	public/build/assets/Index.d203e16d.js
#	public/build/assets/Index.fe71e493.js
#	public/build/assets/InstallationIncomplete-7a0ca111.js
#	public/build/assets/InstallationIncomplete.29d458e0.js
#	public/build/assets/InstallationIncomplete.5ce48727.js
#	public/build/assets/Integrations-02935c41.js
#	public/build/assets/Integrations.c7373676.js
#	public/build/assets/Integrations.e2d78e23.js
#	public/build/assets/Login-0b8af846.js
#	public/build/assets/Login.76b08252.js
#	public/build/assets/Login.9a6f1389.js
#	public/build/assets/MainLayout-8649910c.js
#	public/build/assets/MainLayout.26b583b0.js
#	public/build/assets/MainLayout.da88ac2b.js
#	public/build/assets/ModalContainer-87ab727e.js
#	public/build/assets/ModalContainer.08e5766d.js
#	public/build/assets/ModalContainer.c73e321c.js
#	public/build/assets/Pagination-3f4890e0.js
#	public/build/assets/Pagination.00232add.js
#	public/build/assets/Pagination.a75bec58.js
#	public/build/assets/PasswordCreation-5c8b1f8e.js
#	public/build/assets/PasswordCreation.67495dc1.js
#	public/build/assets/PasswordCreation.84b14c48.js
#	public/build/assets/Privacy-815696be.js
#	public/build/assets/Privacy.99e04234.js
#	public/build/assets/Privacy.fbf4a865.js
#	public/build/assets/Redirects-c6b81f3c.js
#	public/build/assets/Redirects.b99cf7cf.js
#	public/build/assets/Redirects.f8448783.js
#	public/build/assets/Register-0403a2cd.js
#	public/build/assets/Register.a42c47dd.js
#	public/build/assets/Register.d20a1a1b.js
#	public/build/assets/Reset-ddea9d5f.js
#	public/build/assets/Reset.8ac23802.js
#	public/build/assets/Reset.d5c232ca.js
#	public/build/assets/Security-4cd2a6e1.js
#	public/build/assets/Security.0d6b2b10.js
#	public/build/assets/Security.f1214994.js
#	public/build/assets/Settings-e7582a86.js
#	public/build/assets/Settings-efc6bba8.js
#	public/build/assets/Settings-f849221a.js
#	public/build/assets/Settings.168928d6.js
#	public/build/assets/Settings.1c4b0087.js
#	public/build/assets/Settings.52d8d7b4.js
#	public/build/assets/Settings.d667c946.js
#	public/build/assets/Settings.ed66a48f.js
#	public/build/assets/Settings.fadf33ce.js
#	public/build/assets/SettingsLayout-1f4f1c24.js
#	public/build/assets/SettingsLayout.6029cb54.js
#	public/build/assets/SettingsLayout.94ea8a51.js
#	public/build/assets/SettingsSegment-70fda3a9.js
#	public/build/assets/SettingsSegment.8f3bca2b.js
#	public/build/assets/SettingsSegment.e4964203.js
#	public/build/assets/Show-07f07f81.js
#	public/build/assets/Show-2e78bbbc.js
#	public/build/assets/Show-34adf7eb.js
#	public/build/assets/Show-3c892a01.js
#	public/build/assets/Show.0ad83d86.js
#	public/build/assets/Show.4d8ab56a.js
#	public/build/assets/Show.6eaded56.js
#	public/build/assets/Show.859411a2.js
#	public/build/assets/Show.931c3baa.js
#	public/build/assets/Show.ab8d88e8.js
#	public/build/assets/Show.c67e74f4.js
#	public/build/assets/Show.f31307aa.js
#	public/build/assets/TabBar-ad9b2a96.js
#	public/build/assets/TabBar.8304c776.js
#	public/build/assets/TabBar.e7e4c38d.js
#	public/build/assets/TableData-47a3f1fd.js
#	public/build/assets/TableData.4c8a41d7.js
#	public/build/assets/TableData.764d232d.js
#	public/build/assets/Tabs-38ad7844.js
#	public/build/assets/Tabs-66e3833f.js
#	public/build/assets/Tabs-7ea7e6ee.js
#	public/build/assets/Tabs.0753e723.js
#	public/build/assets/Tabs.08e17dfd.js
#	public/build/assets/Tabs.3e1b5c30.js
#	public/build/assets/Tabs.7520b2c6.js
#	public/build/assets/Tabs.9c81a864.js
#	public/build/assets/Tabs.bba69a14.js
#	public/build/assets/Terms-dff83575.js
#	public/build/assets/Terms.0c8ae423.js
#	public/build/assets/Terms.aae13061.js
#	public/build/assets/TextDivider-8ebb8335.js
#	public/build/assets/TextDivider.ab7f414c.js
#	public/build/assets/TextDivider.f06d5c66.js
#	public/build/assets/TopBar-149e0829.js
#	public/build/assets/TopBar-43058ee7.js
#	public/build/assets/TopBar-60517658.js
#	public/build/assets/TopBar-97b50929.js
#	public/build/assets/TopBar-fa507151.js
#	public/build/assets/TopBar-fdcb98f3.js
#	public/build/assets/TopBar.23526c20.js
#	public/build/assets/TopBar.3ed45d47.js
#	public/build/assets/TopBar.42fc17aa.js
#	public/build/assets/TopBar.487eeaa9.js
#	public/build/assets/TopBar.544193fc.js
#	public/build/assets/TopBar.6e42637b.js
#	public/build/assets/TopBar.8509fd3d.js
#	public/build/assets/TopBar.a427a47e.js
#	public/build/assets/TopBar.aecff8e2.js
#	public/build/assets/TopBar.bd25c71c.js
#	public/build/assets/TopBar.ddabe973.js
#	public/build/assets/TopBar.e6994b25.js
#	public/build/assets/TwoFactorAuthentication-d10b254e.js
#	public/build/assets/TwoFactorAuthentication.bf9d9f46.js
#	public/build/assets/TwoFactorAuthentication.c3412bf0.js
#	public/build/assets/app-9a1c122c.js
#	public/build/assets/app.67ed15d7.js
#	public/build/assets/app.997ea3ab.js
#	public/build/assets/confirm-eb12c83b.js
#	public/build/assets/confirm.450efa22.js
#	public/build/assets/confirm.91e5714b.js
#	public/build/assets/notification-c544471b.js
#	public/build/assets/notification.544829a1.js
#	public/build/assets/notification.fa833402.js
#	public/build/manifest.json
2023-01-12 11:45:17 +01:00
Dennis
be00824f59 wip 2023-01-12 11:44:17 +01:00
Dennis
eb4220adc9 wip 2022-12-19 11:39:21 +01:00
GitHub Actions
3562a60461 Updated build assets 2022-10-26 06:33:52 +00:00
Dennis
4d80f26519 Merge branch 'develop' 2022-10-26 08:32:42 +02:00
Dennis
29dc893806 remove this 2022-10-26 08:32:37 +02:00
Dennis
35abe4cfd7 Merge branch 'develop' 2022-10-26 07:56:58 +02:00
Dennis
275b359b53 w 2022-10-26 07:56:53 +02:00
Dennis
0be4f4cd94 Merge branch 'develop' 2022-10-26 07:54:10 +02:00
Dennis
2ffd09877e wip 2022-10-26 07:52:43 +02:00
Dennis
a5d2445e3f Fix #10 2022-10-26 07:27:31 +02:00
377 changed files with 74477 additions and 39940 deletions

0
.ai/mcp/mcp.json Normal file
View File

View File

@@ -7,7 +7,8 @@ APP_DEMO=false
APP_DATE_TIME_FORMAT="Y-m-d H:i:s" APP_DATE_TIME_FORMAT="Y-m-d H:i:s"
PLOI_TOKEN= PLOI_TOKEN=
PLOI_CORE_TOKEN=
IMPERSONATION=false
LOG_CHANNEL=stack LOG_CHANNEL=stack

View File

@@ -1,42 +0,0 @@
name: Run tests & build files
on:
push:
branches:
- master
jobs:
test:
name: Run tests
uses: ./.github/workflows/run-tests.yml
deploy:
needs: test
name: Prepare build assets
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Setup PHP with PECL extension
uses: shivammathur/setup-php@v2
with:
php-version: '8.1'
extensions: pcntl
- run: composer install
name: Install dependencies
- name: Set up Node
uses: actions/setup-node@v1
with:
node-version: '14.x'
- run: npm install
- run: npm run prod
- run: npm run prod:filament
- name: Commit build assets
run: |
git config --local user.email "actions@github.com"
git config --local user.name "GitHub Actions"
git add .
git commit -m "Updated build assets"
git push origin

View File

@@ -11,7 +11,7 @@ jobs:
fail-fast: false fail-fast: false
matrix: matrix:
os: [ubuntu-latest] os: [ubuntu-latest]
php: [8.1] php: [8.4]
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:

1
.gitignore vendored
View File

@@ -21,3 +21,4 @@ yarn-error.log
rr rr
.rr.yaml .rr.yaml
.DS_Store .DS_Store
.phpunit.cache

551
.junie/guidelines.md Normal file
View File

@@ -0,0 +1,551 @@
<laravel-boost-guidelines>
=== foundation rules ===
# Laravel Boost Guidelines
The Laravel Boost guidelines are specifically curated by Laravel maintainers for this application. These guidelines should be followed closely to enhance the user's satisfaction building Laravel applications.
## Foundational Context
This application is a Laravel application and its main Laravel ecosystems package & versions are below. You are an expert with them all. Ensure you abide by these specific packages & versions.
- php - 8.4.10
- filament/filament (FILAMENT) - v3
- inertiajs/inertia-laravel (INERTIA) - v2
- laravel/cashier (CASHIER) - v15
- laravel/framework (LARAVEL) - v11
- laravel/horizon (HORIZON) - v5
- laravel/octane (OCTANE) - v2
- laravel/prompts (PROMPTS) - v0
- livewire/livewire (LIVEWIRE) - v3
- tightenco/ziggy (ZIGGY) - v1
- laravel/dusk (DUSK) - v8
- laravel/mcp (MCP) - v0
- pestphp/pest (PEST) - v3
- phpunit/phpunit (PHPUNIT) - v11
- @inertiajs/vue3 (INERTIA) - v2
- tailwindcss (TAILWINDCSS) - v3
- vue (VUE) - v3
## Conventions
- You must follow all existing code conventions used in this application. When creating or editing a file, check sibling files for the correct structure, approach, naming.
- Use descriptive names for variables and methods. For example, `isRegisteredForDiscounts`, not `discount()`.
- Check for existing components to reuse before writing a new one.
## Verification Scripts
- Do not create verification scripts or tinker when tests cover that functionality and prove it works. Unit and feature tests are more important.
## Application Structure & Architecture
- Stick to existing directory structure - don't create new base folders without approval.
- Do not change the application's dependencies without approval.
## Frontend Bundling
- If the user doesn't see a frontend change reflected in the UI, it could mean they need to run `npm run build`, `npm run dev`, or `composer run dev`. Ask them.
## Replies
- Be concise in your explanations - focus on what's important rather than explaining obvious details.
## Documentation Files
- You must only create documentation files if explicitly requested by the user.
=== boost rules ===
## Laravel Boost
- Laravel Boost is an MCP server that comes with powerful tools designed specifically for this application. Use them.
## Artisan
- Use the `list-artisan-commands` tool when you need to call an Artisan command to double check the available parameters.
## URLs
- Whenever you share a project URL with the user you should use the `get-absolute-url` tool to ensure you're using the correct scheme, domain / IP, and port.
## Tinker / Debugging
- You should use the `tinker` tool when you need to execute PHP to debug code or query Eloquent models directly.
- Use the `database-query` tool when you only need to read from the database.
## Reading Browser Logs With the `browser-logs` Tool
- You can read browser logs, errors, and exceptions using the `browser-logs` tool from Boost.
- Only recent browser logs will be useful - ignore old logs.
## Searching Documentation (Critically Important)
- Boost comes with a powerful `search-docs` tool you should use before any other approaches. This tool automatically passes a list of installed packages and their versions to the remote Boost API, so it returns only version-specific documentation specific for the user's circumstance. You should pass an array of packages to filter on if you know you need docs for particular packages.
- The 'search-docs' tool is perfect for all Laravel related packages, including Laravel, Inertia, Livewire, Filament, Tailwind, Pest, Nova, Nightwatch, etc.
- You must use this tool to search for Laravel-ecosystem documentation before falling back to other approaches.
- Search the documentation before making code changes to ensure we are taking the correct approach.
- Use multiple, broad, simple, topic based queries to start. For example: `['rate limiting', 'routing rate limiting', 'routing']`.
- Do not add package names to queries - package information is already shared. For example, use `test resource table`, not `filament 4 test resource table`.
### Available Search Syntax
- You can and should pass multiple queries at once. The most relevant results will be returned first.
1. Simple Word Searches with auto-stemming - query=authentication - finds 'authenticate' and 'auth'
2. Multiple Words (AND Logic) - query=rate limit - finds knowledge containing both "rate" AND "limit"
3. Quoted Phrases (Exact Position) - query="infinite scroll" - Words must be adjacent and in that order
4. Mixed Queries - query=middleware "rate limit" - "middleware" AND exact phrase "rate limit"
5. Multiple Queries - queries=["authentication", "middleware"] - ANY of these terms
=== php rules ===
## PHP
- Always use curly braces for control structures, even if it has one line.
### Constructors
- Use PHP 8 constructor property promotion in `__construct()`.
- <code-snippet>public function __construct(public GitHub $github) { }</code-snippet>
- Do not allow empty `__construct()` methods with zero parameters.
### Type Declarations
- Always use explicit return type declarations for methods and functions.
- Use appropriate PHP type hints for method parameters.
<code-snippet name="Explicit Return Types and Method Params" lang="php">
protected function isAccessible(User $user, ?string $path = null): bool
{
...
}
</code-snippet>
## Comments
- Prefer PHPDoc blocks over comments. Never use comments within the code itself unless there is something _very_ complex going on.
## PHPDoc Blocks
- Add useful array shape type definitions for arrays when appropriate.
## Enums
- Typically, keys in an Enum should be TitleCase. For example: `FavoritePerson`, `BestLake`, `Monthly`.
=== tests rules ===
## Test Enforcement
- Every change must be programmatically tested. Write a new test or update an existing test, then run the affected tests to make sure they pass.
- Run the minimum number of tests needed to ensure code quality and speed. Use `php artisan test` with a specific filename or filter.
=== inertia-laravel/core rules ===
## Inertia Core
- Inertia.js components should be placed in the `resources/js/Pages` directory unless specified differently in the JS bundler (vite.config.js).
- Use `Inertia::render()` for server-side routing instead of traditional Blade views.
- Use `search-docs` for accurate guidance on all things Inertia.
<code-snippet lang="php" name="Inertia::render Example">
// routes/web.php example
Route::get('/users', function () {
return Inertia::render('Users/Index', [
'users' => User::all()
]);
});
</code-snippet>
=== inertia-laravel/v2 rules ===
## Inertia v2
- Make use of all Inertia features from v1 & v2. Check the documentation before making any changes to ensure we are taking the correct approach.
### Inertia v2 New Features
- Polling
- Prefetching
- Deferred props
- Infinite scrolling using merging props and `WhenVisible`
- Lazy loading data on scroll
### Deferred Props & Empty States
- When using deferred props on the frontend, you should add a nice empty state with pulsing / animated skeleton.
### Inertia Form General Guidance
- Build forms using the `useForm` helper. Use the code examples and `search-docs` tool with a query of `useForm helper` for guidance.
=== laravel/core rules ===
## Do Things the Laravel Way
- Use `php artisan make:` commands to create new files (i.e. migrations, controllers, models, etc.). You can list available Artisan commands using the `list-artisan-commands` tool.
- If you're creating a generic PHP class, use `php artisan make:class`.
- Pass `--no-interaction` to all Artisan commands to ensure they work without user input. You should also pass the correct `--options` to ensure correct behavior.
### Database
- Always use proper Eloquent relationship methods with return type hints. Prefer relationship methods over raw queries or manual joins.
- Use Eloquent models and relationships before suggesting raw database queries
- Avoid `DB::`; prefer `Model::query()`. Generate code that leverages Laravel's ORM capabilities rather than bypassing them.
- Generate code that prevents N+1 query problems by using eager loading.
- Use Laravel's query builder for very complex database operations.
### Model Creation
- When creating new models, create useful factories and seeders for them too. Ask the user if they need any other things, using `list-artisan-commands` to check the available options to `php artisan make:model`.
### APIs & Eloquent Resources
- For APIs, default to using Eloquent API Resources and API versioning unless existing API routes do not, then you should follow existing application convention.
### Controllers & Validation
- Always create Form Request classes for validation rather than inline validation in controllers. Include both validation rules and custom error messages.
- Check sibling Form Requests to see if the application uses array or string based validation rules.
### Queues
- Use queued jobs for time-consuming operations with the `ShouldQueue` interface.
### Authentication & Authorization
- Use Laravel's built-in authentication and authorization features (gates, policies, Sanctum, etc.).
### URL Generation
- When generating links to other pages, prefer named routes and the `route()` function.
### Configuration
- Use environment variables only in configuration files - never use the `env()` function directly outside of config files. Always use `config('app.name')`, not `env('APP_NAME')`.
### Testing
- When creating models for tests, use the factories for the models. Check if the factory has custom states that can be used before manually setting up the model.
- Faker: Use methods such as `$this->faker->word()` or `fake()->randomDigit()`. Follow existing conventions whether to use `$this->faker` or `fake()`.
- When creating tests, make use of `php artisan make:test [options] {name}` to create a feature test, and pass `--unit` to create a unit test. Most tests should be feature tests.
### Vite Error
- If you receive an "Illuminate\Foundation\ViteException: Unable to locate file in Vite manifest" error, you can run `npm run build` or ask the user to run `npm run dev` or `composer run dev`.
=== laravel/v11 rules ===
## Laravel 11
- Use the `search-docs` tool to get version specific documentation.
- This project upgraded from Laravel 10 without migrating to the new streamlined Laravel 11 file structure.
- This is **perfectly fine** and recommended by Laravel. Follow the existing structure from Laravel 10. We do not to need migrate to the Laravel 11 structure unless the user explicitly requests that.
### Laravel 10 Structure
- Middleware typically live in `app/Http/Middleware/` and service providers in `app/Providers/`.
- There is no `bootstrap/app.php` application configuration in a Laravel 10 structure:
- Middleware registration is in `app/Http/Kernel.php`
- Exception handling is in `app/Exceptions/Handler.php`
- Console commands and schedule registration is in `app/Console/Kernel.php`
- Rate limits likely exist in `RouteServiceProvider` or `app/Http/Kernel.php`
### Database
- When modifying a column, the migration must include all of the attributes that were previously defined on the column. Otherwise, they will be dropped and lost.
- Laravel 11 allows limiting eagerly loaded records natively, without external packages: `$query->latest()->limit(10);`.
### Models
- Casts can and likely should be set in a `casts()` method on a model rather than the `$casts` property. Follow existing conventions from other models.
### New Artisan Commands
- List Artisan commands using Boost's MCP tool, if available. New commands available in Laravel 11:
- `php artisan make:enum`
- `php artisan make:class `
- `php artisan make:interface `
=== livewire/core rules ===
## Livewire Core
- Use the `search-docs` tool to find exact version specific documentation for how to write Livewire & Livewire tests.
- Use the `php artisan make:livewire [Posts\CreatePost]` artisan command to create new components
- State should live on the server, with the UI reflecting it.
- All Livewire requests hit the Laravel backend, they're like regular HTTP requests. Always validate form data, and run authorization checks in Livewire actions.
## Livewire Best Practices
- Livewire components require a single root element.
- Use `wire:loading` and `wire:dirty` for delightful loading states.
- Add `wire:key` in loops:
```blade
@foreach ($items as $item)
<div wire:key="item-{{ $item->id }}">
{{ $item->name }}
</div>
@endforeach
```
- Prefer lifecycle hooks like `mount()`, `updatedFoo()` for initialization and reactive side effects:
<code-snippet name="Lifecycle hook examples" lang="php">
public function mount(User $user) { $this->user = $user; }
public function updatedSearch() { $this->resetPage(); }
</code-snippet>
## Testing Livewire
<code-snippet name="Example Livewire component test" lang="php">
Livewire::test(Counter::class)
->assertSet('count', 0)
->call('increment')
->assertSet('count', 1)
->assertSee(1)
->assertStatus(200);
</code-snippet>
<code-snippet name="Testing a Livewire component exists within a page" lang="php">
$this->get('/posts/create')
->assertSeeLivewire(CreatePost::class);
</code-snippet>
=== livewire/v3 rules ===
## Livewire 3
### Key Changes From Livewire 2
- These things changed in Livewire 2, but may not have been updated in this application. Verify this application's setup to ensure you conform with application conventions.
- Use `wire:model.live` for real-time updates, `wire:model` is now deferred by default.
- Components now use the `App\Livewire` namespace (not `App\Http\Livewire`).
- Use `$this->dispatch()` to dispatch events (not `emit` or `dispatchBrowserEvent`).
- Use the `components.layouts.app` view as the typical layout path (not `layouts.app`).
### New Directives
- `wire:show`, `wire:transition`, `wire:cloak`, `wire:offline`, `wire:target` are available for use. Use the documentation to find usage examples.
### Alpine
- Alpine is now included with Livewire, don't manually include Alpine.js.
- Plugins included with Alpine: persist, intersect, collapse, and focus.
### Lifecycle Hooks
- You can listen for `livewire:init` to hook into Livewire initialization, and `fail.status === 419` for the page expiring:
<code-snippet name="livewire:load example" lang="js">
document.addEventListener('livewire:init', function () {
Livewire.hook('request', ({ fail }) => {
if (fail && fail.status === 419) {
alert('Your session expired');
}
});
Livewire.hook('message.failed', (message, component) => {
console.error(message);
});
});
</code-snippet>
=== pest/core rules ===
## Pest
### Testing
- If you need to verify a feature is working, write or update a Unit / Feature test.
### Pest Tests
- All tests must be written using Pest. Use `php artisan make:test --pest {name}`.
- You must not remove any tests or test files from the tests directory without approval. These are not temporary or helper files - these are core to the application.
- Tests should test all of the happy paths, failure paths, and weird paths.
- Tests live in the `tests/Feature` and `tests/Unit` directories.
- Pest tests look and behave like this:
<code-snippet name="Basic Pest Test Example" lang="php">
it('is true', function () {
expect(true)->toBeTrue();
});
</code-snippet>
### Running Tests
- Run the minimal number of tests using an appropriate filter before finalizing code edits.
- To run all tests: `php artisan test`.
- To run all tests in a file: `php artisan test tests/Feature/ExampleTest.php`.
- To filter on a particular test name: `php artisan test --filter=testName` (recommended after making a change to a related file).
- When the tests relating to your changes are passing, ask the user if they would like to run the entire test suite to ensure everything is still passing.
### Pest Assertions
- When asserting status codes on a response, use the specific method like `assertForbidden` and `assertNotFound` instead of using `assertStatus(403)` or similar, e.g.:
<code-snippet name="Pest Example Asserting postJson Response" lang="php">
it('returns all', function () {
$response = $this->postJson('/api/docs', []);
$response->assertSuccessful();
});
</code-snippet>
### Mocking
- Mocking can be very helpful when appropriate.
- When mocking, you can use the `Pest\Laravel\mock` Pest function, but always import it via `use function Pest\Laravel\mock;` before using it. Alternatively, you can use `$this->mock()` if existing tests do.
- You can also create partial mocks using the same import or self method.
### Datasets
- Use datasets in Pest to simplify tests which have a lot of duplicated data. This is often the case when testing validation rules, so consider going with this solution when writing tests for validation rules.
<code-snippet name="Pest Dataset Example" lang="php">
it('has emails', function (string $email) {
expect($email)->not->toBeEmpty();
})->with([
'james' => 'james@laravel.com',
'taylor' => 'taylor@laravel.com',
]);
</code-snippet>
=== inertia-vue/core rules ===
## Inertia + Vue
- Vue components must have a single root element.
- Use `router.visit()` or `<Link>` for navigation instead of traditional links.
<code-snippet name="Inertia Client Navigation" lang="vue">
import { Link } from '@inertiajs/vue3'
<Link href="/">Home</Link>
</code-snippet>
=== inertia-vue/v2/forms rules ===
## Inertia + Vue Forms
<code-snippet name="Inertia Vue useForm example" lang="vue">
<script setup>
import { useForm } from '@inertiajs/vue3'
const form = useForm({
email: null,
password: null,
remember: false,
})
</script>
<template>
<form @submit.prevent="form.post('/login')">
<!-- email -->
<input type="text" v-model="form.email">
<div v-if="form.errors.email">{{ form.errors.email }}</div>
<!-- password -->
<input type="password" v-model="form.password">
<div v-if="form.errors.password">{{ form.errors.password }}</div>
<!-- remember me -->
<input type="checkbox" v-model="form.remember"> Remember Me
<!-- submit -->
<button type="submit" :disabled="form.processing">Login</button>
</form>
</template>
</code-snippet>
=== tailwindcss/core rules ===
## Tailwind Core
- Use Tailwind CSS classes to style HTML, check and use existing tailwind conventions within the project before writing your own.
- Offer to extract repeated patterns into components that match the project's conventions (i.e. Blade, JSX, Vue, etc..)
- Think through class placement, order, priority, and defaults - remove redundant classes, add classes to parent or child carefully to limit repetition, group elements logically
- You can use the `search-docs` tool to get exact examples from the official documentation when needed.
### Spacing
- When listing items, use gap utilities for spacing, don't use margins.
<code-snippet name="Valid Flex Gap Spacing Example" lang="html">
<div class="flex gap-8">
<div>Superior</div>
<div>Michigan</div>
<div>Erie</div>
</div>
</code-snippet>
### Dark Mode
- If existing pages and components support dark mode, new pages and components must support dark mode in a similar way, typically using `dark:`.
=== tailwindcss/v3 rules ===
## Tailwind 3
- Always use Tailwind CSS v3 - verify you're using only classes supported by this version.
=== filament/filament rules ===
## Filament
- Filament is used by this application, check how and where to follow existing application conventions.
- Filament is a Server-Driven UI (SDUI) framework for Laravel. It allows developers to define user interfaces in PHP using structured configuration objects. It is built on top of Livewire, Alpine.js, and Tailwind CSS.
- You can use the `search-docs` tool to get information from the official Filament documentation when needed. This is very useful for Artisan command arguments, specific code examples, testing functionality, relationship management, and ensuring you're following idiomatic practices.
- Utilize static `make()` methods for consistent component initialization.
### Artisan
- You must use the Filament specific Artisan commands to create new files or components for Filament. You can find these with the `list-artisan-commands` tool, or with `php artisan` and the `--help` option.
- Inspect the required options, always pass `--no-interaction`, and valid arguments for other options when applicable.
### Filament's Core Features
- Actions: Handle doing something within the application, often with a button or link. Actions encapsulate the UI, the interactive modal window, and the logic that should be executed when the modal window is submitted. They can be used anywhere in the UI and are commonly used to perform one-time actions like deleting a record, sending an email, or updating data in the database based on modal form input.
- Forms: Dynamic forms rendered within other features, such as resources, action modals, table filters, and more.
- Infolists: Read-only lists of data.
- Notifications: Flash notifications displayed to users within the application.
- Panels: The top-level container in Filament that can include all other features like pages, resources, forms, tables, notifications, actions, infolists, and widgets.
- Resources: Static classes that are used to build CRUD interfaces for Eloquent models. Typically live in `app/Filament/Resources`.
- Schemas: Represent components that define the structure and behavior of the UI, such as forms, tables, or lists.
- Tables: Interactive tables with filtering, sorting, pagination, and more.
- Widgets: Small component included within dashboards, often used for displaying data in charts, tables, or as a stat.
### Relationships
- Determine if you can use the `relationship()` method on form components when you need `options` for a select, checkbox, repeater, or when building a `Fieldset`:
<code-snippet name="Relationship example for Form Select" lang="php">
Forms\Components\Select::make('user_id')
->label('Author')
->relationship('author')
->required(),
</code-snippet>
## Testing
- It's important to test Filament functionality for user satisfaction.
- Ensure that you are authenticated to access the application within the test.
- Filament uses Livewire, so start assertions with `livewire()` or `Livewire::test()`.
### Example Tests
<code-snippet name="Filament Table Test" lang="php">
livewire(ListUsers::class)
->assertCanSeeTableRecords($users)
->searchTable($users->first()->name)
->assertCanSeeTableRecords($users->take(1))
->assertCanNotSeeTableRecords($users->skip(1))
->searchTable($users->last()->email)
->assertCanSeeTableRecords($users->take(-1))
->assertCanNotSeeTableRecords($users->take($users->count() - 1));
</code-snippet>
<code-snippet name="Filament Create Resource Test" lang="php">
livewire(CreateUser::class)
->fillForm([
'name' => 'Howdy',
'email' => 'howdy@example.com',
])
->call('create')
->assertNotified()
->assertRedirect();
assertDatabaseHas(User::class, [
'name' => 'Howdy',
'email' => 'howdy@example.com',
]);
</code-snippet>
<code-snippet name="Testing Multiple Panels (setup())" lang="php">
use Filament\Facades\Filament;
Filament::setCurrentPanel('app');
</code-snippet>
<code-snippet name="Calling an Action in a Test" lang="php">
livewire(EditInvoice::class, [
'invoice' => $invoice,
])->callAction('send');
expect($invoice->refresh())->isSent()->toBeTrue();
</code-snippet>
## Version 3 Changes To Focus On
- Resources are located in `app/Filament/Resources/` directory.
- Resource pages (List, Create, Edit) are auto-generated within the resource's directory - e.g., `app/Filament/Resources/PostResource/Pages/`.
- Forms use the `Forms\Components` namespace for form fields.
- Tables use the `Tables\Columns` namespace for table columns.
- A new `Filament\Forms\Components\RichEditor` component is available.
- Form and table schemas now use fluent method chaining.
- Added `php artisan filament:optimize` command for production optimization.
- Requires implementing `FilamentUser` contract for production access control.
</laravel-boost-guidelines>

11
.junie/mcp/mcp.json Normal file
View File

@@ -0,0 +1,11 @@
{
"mcpServers": {
"laravel-boost": {
"command": "/opt/homebrew/Cellar/php/8.4.10/bin/php",
"args": [
"/Users/dennissmink/Workspace/ploi-core/artisan",
"boost:mcp"
]
}
}
}

11
.mcp.json Normal file
View File

@@ -0,0 +1,11 @@
{
"mcpServers": {
"laravel-boost": {
"command": "php",
"args": [
"artisan",
"boost:mcp"
]
}
}
}

View File

@@ -15,4 +15,5 @@ return (new PhpCsFixer\Config)
'ordered_imports' => ['sort_algorithm' => 'length'], 'ordered_imports' => ['sort_algorithm' => 'length'],
'no_unused_imports' => true, 'no_unused_imports' => true,
]) ])
->setParallelConfig(PhpCsFixer\Runner\Parallel\ParallelConfigFactory::detect())
->setFinder($finder); ->setFinder($finder);

676
CLAUDE.md Normal file
View File

@@ -0,0 +1,676 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project Overview
Ploi Core is a Laravel-based webhosting management platform that allows users to launch their own webhosting service using ploi.io as the backend infrastructure.
## Essential Commands
### Development
```bash
# Start development server
npm run dev
# Build for production
npm run build
# Watch for changes
npm run watch
# Format PHP code
composer format
# Run tests
php artisan test
php artisan test --filter=TestName
# Run browser tests
php artisan dusk
# Clear all caches
php artisan cache:clear
php artisan config:clear
php artisan route:clear
php artisan view:clear
# Queue management
php artisan horizon
php artisan queue:work
```
### Database
```bash
# Run migrations
php artisan migrate
# Rollback migrations
php artisan migrate:rollback
# Fresh migration with seeders
php artisan migrate:fresh --seed
```
### Custom Artisan Commands
```bash
php artisan core:install # Initial installation
php artisan core:synchronize # Sync with Ploi API
php artisan core:cleanup # Clean up resources
php artisan core:trial # Manage trials
```
## Architecture Overview
### Technology Stack
- **Backend**: Laravel 11 (PHP 8.2+), Filament v3 admin panel
- **Frontend**: Vue 3 with Inertia.js, Tailwind CSS, Vite
- **Queue**: Laravel Horizon with Redis
- **Payments**: Laravel Cashier (Stripe)
- **Testing**: Pest PHP, Laravel Dusk
### Key Directories
- `app/Services/Ploi/` - Ploi.io API integration layer
- `app/Filament/` - Admin panel resources and pages
- `app/Http/Controllers/` - Web and API controllers
- `app/Jobs/` - Async queue jobs for Ploi API operations
- `resources/js/Pages/` - Inertia.js Vue pages
- `resources/js/components/` - Reusable Vue components
### Ploi API Integration
The application heavily integrates with the Ploi.io API. Key service class is at `app/Services/Ploi/Ploi.php`. All server/site management operations go through this API layer. Use queue jobs for long-running operations to avoid timeouts.
### Database Structure
Main entities: Users, Packages, Servers, Sites, Databases, Certificates, Cronjobs. Multi-tenancy through user-server-site relationships. Role-based access: admin, reseller, user.
### Frontend Architecture
- Inertia.js handles the Vue-Laravel bridge
- Pages are in `resources/js/Pages/` following Laravel route structure
- Shared data is passed via Inertia middleware
- Vuex store modules in `resources/js/store/`
- Form handling uses Inertia forms
### Testing Approach
- Feature tests use Pest PHP syntax
- Database tests use RefreshDatabase trait
- API calls should be mocked using Http::fake()
- Browser tests in `tests/Browser/` using Dusk
### Important Environment Variables
```
PLOI_TOKEN= # Ploi API token
APP_DEMO=false # Demo mode toggle
STRIPE_KEY= # Stripe public key
STRIPE_SECRET= # Stripe secret key
```
### Development Workflow
1. Always run `npm run dev` for frontend changes
2. Use queue workers for Ploi API operations
3. Clear caches when changing config or routes
4. Format code with `composer format` before commits
5. Test with `php artisan test` for unit/feature tests
### Common Patterns
- Use Actions (`app/Actions/`) for business logic
- API responses follow Laravel's resource pattern
- Filament resources handle admin CRUD operations
- Queue jobs for async Ploi API calls
- Service classes for external integrations
### Deployment
Production deployment uses the `update.sh` script which handles git pull, composer install, migrations, and cache clearing. Laravel Horizon manages queues in production.
===
<laravel-boost-guidelines>
=== foundation rules ===
# Laravel Boost Guidelines
The Laravel Boost guidelines are specifically curated by Laravel maintainers for this application. These guidelines should be followed closely to enhance the user's satisfaction building Laravel applications.
## Foundational Context
This application is a Laravel application and its main Laravel ecosystems package & versions are below. You are an expert with them all. Ensure you abide by these specific packages & versions.
- php - 8.4.10
- filament/filament (FILAMENT) - v3
- inertiajs/inertia-laravel (INERTIA) - v2
- laravel/cashier (CASHIER) - v15
- laravel/framework (LARAVEL) - v11
- laravel/horizon (HORIZON) - v5
- laravel/octane (OCTANE) - v2
- laravel/prompts (PROMPTS) - v0
- livewire/livewire (LIVEWIRE) - v3
- tightenco/ziggy (ZIGGY) - v1
- laravel/dusk (DUSK) - v8
- laravel/mcp (MCP) - v0
- pestphp/pest (PEST) - v3
- phpunit/phpunit (PHPUNIT) - v11
- @inertiajs/vue3 (INERTIA) - v2
- tailwindcss (TAILWINDCSS) - v3
- vue (VUE) - v3
## Conventions
- You must follow all existing code conventions used in this application. When creating or editing a file, check sibling files for the correct structure, approach, naming.
- Use descriptive names for variables and methods. For example, `isRegisteredForDiscounts`, not `discount()`.
- Check for existing components to reuse before writing a new one.
## Verification Scripts
- Do not create verification scripts or tinker when tests cover that functionality and prove it works. Unit and feature tests are more important.
## Application Structure & Architecture
- Stick to existing directory structure - don't create new base folders without approval.
- Do not change the application's dependencies without approval.
## Frontend Bundling
- If the user doesn't see a frontend change reflected in the UI, it could mean they need to run `npm run build`, `npm run dev`, or `composer run dev`. Ask them.
## Replies
- Be concise in your explanations - focus on what's important rather than explaining obvious details.
## Documentation Files
- You must only create documentation files if explicitly requested by the user.
=== boost rules ===
## Laravel Boost
- Laravel Boost is an MCP server that comes with powerful tools designed specifically for this application. Use them.
## Artisan
- Use the `list-artisan-commands` tool when you need to call an Artisan command to double check the available parameters.
## URLs
- Whenever you share a project URL with the user you should use the `get-absolute-url` tool to ensure you're using the correct scheme, domain / IP, and port.
## Tinker / Debugging
- You should use the `tinker` tool when you need to execute PHP to debug code or query Eloquent models directly.
- Use the `database-query` tool when you only need to read from the database.
## Reading Browser Logs With the `browser-logs` Tool
- You can read browser logs, errors, and exceptions using the `browser-logs` tool from Boost.
- Only recent browser logs will be useful - ignore old logs.
## Searching Documentation (Critically Important)
- Boost comes with a powerful `search-docs` tool you should use before any other approaches. This tool automatically passes a list of installed packages and their versions to the remote Boost API, so it returns only version-specific documentation specific for the user's circumstance. You should pass an array of packages to filter on if you know you need docs for particular packages.
- The 'search-docs' tool is perfect for all Laravel related packages, including Laravel, Inertia, Livewire, Filament, Tailwind, Pest, Nova, Nightwatch, etc.
- You must use this tool to search for Laravel-ecosystem documentation before falling back to other approaches.
- Search the documentation before making code changes to ensure we are taking the correct approach.
- Use multiple, broad, simple, topic based queries to start. For example: `['rate limiting', 'routing rate limiting', 'routing']`.
- Do not add package names to queries - package information is already shared. For example, use `test resource table`, not `filament 4 test resource table`.
### Available Search Syntax
- You can and should pass multiple queries at once. The most relevant results will be returned first.
1. Simple Word Searches with auto-stemming - query=authentication - finds 'authenticate' and 'auth'
2. Multiple Words (AND Logic) - query=rate limit - finds knowledge containing both "rate" AND "limit"
3. Quoted Phrases (Exact Position) - query="infinite scroll" - Words must be adjacent and in that order
4. Mixed Queries - query=middleware "rate limit" - "middleware" AND exact phrase "rate limit"
5. Multiple Queries - queries=["authentication", "middleware"] - ANY of these terms
=== php rules ===
## PHP
- Always use curly braces for control structures, even if it has one line.
### Constructors
- Use PHP 8 constructor property promotion in `__construct()`.
- <code-snippet>public function __construct(public GitHub $github) { }</code-snippet>
- Do not allow empty `__construct()` methods with zero parameters.
### Type Declarations
- Always use explicit return type declarations for methods and functions.
- Use appropriate PHP type hints for method parameters.
<code-snippet name="Explicit Return Types and Method Params" lang="php">
protected function isAccessible(User $user, ?string $path = null): bool
{
...
}
</code-snippet>
## Comments
- Prefer PHPDoc blocks over comments. Never use comments within the code itself unless there is something _very_ complex going on.
## PHPDoc Blocks
- Add useful array shape type definitions for arrays when appropriate.
## Enums
- Typically, keys in an Enum should be TitleCase. For example: `FavoritePerson`, `BestLake`, `Monthly`.
=== tests rules ===
## Test Enforcement
- Every change must be programmatically tested. Write a new test or update an existing test, then run the affected tests to make sure they pass.
- Run the minimum number of tests needed to ensure code quality and speed. Use `php artisan test` with a specific filename or filter.
=== inertia-laravel/core rules ===
## Inertia Core
- Inertia.js components should be placed in the `resources/js/Pages` directory unless specified differently in the JS bundler (vite.config.js).
- Use `Inertia::render()` for server-side routing instead of traditional Blade views.
- Use `search-docs` for accurate guidance on all things Inertia.
<code-snippet lang="php" name="Inertia::render Example">
// routes/web.php example
Route::get('/users', function () {
return Inertia::render('Users/Index', [
'users' => User::all()
]);
});
</code-snippet>
=== inertia-laravel/v2 rules ===
## Inertia v2
- Make use of all Inertia features from v1 & v2. Check the documentation before making any changes to ensure we are taking the correct approach.
### Inertia v2 New Features
- Polling
- Prefetching
- Deferred props
- Infinite scrolling using merging props and `WhenVisible`
- Lazy loading data on scroll
### Deferred Props & Empty States
- When using deferred props on the frontend, you should add a nice empty state with pulsing / animated skeleton.
### Inertia Form General Guidance
- Build forms using the `useForm` helper. Use the code examples and `search-docs` tool with a query of `useForm helper` for guidance.
=== laravel/core rules ===
## Do Things the Laravel Way
- Use `php artisan make:` commands to create new files (i.e. migrations, controllers, models, etc.). You can list available Artisan commands using the `list-artisan-commands` tool.
- If you're creating a generic PHP class, use `php artisan make:class`.
- Pass `--no-interaction` to all Artisan commands to ensure they work without user input. You should also pass the correct `--options` to ensure correct behavior.
### Database
- Always use proper Eloquent relationship methods with return type hints. Prefer relationship methods over raw queries or manual joins.
- Use Eloquent models and relationships before suggesting raw database queries
- Avoid `DB::`; prefer `Model::query()`. Generate code that leverages Laravel's ORM capabilities rather than bypassing them.
- Generate code that prevents N+1 query problems by using eager loading.
- Use Laravel's query builder for very complex database operations.
### Model Creation
- When creating new models, create useful factories and seeders for them too. Ask the user if they need any other things, using `list-artisan-commands` to check the available options to `php artisan make:model`.
### APIs & Eloquent Resources
- For APIs, default to using Eloquent API Resources and API versioning unless existing API routes do not, then you should follow existing application convention.
### Controllers & Validation
- Always create Form Request classes for validation rather than inline validation in controllers. Include both validation rules and custom error messages.
- Check sibling Form Requests to see if the application uses array or string based validation rules.
### Queues
- Use queued jobs for time-consuming operations with the `ShouldQueue` interface.
### Authentication & Authorization
- Use Laravel's built-in authentication and authorization features (gates, policies, Sanctum, etc.).
### URL Generation
- When generating links to other pages, prefer named routes and the `route()` function.
### Configuration
- Use environment variables only in configuration files - never use the `env()` function directly outside of config files. Always use `config('app.name')`, not `env('APP_NAME')`.
### Testing
- When creating models for tests, use the factories for the models. Check if the factory has custom states that can be used before manually setting up the model.
- Faker: Use methods such as `$this->faker->word()` or `fake()->randomDigit()`. Follow existing conventions whether to use `$this->faker` or `fake()`.
- When creating tests, make use of `php artisan make:test [options] {name}` to create a feature test, and pass `--unit` to create a unit test. Most tests should be feature tests.
### Vite Error
- If you receive an "Illuminate\Foundation\ViteException: Unable to locate file in Vite manifest" error, you can run `npm run build` or ask the user to run `npm run dev` or `composer run dev`.
=== laravel/v11 rules ===
## Laravel 11
- Use the `search-docs` tool to get version specific documentation.
- This project upgraded from Laravel 10 without migrating to the new streamlined Laravel 11 file structure.
- This is **perfectly fine** and recommended by Laravel. Follow the existing structure from Laravel 10. We do not to need migrate to the Laravel 11 structure unless the user explicitly requests that.
### Laravel 10 Structure
- Middleware typically live in `app/Http/Middleware/` and service providers in `app/Providers/`.
- There is no `bootstrap/app.php` application configuration in a Laravel 10 structure:
- Middleware registration is in `app/Http/Kernel.php`
- Exception handling is in `app/Exceptions/Handler.php`
- Console commands and schedule registration is in `app/Console/Kernel.php`
- Rate limits likely exist in `RouteServiceProvider` or `app/Http/Kernel.php`
### Database
- When modifying a column, the migration must include all of the attributes that were previously defined on the column. Otherwise, they will be dropped and lost.
- Laravel 11 allows limiting eagerly loaded records natively, without external packages: `$query->latest()->limit(10);`.
### Models
- Casts can and likely should be set in a `casts()` method on a model rather than the `$casts` property. Follow existing conventions from other models.
### New Artisan Commands
- List Artisan commands using Boost's MCP tool, if available. New commands available in Laravel 11:
- `php artisan make:enum`
- `php artisan make:class `
- `php artisan make:interface `
=== livewire/core rules ===
## Livewire Core
- Use the `search-docs` tool to find exact version specific documentation for how to write Livewire & Livewire tests.
- Use the `php artisan make:livewire [Posts\CreatePost]` artisan command to create new components
- State should live on the server, with the UI reflecting it.
- All Livewire requests hit the Laravel backend, they're like regular HTTP requests. Always validate form data, and run authorization checks in Livewire actions.
## Livewire Best Practices
- Livewire components require a single root element.
- Use `wire:loading` and `wire:dirty` for delightful loading states.
- Add `wire:key` in loops:
```blade
@foreach ($items as $item)
<div wire:key="item-{{ $item->id }}">
{{ $item->name }}
</div>
@endforeach
```
- Prefer lifecycle hooks like `mount()`, `updatedFoo()` for initialization and reactive side effects:
<code-snippet name="Lifecycle hook examples" lang="php">
public function mount(User $user) { $this->user = $user; }
public function updatedSearch() { $this->resetPage(); }
</code-snippet>
## Testing Livewire
<code-snippet name="Example Livewire component test" lang="php">
Livewire::test(Counter::class)
->assertSet('count', 0)
->call('increment')
->assertSet('count', 1)
->assertSee(1)
->assertStatus(200);
</code-snippet>
<code-snippet name="Testing a Livewire component exists within a page" lang="php">
$this->get('/posts/create')
->assertSeeLivewire(CreatePost::class);
</code-snippet>
=== livewire/v3 rules ===
## Livewire 3
### Key Changes From Livewire 2
- These things changed in Livewire 2, but may not have been updated in this application. Verify this application's setup to ensure you conform with application conventions.
- Use `wire:model.live` for real-time updates, `wire:model` is now deferred by default.
- Components now use the `App\Livewire` namespace (not `App\Http\Livewire`).
- Use `$this->dispatch()` to dispatch events (not `emit` or `dispatchBrowserEvent`).
- Use the `components.layouts.app` view as the typical layout path (not `layouts.app`).
### New Directives
- `wire:show`, `wire:transition`, `wire:cloak`, `wire:offline`, `wire:target` are available for use. Use the documentation to find usage examples.
### Alpine
- Alpine is now included with Livewire, don't manually include Alpine.js.
- Plugins included with Alpine: persist, intersect, collapse, and focus.
### Lifecycle Hooks
- You can listen for `livewire:init` to hook into Livewire initialization, and `fail.status === 419` for the page expiring:
<code-snippet name="livewire:load example" lang="js">
document.addEventListener('livewire:init', function () {
Livewire.hook('request', ({ fail }) => {
if (fail && fail.status === 419) {
alert('Your session expired');
}
});
Livewire.hook('message.failed', (message, component) => {
console.error(message);
});
});
</code-snippet>
=== pest/core rules ===
## Pest
### Testing
- If you need to verify a feature is working, write or update a Unit / Feature test.
### Pest Tests
- All tests must be written using Pest. Use `php artisan make:test --pest {name}`.
- You must not remove any tests or test files from the tests directory without approval. These are not temporary or helper files - these are core to the application.
- Tests should test all of the happy paths, failure paths, and weird paths.
- Tests live in the `tests/Feature` and `tests/Unit` directories.
- Pest tests look and behave like this:
<code-snippet name="Basic Pest Test Example" lang="php">
it('is true', function () {
expect(true)->toBeTrue();
});
</code-snippet>
### Running Tests
- Run the minimal number of tests using an appropriate filter before finalizing code edits.
- To run all tests: `php artisan test`.
- To run all tests in a file: `php artisan test tests/Feature/ExampleTest.php`.
- To filter on a particular test name: `php artisan test --filter=testName` (recommended after making a change to a related file).
- When the tests relating to your changes are passing, ask the user if they would like to run the entire test suite to ensure everything is still passing.
### Pest Assertions
- When asserting status codes on a response, use the specific method like `assertForbidden` and `assertNotFound` instead of using `assertStatus(403)` or similar, e.g.:
<code-snippet name="Pest Example Asserting postJson Response" lang="php">
it('returns all', function () {
$response = $this->postJson('/api/docs', []);
$response->assertSuccessful();
});
</code-snippet>
### Mocking
- Mocking can be very helpful when appropriate.
- When mocking, you can use the `Pest\Laravel\mock` Pest function, but always import it via `use function Pest\Laravel\mock;` before using it. Alternatively, you can use `$this->mock()` if existing tests do.
- You can also create partial mocks using the same import or self method.
### Datasets
- Use datasets in Pest to simplify tests which have a lot of duplicated data. This is often the case when testing validation rules, so consider going with this solution when writing tests for validation rules.
<code-snippet name="Pest Dataset Example" lang="php">
it('has emails', function (string $email) {
expect($email)->not->toBeEmpty();
})->with([
'james' => 'james@laravel.com',
'taylor' => 'taylor@laravel.com',
]);
</code-snippet>
=== inertia-vue/core rules ===
## Inertia + Vue
- Vue components must have a single root element.
- Use `router.visit()` or `<Link>` for navigation instead of traditional links.
<code-snippet name="Inertia Client Navigation" lang="vue">
import { Link } from '@inertiajs/vue3'
<Link href="/">Home</Link>
</code-snippet>
=== inertia-vue/v2/forms rules ===
## Inertia + Vue Forms
<code-snippet name="Inertia Vue useForm example" lang="vue">
<script setup>
import { useForm } from '@inertiajs/vue3'
const form = useForm({
email: null,
password: null,
remember: false,
})
</script>
<template>
<form @submit.prevent="form.post('/login')">
<!-- email -->
<input type="text" v-model="form.email">
<div v-if="form.errors.email">{{ form.errors.email }}</div>
<!-- password -->
<input type="password" v-model="form.password">
<div v-if="form.errors.password">{{ form.errors.password }}</div>
<!-- remember me -->
<input type="checkbox" v-model="form.remember"> Remember Me
<!-- submit -->
<button type="submit" :disabled="form.processing">Login</button>
</form>
</template>
</code-snippet>
=== tailwindcss/core rules ===
## Tailwind Core
- Use Tailwind CSS classes to style HTML, check and use existing tailwind conventions within the project before writing your own.
- Offer to extract repeated patterns into components that match the project's conventions (i.e. Blade, JSX, Vue, etc..)
- Think through class placement, order, priority, and defaults - remove redundant classes, add classes to parent or child carefully to limit repetition, group elements logically
- You can use the `search-docs` tool to get exact examples from the official documentation when needed.
### Spacing
- When listing items, use gap utilities for spacing, don't use margins.
<code-snippet name="Valid Flex Gap Spacing Example" lang="html">
<div class="flex gap-8">
<div>Superior</div>
<div>Michigan</div>
<div>Erie</div>
</div>
</code-snippet>
### Dark Mode
- If existing pages and components support dark mode, new pages and components must support dark mode in a similar way, typically using `dark:`.
=== tailwindcss/v3 rules ===
## Tailwind 3
- Always use Tailwind CSS v3 - verify you're using only classes supported by this version.
=== filament/filament rules ===
## Filament
- Filament is used by this application, check how and where to follow existing application conventions.
- Filament is a Server-Driven UI (SDUI) framework for Laravel. It allows developers to define user interfaces in PHP using structured configuration objects. It is built on top of Livewire, Alpine.js, and Tailwind CSS.
- You can use the `search-docs` tool to get information from the official Filament documentation when needed. This is very useful for Artisan command arguments, specific code examples, testing functionality, relationship management, and ensuring you're following idiomatic practices.
- Utilize static `make()` methods for consistent component initialization.
### Artisan
- You must use the Filament specific Artisan commands to create new files or components for Filament. You can find these with the `list-artisan-commands` tool, or with `php artisan` and the `--help` option.
- Inspect the required options, always pass `--no-interaction`, and valid arguments for other options when applicable.
### Filament's Core Features
- Actions: Handle doing something within the application, often with a button or link. Actions encapsulate the UI, the interactive modal window, and the logic that should be executed when the modal window is submitted. They can be used anywhere in the UI and are commonly used to perform one-time actions like deleting a record, sending an email, or updating data in the database based on modal form input.
- Forms: Dynamic forms rendered within other features, such as resources, action modals, table filters, and more.
- Infolists: Read-only lists of data.
- Notifications: Flash notifications displayed to users within the application.
- Panels: The top-level container in Filament that can include all other features like pages, resources, forms, tables, notifications, actions, infolists, and widgets.
- Resources: Static classes that are used to build CRUD interfaces for Eloquent models. Typically live in `app/Filament/Resources`.
- Schemas: Represent components that define the structure and behavior of the UI, such as forms, tables, or lists.
- Tables: Interactive tables with filtering, sorting, pagination, and more.
- Widgets: Small component included within dashboards, often used for displaying data in charts, tables, or as a stat.
### Relationships
- Determine if you can use the `relationship()` method on form components when you need `options` for a select, checkbox, repeater, or when building a `Fieldset`:
<code-snippet name="Relationship example for Form Select" lang="php">
Forms\Components\Select::make('user_id')
->label('Author')
->relationship('author')
->required(),
</code-snippet>
## Testing
- It's important to test Filament functionality for user satisfaction.
- Ensure that you are authenticated to access the application within the test.
- Filament uses Livewire, so start assertions with `livewire()` or `Livewire::test()`.
### Example Tests
<code-snippet name="Filament Table Test" lang="php">
livewire(ListUsers::class)
->assertCanSeeTableRecords($users)
->searchTable($users->first()->name)
->assertCanSeeTableRecords($users->take(1))
->assertCanNotSeeTableRecords($users->skip(1))
->searchTable($users->last()->email)
->assertCanSeeTableRecords($users->take(-1))
->assertCanNotSeeTableRecords($users->take($users->count() - 1));
</code-snippet>
<code-snippet name="Filament Create Resource Test" lang="php">
livewire(CreateUser::class)
->fillForm([
'name' => 'Howdy',
'email' => 'howdy@example.com',
])
->call('create')
->assertNotified()
->assertRedirect();
assertDatabaseHas(User::class, [
'name' => 'Howdy',
'email' => 'howdy@example.com',
]);
</code-snippet>
<code-snippet name="Testing Multiple Panels (setup())" lang="php">
use Filament\Facades\Filament;
Filament::setCurrentPanel('app');
</code-snippet>
<code-snippet name="Calling an Action in a Test" lang="php">
livewire(EditInvoice::class, [
'invoice' => $invoice,
])->callAction('send');
expect($invoice->refresh())->isSent()->toBeTrue();
</code-snippet>
## Version 3 Changes To Focus On
- Resources are located in `app/Filament/Resources/` directory.
- Resource pages (List, Create, Edit) are auto-generated within the resource's directory - e.g., `app/Filament/Resources/PostResource/Pages/`.
- Forms use the `Forms\Components` namespace for form fields.
- Tables use the `Tables\Columns` namespace for table columns.
- A new `Filament\Forms\Components\RichEditor` component is available.
- Form and table schemas now use fluent method chaining.
- Added `php artisan filament:optimize` command for production optimization.
- Requires implementing `FilamentUser` contract for production access control.
</laravel-boost-guidelines>

View File

@@ -1,6 +1,6 @@
# Ploi Core # Ploi Core
With Ploi Core, you'll power-launch your webhosting company. With Ploi Core, you'll power-launch your webhosting company.
Using the ploi.io system as backbone you will be able to serve your customers your custom panel & feeling. Using the ploi.io system as backbone you will be able to serve your customers your custom panel & feeling.
<p align="center"><img src="https://ploi-core.io/images/og.jpg" width="100%"></p> <p align="center"><img src="https://ploi-core.io/images/og.jpg" width="100%"></p>
@@ -17,4 +17,4 @@ https://ploi.io
The contribution guide can be found inside our documentation: The contribution guide can be found inside our documentation:
https://docs.ploi-core.io/getting-started/contribution-guide https://docs.ploi-core.io/261-getting-started/639-contribution-guide

View File

@@ -2,30 +2,59 @@
namespace App\Actions\Server; namespace App\Actions\Server;
use Throwable;
use App\Models\Server; use App\Models\Server;
use App\Services\Ploi\Ploi; use App\Services\Ploi\Ploi;
use Filament\Notifications\Notification; use Filament\Notifications\Notification;
class SynchronizeServerAction class SynchronizeServerAction
{ {
public function execute(int $ploiServerId): Server public function execute(int $ploiServerId): Server|null
{ {
$serverData = Ploi::make()->server()->get($ploiServerId)->getData(); try {
$serverData = Ploi::make()->server()->get($ploiServerId)->getData();
} catch (Throwable $exception) {
Notification::make()
->title('An error has occurred: ' . $exception->getMessage())
->danger()
->send();
$server = Server::query() return null;
->updateOrCreate([ }
'ploi_id' => $serverData->id,
], [ if (!$serverData) {
'status' => $serverData->status, Notification::make()
'name' => $serverData->name, ->title('Server synchronization')
'ip' => $serverData->ip_address, ->body('It was not possible to synchronize servers, it seems the API key has the wrong scopes. Please make sure the Ploi API key you\'ve entered has all the scopes enabled.')
'ssh_port' => $serverData->ssh_port, ->danger()
'internal_ip' => $serverData->internal_ip, ->send();
'available_php_versions' => $serverData->installed_php_versions,
]); return null;
}
try {
$server = Server::query()
->updateOrCreate([
'ploi_id' => $serverData->id,
], [
'status' => $serverData->status,
'name' => $serverData->name,
'ip' => $serverData->ip_address,
'ssh_port' => $serverData->ssh_port,
'internal_ip' => $serverData->internal_ip,
'available_php_versions' => $serverData->installed_php_versions,
]);
} catch (Throwable $exception) {
Notification::make()
->title('An error has occurred: ' . $exception->getMessage())
->danger()
->send();
return null;
}
Notification::make() Notification::make()
->body(__('Server :server synchronized successfully.', ['server' => $server->name])) ->title(__('Server :server synchronized successfully.', ['server' => $server->name]))
->success() ->success()
->send(); ->send();

View File

@@ -46,7 +46,7 @@ class SynchronizeSiteAction
} }
Notification::make() Notification::make()
->body(__('Site :site synchronized successfully.', ['site' => $site->domain])) ->title(__('Site :site synchronized successfully.', ['site' => $site->domain]))
->success() ->success()
->send(); ->send();

View File

@@ -2,6 +2,7 @@
namespace App\Casts; namespace App\Casts;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes; use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
class Encrypted implements CastsAttributes class Encrypted implements CastsAttributes
@@ -9,7 +10,7 @@ class Encrypted implements CastsAttributes
/** /**
* Cast the given value. * Cast the given value.
* *
* @param \Illuminate\Database\Eloquent\Model $model * @param Model $model
* @param string $key * @param string $key
* @param mixed $value * @param mixed $value
* @param array $attributes * @param array $attributes
@@ -23,7 +24,7 @@ class Encrypted implements CastsAttributes
/** /**
* Prepare the given value for storage. * Prepare the given value for storage.
* *
* @param \Illuminate\Database\Eloquent\Model $model * @param Model $model
* @param string $key * @param string $key
* @param array $value * @param array $value
* @param array $attributes * @param array $attributes

View File

@@ -2,6 +2,7 @@
namespace App\Casts; namespace App\Casts;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes; use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
class PermissionCast implements CastsAttributes class PermissionCast implements CastsAttributes
@@ -9,7 +10,7 @@ class PermissionCast implements CastsAttributes
/** /**
* Cast the given value. * Cast the given value.
* *
* @param \Illuminate\Database\Eloquent\Model $model * @param Model $model
* @param string $key * @param string $key
* @param mixed $value * @param mixed $value
* @param array $attributes * @param array $attributes
@@ -31,7 +32,7 @@ class PermissionCast implements CastsAttributes
/** /**
* Prepare the given value for storage. * Prepare the given value for storage.
* *
* @param \Illuminate\Database\Eloquent\Model $model * @param Model $model
* @param string $key * @param string $key
* @param array $value * @param array $value
* @param array $attributes * @param array $attributes

View File

@@ -11,9 +11,19 @@ use Illuminate\Support\Arr;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use App\Services\VersionChecker; use App\Services\VersionChecker;
use function Laravel\Prompts\info;
use function Laravel\Prompts\note;
use function Laravel\Prompts\spin;
use function Laravel\Prompts\text;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use function Laravel\Prompts\error;
use function Laravel\Prompts\intro;
use function Laravel\Prompts\outro;
use function Laravel\Prompts\select;
use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Artisan; use function Laravel\Prompts\confirm;
use function Laravel\Prompts\warning;
use function Laravel\Prompts\password;
class Install extends Command class Install extends Command
{ {
@@ -25,29 +35,34 @@ class Install extends Command
public function handle() public function handle()
{ {
$this->init(); try {
$this->intro(); $this->init();
$this->isInstalled(); $this->intro();
$this->checkApplicationKey(); $this->isInstalled();
$this->checkDatabaseConnection(); $this->checkApplicationKey();
$this->runDatabaseMigrations(); $this->checkDatabaseConnection();
$this->checkCredentials(); $this->runDatabaseMigrations();
$this->askAboutAdministrationAccount(); $this->checkCredentials();
$this->askAboutDefaultPackages(); $this->askAboutAdministrationAccount();
$this->checkApplicationUrl(); $this->askAboutDefaultPackages();
$this->createInstallationFile(); $this->checkApplicationUrl();
$this->linkStorage(); $this->createInstallationFile();
$this->linkStorage();
$this->info('Success! Installation has finished.'); outro('🎉 Installation completed successfully!');
$this->line(' ');
$this->writeSeparationLine(); note(
$this->info('Make sure to also setup emailing, the cronjob and the queue worker.'); "Next steps:\n\n" .
$this->line(' '); "📧 Setup email: https://docs.ploi-core.io/261-getting-started/918-setting-up-email\n" .
$this->info('Setting up emailing: https://docs.ploi-core.io/getting-started/setting-up-email'); "⚙️ Setup cron & queue: https://docs.ploi-core.io/261-getting-started/638-installation\n\n" .
$this->info('Setting up cronjob & queue worker: https://docs.ploi-core.io/getting-started/installation'); "Visit your platform at: " . env('APP_URL')
$this->writeSeparationLine(); );
$this->line(' ');
$this->info('Visit your platform at ' . env('APP_URL')); return Command::SUCCESS;
} catch (Exception $e) {
error('Installation failed: ' . $e->getMessage());
return Command::FAILURE;
}
} }
protected function init() protected function init()
@@ -58,96 +73,122 @@ class Install extends Command
protected function askAboutAdministrationAccount() protected function askAboutAdministrationAccount()
{ {
if (!User::query()->where('role', User::ADMIN)->count()) { if (!User::query()->where('role', User::ADMIN)->count()) {
$this->info('Let\'s start by setting up your administration account.'); note('Let\'s set up your administration account');
$name = $this->ask('What is your name', $this->company['user_name']); $name = text(
$email = $this->ask('What is your e-mail address', $this->company['email']); label: 'What is your name?',
$password = $this->secret('What password do you desire'); default: $this->company['user_name'],
required: true
);
$check = User::where('email', $email)->count(); $email = text(
label: 'What is your email address?',
default: $this->company['email'],
required: true,
validate: fn (string $value) => match (true) {
!filter_var($value, FILTER_VALIDATE_EMAIL) => 'Please enter a valid email address.',
User::where('email', $value)->exists() => 'This email is already registered in the system.',
default => null
}
);
if ($check) { $password = password(
$this->line(''); label: 'Choose a secure password',
$this->comment('This user is already present in your system, please refresh your database or use different credentials.'); required: true,
$this->comment('Aborting installation..'); validate: fn (string $value) => match (true) {
strlen($value) < 8 => 'Password must be at least 8 characters.',
default => null
}
);
exit(); spin(
} function () use ($name, $email, $password) {
User::forceCreate([
'name' => $name,
'email' => $email,
'password' => $password,
'role' => User::ADMIN
]);
},
'Creating administrator account...'
);
User::forceCreate([ info('✓ Administrator account created successfully');
'name' => $name,
'email' => $email,
'password' => $password,
'role' => User::ADMIN
]);
} else { } else {
$this->line('Already found a administrator user in your system. Use that user to login.'); note('Administrator account already exists. Use existing credentials to login.');
} }
} }
protected function askAboutDefaultPackages() protected function askAboutDefaultPackages()
{ {
$basicPackages = $this->confirm( $createPackages = confirm(
'Do you want to create the basic packages which you can edit later?', label: 'Would you like to create default packages?',
true default: true,
hint: 'Basic (5 sites), Professional (30 sites), and Unlimited packages'
); );
if (!$basicPackages) { if (!$createPackages) {
return false; return false;
} }
Package::create([ spin(
'name' => 'Basic', function () {
'maximum_sites' => 5, Package::create([
'site_permissions' => [ 'name' => 'Basic',
'create' => true, 'maximum_sites' => 5,
'update' => true, 'site_permissions' => [
'delete' => true 'create' => true,
], 'update' => true,
'server_permissions' => [ 'delete' => true
'create' => false, ],
'update' => false, 'server_permissions' => [
'delete' => false 'create' => false,
] 'update' => false,
]); 'delete' => false
]
]);
Package::create([ Package::create([
'name' => 'Professional', 'name' => 'Professional',
'maximum_sites' => 30, 'maximum_sites' => 30,
'site_permissions' => [ 'site_permissions' => [
'create' => true, 'create' => true,
'update' => true, 'update' => true,
'delete' => true 'delete' => true
], ],
'server_permissions' => [ 'server_permissions' => [
'create' => false, 'create' => false,
'update' => false, 'update' => false,
'delete' => false 'delete' => false
] ]
]); ]);
Package::create([ Package::create([
'name' => 'Unlimited', 'name' => 'Unlimited',
'maximum_sites' => 0, 'maximum_sites' => 0,
'site_permissions' => [ 'site_permissions' => [
'create' => true, 'create' => true,
'update' => true, 'update' => true,
'delete' => true 'delete' => true
], ],
'server_permissions' => [ 'server_permissions' => [
'create' => false, 'create' => false,
'update' => false, 'update' => false,
'delete' => false 'delete' => false
] ]
]); ]);
},
'Creating default packages...'
);
info('✓ Created 3 default packages');
} }
protected function getCompany($ploiCoreKey, $token) protected function getCompany($token)
{ {
$response = Http::withHeaders([ $response = Http::withHeaders([
'Accept' => 'application/json', 'Accept' => 'application/json',
'Content-Type' => 'application/json', 'Content-Type' => 'application/json'
'X-Ploi-Core-Key' => $ploiCoreKey
]) ])
->withToken($token) ->withToken($token)
->get((new Ploi)->url . 'ping'); ->get((new Ploi)->url . 'ping');
@@ -170,28 +211,26 @@ class Install extends Command
protected function intro() protected function intro()
{ {
$this->writeSeparationLine(); intro('🚀 Ploi Core Installation');
$this->line('Ploi Core Installation');
$this->line('Ploi Core version: ' . $this->versionChecker->currentVersion); note(
$this->line('Ploi Core remote: ' . $this->versionChecker->remoteVersion); "Ploi Core v{$this->versionChecker->currentVersion} (Remote: v{$this->versionChecker->remoteVersion})\n" .
$this->line('Laravel version: ' . app()->version()); "Laravel v" . app()->version() . " | PHP v" . trim(phpversion()) . "\n\n" .
$this->line('PHP version: ' . trim(phpversion())); "Website: https://ploi-core.io\n" .
$this->line(' '); "E-mail: core@ploi.io\n" .
$this->line('Website: https://ploi-core.io'); "Terms: https://ploi-core.io/terms"
$this->line('E-mail: core@ploi.io'); );
$this->line('Terms of service: https://ploi-core.io/terms');
$this->writeSeparationLine();
$this->line('');
} }
protected function isInstalled() protected function isInstalled()
{ {
if (file_exists(storage_path($this->installationFile)) && !$this->option('force')) { if (file_exists(storage_path($this->installationFile)) && !$this->option('force')) {
$this->line(''); warning('Ploi Core has already been installed before.');
$this->comment('Ploi Core has already been installed before.'); error(
$this->comment('If you still want to start installation, remove this file to continue: ./storage/' . $this->installationFile); "To reinstall, either:\n" .
$this->comment('Aborting installation..'); "• Remove the file: ./storage/{$this->installationFile}\n" .
"• Or run with --force flag"
);
exit(); exit();
} }
@@ -201,138 +240,215 @@ class Install extends Command
protected function checkApplicationKey(): void protected function checkApplicationKey(): void
{ {
if (!config('app.key')) { if (!config('app.key')) {
$this->call('key:generate'); spin(
fn () => $this->call('key:generate', [], $this->getOutput()),
$this->info('Application key has been set'); 'Generating application key...'
);
info('✓ Application key has been set');
} }
} }
protected function checkApplicationUrl() protected function checkApplicationUrl()
{ {
// Ask about URL $url = text(
$url = $this->ask('What URL is this platform using?', env('APP_URL')); label: 'What URL will this platform use?',
default: env('APP_URL', 'https://example.com'),
required: true,
validate: fn (string $value) => match (true) {
!filter_var($value, FILTER_VALIDATE_URL) => 'Please enter a valid URL.',
!str_starts_with($value, 'http://') && !str_starts_with($value, 'https://') => 'URL must start with http:// or https://',
default => null
},
hint: 'Include the protocol (http:// or https://)'
);
$this->writeToEnvironmentFile('APP_URL', $url); try {
$this->writeToEnvironmentFile('APP_URL', $url);
info('✓ Application URL configured');
} catch (Exception $e) {
error('Failed to save application URL: ' . $e->getMessage());
exit(1);
}
} }
protected function createInstallationFile() protected function createInstallationFile()
{ {
file_put_contents(storage_path($this->installationFile), json_encode($this->getInstallationPayload(), JSON_PRETTY_PRINT)); try {
$path = storage_path($this->installationFile);
$content = json_encode($this->getInstallationPayload(), JSON_PRETTY_PRINT);
if (file_put_contents($path, $content) === false) {
error('Failed to create installation file');
exit(1);
}
info('✓ Installation marker created');
} catch (Exception $e) {
error('Error creating installation file: ' . $e->getMessage());
exit(1);
}
} }
protected function linkStorage() protected function linkStorage()
{ {
Artisan::call('storage:link'); // Create storage symlink
$publicPath = public_path('storage');
$storagePath = storage_path('app/public');
// Remove existing symlink if it exists
if (is_link($publicPath)) {
unlink($publicPath);
}
// Create new symlink
if (!file_exists($publicPath)) {
try {
symlink($storagePath, $publicPath);
info('✓ Storage symlink created');
} catch (Exception $e) {
warning('Could not create storage symlink (may need manual creation)');
}
} else {
info('✓ Storage path already exists');
}
} }
protected function createDatabaseCredentials(): bool protected function createDatabaseCredentials(): bool
{ {
$storeCredentials = $this->confirm( $storeCredentials = confirm(
'Unable to connect to your database. Would you like to enter your credentials now?', label: 'Would you like to configure database credentials now?',
true default: true
); );
if (!$storeCredentials) { if (!$storeCredentials) {
return false; return false;
} }
$connection = $this->choice('Type', ['mysql', 'pgsql'], 0); $connection = select(
label: 'Select database type',
options: [
'mysql' => 'MySQL / MariaDB',
'pgsql' => 'PostgreSQL'
],
default: 'mysql'
);
$defaultPort = $connection === 'mysql' ? '3306' : '5432';
$variables = [ $variables = [
'DB_CONNECTION' => $connection, 'DB_CONNECTION' => $connection,
'DB_HOST' => $this->anticipate( 'DB_HOST' => text(
'Host', label: 'Database host',
['127.0.0.1', 'localhost'], default: config("database.connections.{$connection}.host", '127.0.0.1'),
config("database.connections.{$connection}.host", '127.0.0.1') required: true,
hint: 'Usually 127.0.0.1 or localhost'
), ),
'DB_PORT' => $this->ask( 'DB_PORT' => text(
'Port', label: 'Database port',
config("database.connections.{$connection}.port", '3306') default: config("database.connections.{$connection}.port", $defaultPort),
required: true
), ),
'DB_DATABASE' => $this->ask( 'DB_DATABASE' => text(
'Database', label: 'Database name',
config("database.connections.{$connection}.database") default: config("database.connections.{$connection}.database", 'ploi_core'),
required: true
), ),
'DB_USERNAME' => $this->ask( 'DB_USERNAME' => text(
'Username', label: 'Database username',
config("database.connections.{$connection}.username") default: config("database.connections.{$connection}.username", 'root'),
required: true
), ),
'DB_PASSWORD' => $this->secret( 'DB_PASSWORD' => password(
'Password', label: 'Database password',
config("database.connections.{$connection}.password") hint: 'Leave empty if no password is set'
), ) ?: '',
]; ];
$this->persistVariables($variables); spin(
fn () => $this->persistVariables($variables),
'Saving database configuration...'
);
return true; return true;
} }
protected function checkCredentials() protected function checkCredentials()
{ {
do { $ploiApiToken = text(
$ploiApiToken = $this->ask('Enter the Ploi API token', env('PLOI_TOKEN')); label: 'Enter your Ploi API token',
} while (empty($ploiApiToken)); default: env('PLOI_TOKEN'),
required: true,
hint: 'You can find this in your Ploi account settings'
);
do { $this->company = spin(
$ploiCoreKey = $this->ask('Enter the Ploi Core key', env('PLOI_CORE_TOKEN')); fn () => $this->getCompany($ploiApiToken),
} while (empty($ploiCoreKey)); 'Authenticating with Ploi API...'
);
$this->company = $this->getCompany($ploiCoreKey, $ploiApiToken);
if (!$this->company) { if (!$this->company) {
$this->error('Could not authenticate with ploi.io, please retry by running this command again.'); error('Could not authenticate with ploi.io');
exit(); exit();
} }
if (isset($this->company['error'])) { if (isset($this->company['error'])) {
$this->error($this->company['error']); error($this->company['error']);
exit(); exit();
} }
if ($this->company['user']['subscription'] !== 'unlimited') { if ($this->company['user']['subscription'] !== 'unlimited') {
$this->error('Your subscription does not cover the usage of Ploi Core. Please upgrade your subscription to Unlimited.'); error('Your Ploi subscription does not support Ploi Core.');
warning('Please upgrade to the Unlimited plan at https://ploi.io');
exit(); exit();
} }
info('✓ Successfully authenticated with Ploi');
$this->writeToEnvironmentFile('PLOI_TOKEN', $ploiApiToken); $this->writeToEnvironmentFile('PLOI_TOKEN', $ploiApiToken);
$this->writeToEnvironmentFile('PLOI_CORE_TOKEN', $ploiCoreKey);
$name = $this->ask('What is the name of your company? (Press enter to keep the name here)', $this->company['name']); $name = text(
label: 'What is the name of your company?',
default: $this->company['name'],
required: true
);
$this->writeToEnvironmentFile('APP_NAME', $name); $this->writeToEnvironmentFile('APP_NAME', $name);
setting(['name' => $name]); setting(['name' => $name]);
} }
protected function runDatabaseMigrations() protected function runDatabaseMigrations()
{ {
$this->info('Running database migrations..'); spin(
$this->call('migrate', ['--force' => true]); fn () => $this->call('migrate', ['--force' => true], $this->getOutput()),
$this->info('Database migrations successful'); 'Running database migrations...'
);
info('✓ Database migrations completed');
} }
protected function checkDatabaseConnection(): void protected function checkDatabaseConnection(): void
{ {
try { try {
DB::connection()->getPdo(); spin(
$this->info('Database connection successful.'); fn () => DB::connection()->getPdo(),
'Testing database connection...'
);
info('✓ Database connection successful');
} catch (Exception $e) { } catch (Exception $e) {
warning('Unable to connect to database');
try { try {
if (!$this->createDatabaseCredentials()) { if (!$this->createDatabaseCredentials()) {
$this->error('A database connection could not be established. Please update your configuration and try again.'); error('Database connection could not be established.');
$this->printDatabaseConfig(); $this->printDatabaseConfig();
exit(); exit();
} }
} catch (RuntimeException $e) { } catch (RuntimeException $e) {
$this->error('Failed to persist environment configuration.'); error('Failed to persist environment configuration.');
exit(); exit();
} }
@@ -344,14 +460,15 @@ class Install extends Command
{ {
$connection = config('database.default'); $connection = config('database.default');
$this->line(''); note(
$this->info('Database Configuration:'); "Current Database Configuration:\n" .
$this->line("- Connection: {$connection}"); " Connection: {$connection}\n" .
$this->line('- Host: ' . config("database.connections.{$connection}.host")); " Host: " . config("database.connections.{$connection}.host") . "\n" .
$this->line('- Port: ' . config("database.connections.{$connection}.port")); " Port: " . config("database.connections.{$connection}.port") . "\n" .
$this->line('- Database: ' . config("database.connections.{$connection}.database")); " Database: " . config("database.connections.{$connection}.database") . "\n" .
$this->line('- Username: ' . config("database.connections.{$connection}.username")); " Username: " . config("database.connections.{$connection}.username") . "\n" .
$this->line('- Password: ' . config("database.connections.{$connection}.password")); " Password: " . (config("database.connections.{$connection}.password") ? '***' : '(not set)')
);
} }
protected function persistVariables(array $connectionData): void protected function persistVariables(array $connectionData): void
@@ -407,8 +524,4 @@ class Install extends Command
$this->laravel['config'][$key] = $value; $this->laravel['config'][$key] = $value;
} }
protected function writeSeparationLine()
{
$this->info('*---------------------------------------------------------------------------*');
}
} }

View File

@@ -2,6 +2,7 @@
namespace App\Console\Commands\Core; namespace App\Console\Commands\Core;
use App\Models\Provider;
use App\Services\Ploi\Ploi; use App\Services\Ploi\Ploi;
use Illuminate\Console\Command; use Illuminate\Console\Command;
@@ -18,10 +19,10 @@ class Synchronize extends Command
$data = collect($ploi->user()->serverProviders()->getData()); $data = collect($ploi->user()->serverProviders()->getData());
foreach ($data as $apiProvider) { foreach ($data as $apiProvider) {
$provider = \App\Models\Provider::where('ploi_id', $apiProvider->id)->first(); $provider = Provider::where('ploi_id', $apiProvider->id)->first();
if (!$provider) { if (!$provider) {
$provider = \App\Models\Provider::create([ $provider = Provider::create([
'ploi_id' => $apiProvider->id, 'ploi_id' => $apiProvider->id,
'label' => $apiProvider->label, 'label' => $apiProvider->label,
'name' => $apiProvider->label 'name' => $apiProvider->label

View File

@@ -26,24 +26,17 @@ class ServerData extends Data
public ?int $id = null, public ?int $id = null,
#[StringType] #[StringType]
public ?string $status = null, public ?string $status = null,
#[StringType, #[StringType, AlphaDash, Max(40)]
AlphaDash,
Max(40)]
public string $name, public string $name,
#[NotIn(0), #[NotIn(0), Exists(Provider::class, 'id')]
Exists(Provider::class, 'id')]
public int $provider_id, public int $provider_id,
#[NotIn(0), #[NotIn(0), Exists(ProviderRegion::class, 'id')]
Exists(ProviderRegion::class, 'id')]
public int $provider_region_id, public int $provider_region_id,
#[NotIn(0), #[NotIn(0), Exists(ProviderPlan::class, 'id')]
Exists(ProviderPlan::class, 'id')]
public int $provider_plan_id, public int $provider_plan_id,
#[StringType, #[StringType, In(['mysql', 'mariadb', 'postgresql', 'postgresql13'])]
In(['mysql', 'mariadb', 'postgresql', 'postgresql13'])]
public string $database_type, public string $database_type,
#[Exists(User::class, 'id'), #[Exists(User::class, 'id'), IntegerType]
IntegerType]
public ?int $user_id = null, public ?int $user_id = null,
public ?Carbon $created_at = null, public ?Carbon $created_at = null,
) { ) {

View File

@@ -23,14 +23,11 @@ class SiteData extends Data
public function __construct( public function __construct(
public ?int $id = null, public ?int $id = null,
public ?string $status = null, public ?string $status = null,
#[Exists(Server::class, 'id'), #[Exists(Server::class, 'id'), IntegerType]
IntegerType]
public ?int $server_id = null, public ?int $server_id = null,
#[StringType, #[StringType, CustomRule(Hostname::class, ValidateMaximumSites::class)]
CustomRule(Hostname::class, ValidateMaximumSites::class)]
public ?string $domain = null, public ?string $domain = null,
#[Exists(User::class, 'id'), #[Exists(User::class, 'id'), IntegerType]
IntegerType]
public ?int $user_id = null, public ?int $user_id = null,
public ?Carbon $created_at = null, public ?Carbon $created_at = null,
) { ) {

View File

@@ -8,7 +8,7 @@ use Spatie\LaravelData\Support\DataProperty;
class CarbonCast implements Cast class CarbonCast implements Cast
{ {
public function cast(DataProperty $property, mixed $value): mixed public function cast(DataProperty $property, mixed $value, array $context): Carbon
{ {
return Carbon::parse($value); return Carbon::parse($value);
} }

View File

@@ -2,16 +2,13 @@
namespace App\DataTransferObjects\Support; namespace App\DataTransferObjects\Support;
use Illuminate\Support\Enumerable;
use Spatie\LaravelData\DataCollection;
use Illuminate\Pagination\AbstractPaginator;
use Illuminate\Contracts\Pagination\Paginator;
use Illuminate\Pagination\AbstractCursorPaginator;
class Data extends \Spatie\LaravelData\Data class Data extends \Spatie\LaravelData\Data
{ {
public static function collection(Paginator|Enumerable|array|AbstractCursorPaginator|DataCollection|AbstractPaginator $items): \App\DataTransferObjects\Support\DataCollection /**
{ * When working with paginated data, we want to include pagination details in JSON
return new \App\DataTransferObjects\Support\DataCollection(static::class, $items); * responses from the API. However, due to legacy requirements Ploi Core is using
} * a different structure than this package assumes. Therefore, we will override
* the data collection, register a custom transformer and output the structure.
*/
protected static string $_paginatedCollectionClass = PaginatedDataCollection::class;
} }

View File

@@ -2,14 +2,14 @@
namespace App\DataTransferObjects\Support; namespace App\DataTransferObjects\Support;
use Illuminate\Support\Arr; class DataCollectableTransformer extends \Spatie\LaravelData\Transformers\DataCollectableTransformer
class DataCollectionTransformer extends \Spatie\LaravelData\Transformers\DataCollectionTransformer
{ {
protected function wrapPaginatedArray(array $paginated): array protected function wrapPaginatedArray(array $paginated): array
{ {
$wrapKey = $this->wrap->getKey() ?? 'data';
return [ return [
'data' => $paginated['data'], $wrapKey => $paginated['data'],
'links' => [ 'links' => [
'first' => $paginated['first_page_url'], 'first' => $paginated['first_page_url'],
'last' => $paginated['last_page_url'], 'last' => $paginated['last_page_url'],
@@ -27,14 +27,5 @@ class DataCollectionTransformer extends \Spatie\LaravelData\Transformers\DataCol
'total' => $paginated['total'], 'total' => $paginated['total'],
], ],
]; ];
return [
'data' => $paginated['data'],
'links' => $paginated['links'] ?? [],
'meta' => Arr::except($paginated, [
'data',
'links',
]),
];
} }
} }

View File

@@ -1,23 +0,0 @@
<?php
namespace App\DataTransferObjects\Support;
use Spatie\LaravelData\Support\TransformationType;
class DataCollection extends \Spatie\LaravelData\DataCollection
{
public function transform(TransformationType $type): array
{
$transformer = new DataCollectionTransformer(
$this->dataClass,
$type,
$this->getInclusionTree(),
$this->getExclusionTree(),
$this->items,
$this->through,
$this->filter
);
return $transformer->transform();
}
}

View File

@@ -0,0 +1,23 @@
<?php
namespace App\DataTransferObjects\Support;
use Spatie\LaravelData\Support\Wrapping\WrapExecutionType;
class PaginatedDataCollection extends \Spatie\LaravelData\PaginatedDataCollection
{
public function transform(bool $transformValues = true, WrapExecutionType $wrapExecutionType = WrapExecutionType::Disabled, bool $mapPropertyNames = true): array
{
$transformer = new DataCollectableTransformer(
$this->dataClass,
$transformValues,
$wrapExecutionType,
$mapPropertyNames,
$this->getPartialTrees(),
$this->items,
$this->getWrap(),
);
return $transformer->transform();
}
}

View File

@@ -3,10 +3,11 @@
namespace App\DataTransferObjects\Support\Rules; namespace App\DataTransferObjects\Support\Rules;
use Attribute; use Attribute;
use Spatie\LaravelData\Attributes\Validation\ValidationAttribute; use Spatie\LaravelData\Support\Validation\ValidationPath;
use Spatie\LaravelData\Attributes\Validation\CustomValidationAttribute;
#[Attribute(Attribute::TARGET_PROPERTY)] #[Attribute(Attribute::TARGET_PROPERTY | Attribute::TARGET_PARAMETER)]
class CustomRule extends ValidationAttribute class CustomRule extends CustomValidationAttribute
{ {
protected array $rules = []; protected array $rules = [];
@@ -15,10 +16,14 @@ class CustomRule extends ValidationAttribute
$this->rules = $rules; $this->rules = $rules;
} }
public function getRules(): array /**
* @return array<object|string>|object|string
*/
public function getRules(ValidationPath $path): array|object|string
{ {
return collect($this->rules) return array_map(
->map(fn (string $rule) => new $rule()) fn (string $ruleClass) => new $ruleClass(),
->all(); $this->rules
);
} }
} }

View File

@@ -2,13 +2,15 @@
namespace App\DataTransferObjects\Support\Transformers; namespace App\DataTransferObjects\Support\Transformers;
use Illuminate\Support\Carbon;
use Spatie\LaravelData\Support\DataProperty; use Spatie\LaravelData\Support\DataProperty;
use Spatie\LaravelData\Transformers\Transformer; use Spatie\LaravelData\Transformers\Transformer;
class CarbonTransformer implements Transformer class CarbonTransformer implements Transformer
{ {
public function transform(DataProperty $property, mixed $value): mixed public function transform(DataProperty $property, mixed $value): string
{ {
/** @var Carbon $value */
return $value->toISOString(); return $value->toISOString();
} }
} }

View File

@@ -19,16 +19,11 @@ class UserData extends Data
public function __construct( public function __construct(
public ?int $id = null, public ?int $id = null,
public ?string $avatar = null, public ?string $avatar = null,
#[StringType, #[StringType, Max(255)]
Max(255)]
public ?string $name = null, public ?string $name = null,
#[StringType, #[StringType, Email, Max(255), Unique(User::class)]
Email,
Max(255),
Unique(User::class)]
public ?string $email = null, public ?string $email = null,
#[Exists(Package::class, 'id'), #[Exists(Package::class, 'id'), IntegerType]
IntegerType]
public ?int $package_id = null, public ?int $package_id = null,
#[StringType] #[StringType]
public ?string $blocked = null, public ?string $blocked = null,

View File

@@ -2,27 +2,32 @@
namespace App\Filament\Pages; namespace App\Filament\Pages;
use Filament\Schemas\Schema;
use Filament\Schemas\Components\Grid;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Toggle;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Forms\Contracts\HasForms;
use Filament\Actions\Action;
use Filament\Forms;
use App\Models\Server; use App\Models\Server;
use App\Models\Package; use App\Models\Package;
use Filament\Pages\Page; use Filament\Pages\Page;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use Illuminate\Support\HtmlString; use Illuminate\Support\HtmlString;
use Filament\Forms\Components\Grid;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Toggle;
use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Storage;
use Filament\Forms\Components\TextInput; use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification; use Filament\Notifications\Notification;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Actions\Action;
class Settings extends Page class Settings extends Page implements HasForms
{ {
protected static ?string $navigationIcon = 'heroicon-o-cog'; use InteractsWithForms;
protected static string | \BackedEnum | null $navigationIcon = 'heroicon-o-cog';
protected static string $view = 'filament.pages.settings'; protected string $view = 'filament.pages.settings';
protected static ?string $navigationGroup = 'Settings'; protected static string | \UnitEnum | null $navigationGroup = 'Settings';
protected static ?int $navigationSort = 1; protected static ?int $navigationSort = 1;
@@ -40,26 +45,27 @@ class Settings extends Page
'default_package' => setting('default_package'), 'default_package' => setting('default_package'),
'default_language' => setting('default_language'), 'default_language' => setting('default_language'),
'rotate_logs_after' => setting('rotate_logs_after'), 'rotate_logs_after' => setting('rotate_logs_after'),
'trial' => (bool) setting('trial'), 'trial' => (bool)setting('trial'),
'support' => (bool) setting('support'), 'support' => (bool)setting('support'),
'documentation' => (bool) setting('documentation'), 'documentation' => (bool)setting('documentation'),
'allow_registration' => (bool) setting('allow_registration'), 'allow_registration' => (bool)setting('allow_registration'),
'receive_email_on_server_creation' => (bool) setting('receive_email_on_server_creation'), 'receive_email_on_server_creation' => (bool)setting('receive_email_on_server_creation'),
'receive_email_on_site_creation' => (bool) setting('receive_email_on_site_creation'), 'receive_email_on_site_creation' => (bool)setting('receive_email_on_site_creation'),
'enable_api' => (bool) setting('enable_api'), 'enable_api' => (bool)setting('enable_api'),
'api_token' => setting('api_token'), 'api_token' => setting('api_token'),
'isolate_per_site_per_user' => (bool) setting('isolate_per_site_per_user'), 'isolate_per_site_per_user' => (bool)setting('isolate_per_site_per_user'),
'default_os' => setting('default_os', Server::OS_UBUNTU_22), 'default_os' => setting('default_os', Server::OS_UBUNTU_22),
]); ]);
} }
public function getFormSchema(): array public function form(Schema $schema): Schema
{ {
return [ return $schema
Grid::make(2) ->statePath('data')
->schema([ ->components([
Grid::make(2)
Grid::make(1) ->schema([
Grid::make(2)
->schema([ ->schema([
TextInput::make('name') TextInput::make('name')
->label(__('Company name')) ->label(__('Company name'))
@@ -73,7 +79,7 @@ class Settings extends Page
]) ])
->columnSpan(2), ->columnSpan(2),
Select::make('default_package') Select::make('default_package')
->options(fn () => Package::orderBy('name')->get()->mapWithKeys(fn (Package $package) => [$package->id => $package->name])) ->options(fn () => Package::orderBy('name')->pluck('name', 'id'))
->label(__('Select default package')) ->label(__('Select default package'))
->helperText(__('Select the default package a user should get when you create or they register')), ->helperText(__('Select the default package a user should get when you create or they register')),
Select::make('default_language') Select::make('default_language')
@@ -112,7 +118,7 @@ class Settings extends Page
->helperText(__('This will allow you to have users with trials.')), ->helperText(__('This will allow you to have users with trials.')),
Toggle::make('allow_registration') Toggle::make('allow_registration')
->label(__('Allow registration')) ->label(__('Allow registration'))
->helperText(__('This will allow your customers to make support requests to you.')), ->helperText(__('Allow customer registration')),
Toggle::make('support') Toggle::make('support')
->label(__('Enable support platform')) ->label(__('Enable support platform'))
->helperText(__('This will allow your customers to make support requests to you.')), ->helperText(__('This will allow your customers to make support requests to you.')),
@@ -127,7 +133,7 @@ class Settings extends Page
->helperText(__('This will send an email to all admins notifying them about a new site installation.')), ->helperText(__('This will send an email to all admins notifying them about a new site installation.')),
Toggle::make('enable_api') Toggle::make('enable_api')
->label(__('Enable API')) ->label(__('Enable API'))
->helperText(new HtmlString(__('This will allow you to interact with your system via the API. ') . '<a href="https://docs.ploi-core.io/core-api/introduction" target="_blank" class="text-primary-600">' . __('More information') . '</a>')), ->helperText(new HtmlString(__('This will allow you to interact with your system via the API. ') . '<a href="https://docs.ploi-core.io/304-core-api/737-introduction" target="_blank" class="text-primary-600">' . __('More information') . '</a>')),
TextInput::make('api_token') TextInput::make('api_token')
->label(__('API token')) ->label(__('API token'))
->afterStateHydrated(function (?string $state, TextInput $component) { ->afterStateHydrated(function (?string $state, TextInput $component) {
@@ -152,12 +158,7 @@ class Settings extends Page
->label(__('Enable site isolation per site & user')) ->label(__('Enable site isolation per site & user'))
->helperText(__('This will make sure each site created by one user is always isolated from another.')), ->helperText(__('This will make sure each site created by one user is always isolated from another.')),
]), ]),
]; ]);
}
public function getFormStatePath(): ?string
{
return 'data';
} }
public function save(): void public function save(): void
@@ -178,11 +179,11 @@ class Settings extends Page
Notification::make() Notification::make()
->success() ->success()
->body(__('Settings saved.')) ->title(__('Settings saved.'))
->send(); ->send();
if ($state['logo'] !== $oldLogo || $state['documentation'] !== $oldDocumentation || $state['support'] !== $oldSupport) { if ($state['logo'] !== $oldLogo || $state['documentation'] !== $oldDocumentation || $state['support'] !== $oldSupport) {
$this->redirectRoute('filament.pages.settings'); $this->redirect(Settings::getUrl());
} }
} }
} }

View File

@@ -9,11 +9,11 @@ use Laravel\Horizon\Contracts\MasterSupervisorRepository;
class System extends Page class System extends Page
{ {
protected static ?string $navigationIcon = 'heroicon-o-adjustments'; protected static string | \BackedEnum | null $navigationIcon = 'heroicon-o-adjustments-vertical';
protected static string $view = 'filament.pages.system'; protected string $view = 'filament.pages.system';
protected static ?string $navigationGroup = 'Settings'; protected static string | \UnitEnum | null $navigationGroup = 'Settings';
protected static ?int $navigationSort = 2; protected static ?int $navigationSort = 2;
@@ -33,13 +33,13 @@ class System extends Page
Notification::make() Notification::make()
->success() ->success()
->body(__('Refreshed versions')) ->title(__('Refreshed versions'))
->send(); ->send();
} }
public function getHorizonWorkerStatus(): bool public function getHorizonWorkerStatus(): bool
{ {
return rescue(fn () => (bool) app(MasterSupervisorRepository::class)->all(), false, false); return rescue(fn () => (bool)app(MasterSupervisorRepository::class)->all(), false, false);
} }
public function hasAvailableUpdate(): bool public function hasAvailableUpdate(): bool
@@ -47,7 +47,7 @@ class System extends Page
return app(VersionChecker::class)->getVersions()->isOutOfDate(); return app(VersionChecker::class)->getVersions()->isOutOfDate();
} }
protected static function getNavigationBadge(): ?string public static function getNavigationBadge(): ?string
{ {
$systemChecker = app(VersionChecker::class); $systemChecker = app(VersionChecker::class);

View File

@@ -2,20 +2,26 @@
namespace App\Filament\Pages; namespace App\Filament\Pages;
use Filament\Pages\Page;
use Illuminate\Support\Str;
use Filament\Pages\Actions\Action;
use Filament\Forms\Components\Toggle; use Filament\Forms\Components\Toggle;
use Filament\Notifications\Notification;
use Filament\Forms\Components\MarkdownEditor; use Filament\Forms\Components\MarkdownEditor;
use Filament\Actions\Action;
use Filament\Forms;
use Filament\Actions;
use Filament\Pages\Page;
use Filament\Schemas\Schema;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Forms\Contracts\HasForms;
use Illuminate\Support\Str;
use Filament\Notifications\Notification;
class Terms extends Page class Terms extends Page implements HasForms
{ {
protected static ?string $navigationIcon = 'heroicon-o-document-text'; use InteractsWithForms;
protected static string | \BackedEnum | null $navigationIcon = 'heroicon-o-document-text';
protected static string $view = 'filament.pages.terms'; protected string $view = 'filament.pages.terms';
protected static ?string $navigationGroup = 'Settings'; protected static string | \UnitEnum | null $navigationGroup = 'Settings';
protected static ?int $navigationSort = 3; protected static ?int $navigationSort = 3;
@@ -26,26 +32,28 @@ class Terms extends Page
cache()->forget('core.settings'); cache()->forget('core.settings');
$this->form->fill([ $this->form->fill([
'accept_terms_required' => (bool) setting('accept_terms_required'), 'accept_terms_required' => (bool)setting('accept_terms_required'),
'terms' => setting('terms'), 'terms' => setting('terms'),
'privacy' => setting('privacy'), 'privacy' => setting('privacy'),
]); ]);
} }
protected function getFormSchema(): array public function form(Schema $schema): Schema
{ {
return [ return $schema
Toggle::make('accept_terms_required') ->statePath('data')
->label(__(' Require users to accept terms of service on registration')) ->components([
->helperText(__('This will require newly registered users to accept the terms of service.')), Toggle::make('accept_terms_required')
MarkdownEditor::make('terms') ->label(__(' Require users to accept terms of service on registration'))
->label(__('Content Terms Of Service')), ->helperText(__('This will require newly registered users to accept the terms of service.')),
MarkdownEditor::make('privacy') MarkdownEditor::make('terms')
->label(__('Content Privacy Policy')), ->label(__('Content Terms Of Service')),
]; MarkdownEditor::make('privacy')
->label(__('Content Privacy Policy')),
]);
} }
protected function getActions(): array protected function getHeaderActions(): array
{ {
return [ return [
Action::make('load_terms_template') Action::make('load_terms_template')
@@ -67,17 +75,12 @@ class Terms extends Page
Notification::make() Notification::make()
->success() ->success()
->body(__('Loaded Terms Of Service Template')) ->title(__('Loaded Terms Of Service Template'))
->send(); ->send();
}), }),
]; ];
} }
protected function getFormStatePath(): ?string
{
return 'data';
}
public function save(): void public function save(): void
{ {
$state = $this->form->getState(); $state = $this->form->getState();
@@ -88,7 +91,7 @@ class Terms extends Page
Notification::make() Notification::make()
->success() ->success()
->body(__('Terms saved.')) ->title(__('Terms saved.'))
->send(); ->send();
} }
} }

View File

@@ -1,19 +0,0 @@
<?php
namespace App\Filament\Resources\AlertResource\Pages;
use Filament\Pages\Actions\CreateAction;
use App\Filament\Resources\AlertResource;
use Filament\Resources\Pages\ListRecords;
class ListAlerts extends ListRecords
{
protected static string $resource = AlertResource::class;
protected function getActions(): array
{
return [
CreateAction::make(),
];
}
}

View File

@@ -1,36 +1,40 @@
<?php <?php
namespace App\Filament\Resources; namespace App\Filament\Resources\Alerts;
use Filament\Schemas\Schema;
use Filament\Forms\Components\MarkdownEditor;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\DateTimePicker;
use Filament\Tables\Columns\TextColumn;
use App\Filament\Resources\Alerts\Pages\ListAlerts;
use App\Filament\Resources\Alerts\Pages\CreateAlert;
use App\Filament\Resources\Alerts\Pages\EditAlert;
use Filament\Forms;
use Filament\Tables;
use App\Models\Alert; use App\Models\Alert;
use Filament\Tables\Table;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use Filament\Resources\Form;
use Filament\Resources\Table;
use Filament\Resources\Resource; use Filament\Resources\Resource;
use Illuminate\Support\HtmlString; use Illuminate\Support\HtmlString;
use Filament\Forms\Components\Select;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Columns\BadgeColumn;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\MarkdownEditor;
use App\Filament\Resources\AlertResource\Pages; use App\Filament\Resources\AlertResource\Pages;
class AlertResource extends Resource class AlertResource extends Resource
{ {
protected static ?string $model = Alert::class; protected static ?string $model = Alert::class;
protected static ?string $navigationIcon = 'heroicon-o-bell'; protected static string | \BackedEnum | null $navigationIcon = 'heroicon-o-bell';
protected static ?string $navigationGroup = 'Settings'; protected static string | \UnitEnum | null $navigationGroup = 'Settings';
protected static ?int $navigationSort = 4; protected static ?int $navigationSort = 4;
protected static ?string $recordTitleAttribute = 'message'; protected static ?string $recordTitleAttribute = 'message';
public static function form(Form $form): Form public static function form(Schema $schema): Schema
{ {
return $form return $schema
->schema([ ->components([
MarkdownEditor::make('message') MarkdownEditor::make('message')
->label(__('Content')) ->label(__('Content'))
->columnSpan(2) ->columnSpan(2)
@@ -45,7 +49,7 @@ class AlertResource extends Resource
->required(), ->required(),
DateTimePicker::make('expires_at') DateTimePicker::make('expires_at')
->label(__('Expires at')) ->label(__('Expires at'))
->withoutSeconds(), ->seconds(false),
]); ]);
} }
@@ -56,30 +60,32 @@ class AlertResource extends Resource
TextColumn::make('message') TextColumn::make('message')
->label(__('Content')) ->label(__('Content'))
->formatStateUsing(fn (?string $state) => new HtmlString(Str::markdown($state))), ->formatStateUsing(fn (?string $state) => new HtmlString(Str::markdown($state))),
BadgeColumn::make('type') TextColumn::make('type')
->label(__('Type')) ->label(__('Type'))
->enum([ ->badge()
->formatStateUsing(fn (string $state) => match ($state) {
Alert::TYPE_INFO => __('Informational'), Alert::TYPE_INFO => __('Informational'),
Alert::TYPE_WARNING => __('Warning'), Alert::TYPE_WARNING => __('Warning'),
Alert::TYPE_DANGER => __('Danger'), Alert::TYPE_DANGER => __('Danger'),
]) default => __('Unknown status')
})
->colors([ ->colors([
'primary' => Alert::TYPE_INFO, 'primary' => Alert::TYPE_INFO,
'warning' => Alert::TYPE_WARNING, 'warning' => Alert::TYPE_WARNING,
'danger' => Alert::TYPE_DANGER, 'danger' => Alert::TYPE_DANGER,
]), ]),
TextColumn::make('expires_at') TextColumn::make('expires_at')
->label('Expires Date') ->label('Expires')
->formatStateUsing(fn (?string $state) => filled($state) ? $state : '-'), ->default('-'),
]); ]);
} }
public static function getPages(): array public static function getPages(): array
{ {
return [ return [
'index' => Pages\ListAlerts::route('/'), 'index' => ListAlerts::route('/'),
'create' => Pages\CreateAlert::route('/create'), 'create' => CreateAlert::route('/create'),
'edit' => Pages\EditAlert::route('/{record}/edit'), 'edit' => EditAlert::route('/{record}/edit'),
]; ];
} }

View File

@@ -1,8 +1,8 @@
<?php <?php
namespace App\Filament\Resources\AlertResource\Pages; namespace App\Filament\Resources\Alerts\Pages;
use App\Filament\Resources\AlertResource; use App\Filament\Resources\Alerts\AlertResource;
use Filament\Resources\Pages\CreateRecord; use Filament\Resources\Pages\CreateRecord;
class CreateAlert extends CreateRecord class CreateAlert extends CreateRecord

View File

@@ -1,16 +1,17 @@
<?php <?php
namespace App\Filament\Resources\AlertResource\Pages; namespace App\Filament\Resources\Alerts\Pages;
use Filament\Pages\Actions\DeleteAction; use Filament\Actions\DeleteAction;
use Filament\Actions;
use Filament\Resources\Pages\EditRecord; use Filament\Resources\Pages\EditRecord;
use App\Filament\Resources\AlertResource; use App\Filament\Resources\Alerts\AlertResource;
class EditAlert extends EditRecord class EditAlert extends EditRecord
{ {
protected static string $resource = AlertResource::class; protected static string $resource = AlertResource::class;
protected function getActions(): array protected function getHeaderActions(): array
{ {
return [ return [
DeleteAction::make(), DeleteAction::make(),

View File

@@ -0,0 +1,22 @@
<?php
namespace App\Filament\Resources\Alerts\Pages;
use Filament\Actions\CreateAction;
use Filament\Actions;
use App\Filament\Resources\Alerts\AlertResource;
use Filament\Resources\Pages\ListRecords;
class ListAlerts extends ListRecords
{
protected static string $resource = AlertResource::class;
protected ?string $subheading = 'Alerts are meant to inform your users about things that are going on. For example server migrations, pricing changes. They will display as top-banner inside the panel.';
protected function getHeaderActions(): array
{
return [
CreateAction::make(),
];
}
}

View File

@@ -1,19 +0,0 @@
<?php
namespace App\Filament\Resources\CertificateResource\Pages;
use Filament\Pages\Actions;
use Filament\Resources\Pages\ListRecords;
use App\Filament\Resources\CertificateResource;
class ListCertificates extends ListRecords
{
protected static string $resource = CertificateResource::class;
protected function getActions(): array
{
return [
Actions\CreateAction::make(),
];
}
}

View File

@@ -1,42 +1,46 @@
<?php <?php
namespace App\Filament\Resources; namespace App\Filament\Resources\Certificates;
use Filament\Schemas\Schema;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Textarea;
use Filament\Tables\Columns\TextColumn;
use Filament\Actions\EditAction;
use Filament\Actions\DeleteAction;
use Filament\Actions\DeleteBulkAction;
use App\Filament\Resources\Certificates\Pages\ListCertificates;
use Filament\Forms; use Filament\Forms;
use Filament\Tables; use Filament\Tables;
use Filament\Tables\Table;
use App\Models\Certificate; use App\Models\Certificate;
use Filament\Resources\Form;
use Filament\Resources\Table;
use Filament\Resources\Resource; use Filament\Resources\Resource;
use Illuminate\Support\HtmlString;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use App\Filament\Resources\CertificateResource\Pages; use App\Filament\Resources\CertificateResource\Pages;
use Illuminate\Support\HtmlString;
class CertificateResource extends Resource class CertificateResource extends Resource
{ {
protected static ?string $model = Certificate::class; protected static ?string $model = Certificate::class;
protected static ?string $navigationIcon = 'heroicon-o-annotation'; protected static string | \BackedEnum | null $navigationIcon = 'heroicon-o-chat-bubble-bottom-center-text';
protected static ?string $navigationGroup = 'Site management'; protected static string | \UnitEnum | null $navigationGroup = 'Site management';
protected static ?int $navigationSort = 2; protected static ?int $navigationSort = 2;
public static function form(Form $form): Form public static function form(Schema $schema): Schema
{ {
return $form return $schema
->schema([ ->components([
Forms\Components\TextInput::make('site.name'), TextInput::make('site.name'),
Forms\Components\TextInput::make('server_id'), TextInput::make('server_id'),
Forms\Components\TextInput::make('status') TextInput::make('status'),
->maxLength(255), TextInput::make('ploi_id'),
Forms\Components\TextInput::make('ploi_id'), TextInput::make('domain'),
Forms\Components\TextInput::make('domain') Textarea::make('certificate'),
->maxLength(255), Textarea::make('private'),
Forms\Components\Textarea::make('certificate'), TextInput::make('type'),
Forms\Components\Textarea::make('private'),
Forms\Components\TextInput::make('type')
->maxLength(255),
]); ]);
} }
@@ -44,25 +48,27 @@ class CertificateResource extends Resource
{ {
return $table return $table
->columns([ ->columns([
Tables\Columns\TextColumn::make('server.name') TextColumn::make('server.name')
->searchable() ->searchable()
->label(__('Server')), ->label(__('Server')),
Tables\Columns\TextColumn::make('site.domain') TextColumn::make('site.domain')
->searchable() ->searchable()
->label(__('Main domain')), ->label(__('Main domain')),
Tables\Columns\TextColumn::make('type') TextColumn::make('type')
->label('Type'), ->label('Type'),
Tables\Columns\BadgeColumn::make('status') TextColumn::make('status')
->enum([ ->badge()
->formatStateUsing(fn (string $state) => match ($state) {
Certificate::STATUS_BUSY => __('Busy'), Certificate::STATUS_BUSY => __('Busy'),
Certificate::STATUS_ACTIVE => __('Active'), Certificate::STATUS_ACTIVE => __('Active'),
]) default => __('Unknown status')
})
->colors([ ->colors([
'warning' => Certificate::STATUS_BUSY, 'warning' => Certificate::STATUS_BUSY,
'success' => Certificate::STATUS_ACTIVE, 'success' => Certificate::STATUS_ACTIVE,
]) ])
->label(__('Status')), ->label(__('Status')),
Tables\Columns\TextColumn::make('domain') TextColumn::make('domain')
->searchable() ->searchable()
->wrap() ->wrap()
->getStateUsing(function (Certificate $record) { ->getStateUsing(function (Certificate $record) {
@@ -71,7 +77,7 @@ class CertificateResource extends Resource
return new HtmlString($state); return new HtmlString($state);
}) })
->label('Domains & aliases'), ->label('Domains & aliases'),
Tables\Columns\TextColumn::make('created_at') TextColumn::make('created_at')
->label(__('Date')) ->label(__('Date'))
->sortable() ->sortable()
->dateTime(), ->dateTime(),
@@ -79,11 +85,12 @@ class CertificateResource extends Resource
->filters([ ->filters([
// //
]) ])
->actions([ ->recordActions([
Tables\Actions\EditAction::make(), EditAction::make(),
DeleteAction::make(),
]) ])
->bulkActions([ ->toolbarActions([
Tables\Actions\DeleteBulkAction::make(), DeleteBulkAction::make(),
]) ])
->defaultSort('created_at', 'desc'); ->defaultSort('created_at', 'desc');
} }
@@ -104,7 +111,7 @@ class CertificateResource extends Resource
public static function getPages(): array public static function getPages(): array
{ {
return [ return [
'index' => Pages\ListCertificates::route('/'), 'index' => ListCertificates::route('/'),
]; ];
} }
} }

View File

@@ -0,0 +1,20 @@
<?php
namespace App\Filament\Resources\Certificates\Pages;
use Filament\Actions\CreateAction;
use Filament\Actions;
use Filament\Resources\Pages\ListRecords;
use App\Filament\Resources\Certificates\CertificateResource;
class ListCertificates extends ListRecords
{
protected static string $resource = CertificateResource::class;
protected function getHeaderActions(): array
{
return [
CreateAction::make(),
];
}
}

View File

@@ -1,19 +0,0 @@
<?php
namespace App\Filament\Resources\CronjobResource\Pages;
use Filament\Pages\Actions;
use Filament\Resources\Pages\EditRecord;
use App\Filament\Resources\CronjobResource;
class EditCronjob extends EditRecord
{
protected static string $resource = CronjobResource::class;
protected function getActions(): array
{
return [
Actions\DeleteAction::make(),
];
}
}

View File

@@ -1,19 +0,0 @@
<?php
namespace App\Filament\Resources\CronjobResource\Pages;
use Filament\Pages\Actions;
use Filament\Resources\Pages\ListRecords;
use App\Filament\Resources\CronjobResource;
class ListCronjobs extends ListRecords
{
protected static string $resource = CronjobResource::class;
protected function getActions(): array
{
return [
Actions\CreateAction::make(),
];
}
}

View File

@@ -1,11 +1,13 @@
<?php <?php
namespace App\Filament\Resources; namespace App\Filament\Resources\Cronjobs;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use App\Filament\Resources\Cronjobs\Pages\ListCronjobs;
use Filament\Tables; use Filament\Tables;
use App\Models\Cronjob; use App\Models\Cronjob;
use Filament\Resources\Form; use Filament\Tables\Table;
use Filament\Resources\Table;
use Filament\Resources\Resource; use Filament\Resources\Resource;
use App\Filament\Resources\CronjobResource\Pages; use App\Filament\Resources\CronjobResource\Pages;
@@ -13,16 +15,16 @@ class CronjobResource extends Resource
{ {
protected static ?string $model = Cronjob::class; protected static ?string $model = Cronjob::class;
protected static ?string $navigationIcon = 'heroicon-o-clock'; protected static string | \BackedEnum | null $navigationIcon = 'heroicon-o-clock';
protected static ?string $navigationGroup = 'Site management'; protected static string | \UnitEnum | null $navigationGroup = 'Site management';
protected static ?int $navigationSort = 3; protected static ?int $navigationSort = 3;
public static function form(Form $form): Form public static function form(Schema $schema): Schema
{ {
return $form return $schema
->schema([ ->components([
// //
]); ]);
} }
@@ -31,28 +33,30 @@ class CronjobResource extends Resource
{ {
return $table return $table
->columns([ ->columns([
Tables\Columns\TextColumn::make('site.domain') TextColumn::make('site.domain')
->searchable() ->searchable()
->label(__('Site')), ->label(__('Site')),
Tables\Columns\BadgeColumn::make('status') TextColumn::make('status')
->enum([ ->badge()
->formatStateUsing(fn (string $state) => match ($state) {
Cronjob::STATUS_BUSY => __('Busy'), Cronjob::STATUS_BUSY => __('Busy'),
Cronjob::STATUS_ACTIVE => __('Active'), Cronjob::STATUS_ACTIVE => __('Active'),
]) default => __('Unknown status')
})
->colors([ ->colors([
'warning' => Cronjob::STATUS_BUSY, 'warning' => Cronjob::STATUS_BUSY,
'success' => Cronjob::STATUS_ACTIVE, 'success' => Cronjob::STATUS_ACTIVE,
]) ])
->label(__('Status')), ->label(__('Status')),
Tables\Columns\TextColumn::make('server.name') TextColumn::make('server.name')
->searchable() ->searchable()
->label(__('Server')), ->label(__('Server')),
Tables\Columns\TextColumn::make('command') TextColumn::make('command')
->searchable() ->searchable()
->label(__('Command')), ->label(__('Command')),
Tables\Columns\TextColumn::make('frequency') TextColumn::make('frequency')
->label(__('Frequency')), ->label(__('Frequency')),
Tables\Columns\TextColumn::make('created_at') TextColumn::make('created_at')
->label(__('Date')) ->label(__('Date'))
->sortable() ->sortable()
->dateTime(), ->dateTime(),
@@ -60,10 +64,10 @@ class CronjobResource extends Resource
->filters([ ->filters([
// //
]) ])
->actions([ ->recordActions([
// //
]) ])
->bulkActions([ ->toolbarActions([
// //
]) ])
->defaultSort('created_at', 'desc'); ->defaultSort('created_at', 'desc');
@@ -79,7 +83,7 @@ class CronjobResource extends Resource
public static function getPages(): array public static function getPages(): array
{ {
return [ return [
'index' => Pages\ListCronjobs::route('/'), 'index' => ListCronjobs::route('/'),
]; ];
} }
} }

View File

@@ -1,9 +1,9 @@
<?php <?php
namespace App\Filament\Resources\CronjobResource\Pages; namespace App\Filament\Resources\Cronjobs\Pages;
use Filament\Resources\Pages\CreateRecord; use Filament\Resources\Pages\CreateRecord;
use App\Filament\Resources\CronjobResource; use App\Filament\Resources\Cronjobs\CronjobResource;
class CreateCronjob extends CreateRecord class CreateCronjob extends CreateRecord
{ {

View File

@@ -0,0 +1,20 @@
<?php
namespace App\Filament\Resources\Cronjobs\Pages;
use Filament\Actions\DeleteAction;
use Filament\Actions;
use Filament\Resources\Pages\EditRecord;
use App\Filament\Resources\Cronjobs\CronjobResource;
class EditCronjob extends EditRecord
{
protected static string $resource = CronjobResource::class;
protected function getHeaderActions(): array
{
return [
DeleteAction::make(),
];
}
}

View File

@@ -0,0 +1,20 @@
<?php
namespace App\Filament\Resources\Cronjobs\Pages;
use Filament\Actions\CreateAction;
use Filament\Actions;
use Filament\Resources\Pages\ListRecords;
use App\Filament\Resources\Cronjobs\CronjobResource;
class ListCronjobs extends ListRecords
{
protected static string $resource = CronjobResource::class;
protected function getHeaderActions(): array
{
return [
CreateAction::make(),
];
}
}

View File

@@ -1,19 +0,0 @@
<?php
namespace App\Filament\Resources\DatabaseResource\Pages;
use Filament\Pages\Actions;
use Filament\Resources\Pages\ListRecords;
use App\Filament\Resources\DatabaseResource;
class ListDatabases extends ListRecords
{
protected static string $resource = DatabaseResource::class;
protected function getActions(): array
{
return [
Actions\CreateAction::make(),
];
}
}

View File

@@ -1,11 +1,15 @@
<?php <?php
namespace App\Filament\Resources; namespace App\Filament\Resources\Databases;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Actions\EditAction;
use App\Filament\Resources\Databases\Pages\ListDatabases;
use App\Filament\Resources\Databases\Pages\EditDatabase;
use Filament\Tables; use Filament\Tables;
use App\Models\Database; use App\Models\Database;
use Filament\Resources\Form; use Filament\Tables\Table;
use Filament\Resources\Table;
use Filament\Resources\Resource; use Filament\Resources\Resource;
use App\Filament\Resources\DatabaseResource\Pages; use App\Filament\Resources\DatabaseResource\Pages;
@@ -13,16 +17,16 @@ class DatabaseResource extends Resource
{ {
protected static ?string $model = Database::class; protected static ?string $model = Database::class;
protected static ?string $navigationIcon = 'heroicon-o-database'; protected static string | \BackedEnum | null $navigationIcon = 'heroicon-o-circle-stack';
protected static ?string $navigationGroup = 'Site management'; protected static string | \UnitEnum | null $navigationGroup = 'Site management';
protected static ?int $navigationSort = 4; protected static ?int $navigationSort = 4;
public static function form(Form $form): Form public static function form(Schema $schema): Schema
{ {
return $form return $schema
->schema([ ->components([
// //
]); ]);
} }
@@ -31,27 +35,28 @@ class DatabaseResource extends Resource
{ {
return $table return $table
->columns([ ->columns([
Tables\Columns\TextColumn::make('name') TextColumn::make('name')
->label(__('Name')) ->label(__('Name'))
->searchable(), ->searchable(),
Tables\Columns\TextColumn::make('server.name') TextColumn::make('server.name')
->label(__('Server')) ->label(__('Server'))
->searchable(), ->searchable(),
Tables\Columns\TextColumn::make('site.domain') TextColumn::make('site.domain')
->label(__('Site')) ->label(__('Site'))
->searchable(), ->searchable(),
Tables\Columns\BadgeColumn::make('status') TextColumn::make('status')
->enum([ ->badge()
->formatStateUsing(fn (string $state) => match ($state) {
Database::STATUS_BUSY => __('Busy'), Database::STATUS_BUSY => __('Busy'),
Database::STATUS_ACTIVE => __('Active'), Database::STATUS_ACTIVE => __('Active'),
]) default => __('Unknown status')
})
->colors([ ->colors([
'warning' => Database::STATUS_BUSY, 'warning' => Database::STATUS_BUSY,
'success' => Database::STATUS_ACTIVE, 'success' => Database::STATUS_ACTIVE,
]) ])
->label(__('Status')), ->label(__('Status')),
TextColumn::make('created_at')
Tables\Columns\TextColumn::make('created_at')
->label(__('Date')) ->label(__('Date'))
->sortable() ->sortable()
->dateTime(), ->dateTime(),
@@ -59,10 +64,10 @@ class DatabaseResource extends Resource
->filters([ ->filters([
// //
]) ])
->actions([ ->recordActions([
Tables\Actions\EditAction::make(), EditAction::make(),
]) ])
->bulkActions([ ->toolbarActions([
// //
]) ])
->defaultSort('created_at', 'desc'); ->defaultSort('created_at', 'desc');
@@ -78,8 +83,8 @@ class DatabaseResource extends Resource
public static function getPages(): array public static function getPages(): array
{ {
return [ return [
'index' => Pages\ListDatabases::route('/'), 'index' => ListDatabases::route('/'),
'edit' => Pages\EditDatabase::route('/{record}'), 'edit' => EditDatabase::route('/{record}'),
]; ];
} }
} }

View File

@@ -1,25 +1,25 @@
<?php <?php
namespace App\Filament\Resources\DatabaseResource\Pages; namespace App\Filament\Resources\Databases\Pages;
use App\Models\Database; use App\Models\Database;
use App\Services\Ploi\Ploi; use App\Services\Ploi\Ploi;
use Filament\Resources\Pages\Page; use Filament\Resources\Pages\Page;
use Filament\Schemas\Schema;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Forms\Contracts\HasForms;
use App\Mail\Database\PasswordReset; use App\Mail\Database\PasswordReset;
use Illuminate\Support\Facades\Mail; use Illuminate\Support\Facades\Mail;
use Filament\Forms\Components\Toggle; use Filament\Forms\Components\Toggle;
use Filament\Notifications\Notification; use Filament\Notifications\Notification;
use App\Filament\Resources\DatabaseResource; use App\Filament\Resources\Databases\DatabaseResource;
class EditDatabase extends Page class EditDatabase extends Page implements HasForms
{ {
protected $listeners = [ use InteractsWithForms;
'$refresh',
];
protected static string $resource = DatabaseResource::class; protected static string $resource = DatabaseResource::class;
protected static string $view = 'filament.resources.database-resource.pages.edit-database'; protected string $view = 'filament.resources.database-resource.pages.edit-database';
public Database $record; public Database $record;
@@ -30,16 +30,16 @@ class EditDatabase extends Page
$this->resetDatabasePasswordForm->fill(); $this->resetDatabasePasswordForm->fill();
} }
public function getForms(): array public ?array $resetDatabasePasswordData = [];
public function resetDatabasePasswordForm(Schema $schema): Schema
{ {
return [ return $schema
'resetDatabasePasswordForm' => $this->makeForm() ->statePath('resetDatabasePasswordData')
->schema([ ->components([
Toggle::make('send_new_password_to_user') Toggle::make('send_new_password_to_user')
->label(__('Email new password to user')), ->label(__('Email new password to user')),
]) ]);
->model($this->record),
];
} }
public function resetDatabasePassword(): void public function resetDatabasePassword(): void
@@ -56,7 +56,7 @@ class EditDatabase extends Page
$this->recentlyUpdatedPassword = $data->new_password; $this->recentlyUpdatedPassword = $data->new_password;
Notification::make() Notification::make()
->body(__('Successfully reset database password.')) ->title(__('Successfully reset database password.'))
->success() ->success()
->send(); ->send();

View File

@@ -0,0 +1,20 @@
<?php
namespace App\Filament\Resources\Databases\Pages;
use Filament\Actions\CreateAction;
use Filament\Actions;
use Filament\Resources\Pages\ListRecords;
use App\Filament\Resources\Databases\DatabaseResource;
class ListDatabases extends ListRecords
{
protected static string $resource = DatabaseResource::class;
protected function getHeaderActions(): array
{
return [
CreateAction::make(),
];
}
}

View File

@@ -1,26 +1,32 @@
<?php <?php
namespace App\Filament\Resources; namespace App\Filament\Resources\DocumentationCategories;
use Filament\Schemas\Schema;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\MarkdownEditor;
use Filament\Tables\Columns\TextColumn;
use App\Filament\Resources\DocumentationCategories\RelationManagers\DocumentationItemsRelationManager;
use App\Filament\Resources\DocumentationCategories\Pages\ListDocumentationCategories;
use App\Filament\Resources\DocumentationCategories\Pages\CreateDocumentationCategory;
use App\Filament\Resources\DocumentationCategories\Pages\EditDocumentationCategory;
use Filament\Forms;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use Filament\Resources\Form;
use Filament\Resources\Table;
use Filament\Resources\Resource; use Filament\Resources\Resource;
use Illuminate\Support\HtmlString; use Illuminate\Support\HtmlString;
use App\Models\DocumentationCategory; use App\Models\DocumentationCategory;
use Filament\Tables\Columns\TextColumn;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\MarkdownEditor;
use App\Filament\Resources\DocumentationCategoryResource\Pages; use App\Filament\Resources\DocumentationCategoryResource\Pages;
use App\Filament\Resources\DocumentationCategoryResource\RelationManagers\DocumentationItemsRelationManager; use App\Filament\Resources\DocumentationCategoryResource\RelationManagers;
class DocumentationCategoryResource extends Resource class DocumentationCategoryResource extends Resource
{ {
protected static ?string $model = DocumentationCategory::class; protected static ?string $model = DocumentationCategory::class;
protected static ?string $navigationIcon = 'heroicon-o-tag'; protected static string | \BackedEnum | null $navigationIcon = 'heroicon-o-tag';
protected static ?string $navigationGroup = 'Documentation'; protected static string | \UnitEnum | null $navigationGroup = 'Documentation';
protected static ?int $navigationSort = 2; protected static ?int $navigationSort = 2;
@@ -28,15 +34,15 @@ class DocumentationCategoryResource extends Resource
protected static ?string $label = 'Category'; protected static ?string $label = 'Category';
protected static function shouldRegisterNavigation(): bool public static function shouldRegisterNavigation(): bool
{ {
return (bool) setting('documentation'); return (bool)setting('documentation');
} }
public static function form(Form $form): Form public static function form(Schema $schema): Schema
{ {
return $form return $schema
->schema([ ->components([
TextInput::make('title') TextInput::make('title')
->label(__('Title')) ->label(__('Title'))
->unique(table: DocumentationCategory::class, column: 'title', ignoreRecord: true) ->unique(table: DocumentationCategory::class, column: 'title', ignoreRecord: true)
@@ -73,9 +79,9 @@ class DocumentationCategoryResource extends Resource
public static function getPages(): array public static function getPages(): array
{ {
return [ return [
'index' => Pages\ListDocumentationCategories::route('/'), 'index' => ListDocumentationCategories::route('/'),
'create' => Pages\CreateDocumentationCategory::route('/create'), 'create' => CreateDocumentationCategory::route('/create'),
'edit' => Pages\EditDocumentationCategory::route('/{record}/edit'), 'edit' => EditDocumentationCategory::route('/{record}/edit'),
]; ];
} }

View File

@@ -1,9 +1,9 @@
<?php <?php
namespace App\Filament\Resources\DocumentationCategoryResource\Pages; namespace App\Filament\Resources\DocumentationCategories\Pages;
use Filament\Resources\Pages\CreateRecord; use Filament\Resources\Pages\CreateRecord;
use App\Filament\Resources\DocumentationCategoryResource; use App\Filament\Resources\DocumentationCategories\DocumentationCategoryResource;
class CreateDocumentationCategory extends CreateRecord class CreateDocumentationCategory extends CreateRecord
{ {

View File

@@ -1,16 +1,17 @@
<?php <?php
namespace App\Filament\Resources\DocumentationCategoryResource\Pages; namespace App\Filament\Resources\DocumentationCategories\Pages;
use Filament\Pages\Actions\DeleteAction; use Filament\Actions\DeleteAction;
use Filament\Actions;
use Filament\Resources\Pages\EditRecord; use Filament\Resources\Pages\EditRecord;
use App\Filament\Resources\DocumentationCategoryResource; use App\Filament\Resources\DocumentationCategories\DocumentationCategoryResource;
class EditDocumentationCategory extends EditRecord class EditDocumentationCategory extends EditRecord
{ {
protected static string $resource = DocumentationCategoryResource::class; protected static string $resource = DocumentationCategoryResource::class;
protected function getActions(): array protected function getHeaderActions(): array
{ {
return [ return [
DeleteAction::make(), DeleteAction::make(),

View File

@@ -1,16 +1,17 @@
<?php <?php
namespace App\Filament\Resources\DocumentationCategoryResource\Pages; namespace App\Filament\Resources\DocumentationCategories\Pages;
use Filament\Pages\Actions\CreateAction; use Filament\Actions\CreateAction;
use Filament\Actions;
use Filament\Resources\Pages\ListRecords; use Filament\Resources\Pages\ListRecords;
use App\Filament\Resources\DocumentationCategoryResource; use App\Filament\Resources\DocumentationCategories\DocumentationCategoryResource;
class ListDocumentationCategories extends ListRecords class ListDocumentationCategories extends ListRecords
{ {
protected static string $resource = DocumentationCategoryResource::class; protected static string $resource = DocumentationCategoryResource::class;
protected function getActions(): array protected function getHeaderActions(): array
{ {
return [ return [
CreateAction::make(), CreateAction::make(),

View File

@@ -0,0 +1,57 @@
<?php
namespace App\Filament\Resources\DocumentationCategories\RelationManagers;
use Filament\Schemas\Schema;
use Filament\Forms\Components\TextInput;
use Filament\Tables\Columns\TextColumn;
use Filament\Actions\CreateAction;
use Filament\Actions\EditAction;
use Filament\Actions\DeleteAction;
use Filament\Actions\DeleteBulkAction;
use Filament\Forms;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Resources\RelationManagers\RelationManager;
class DocumentationItemsRelationManager extends RelationManager
{
protected static string $relationship = 'items';
protected static ?string $recordTitleAttribute = 'title';
protected static ?string $label = 'Article';
protected static ?string $pluralLabel = 'Articles';
public function form(Schema $schema): Schema
{
return $schema
->components([
TextInput::make('title')
->required()
->maxLength(255),
]);
}
public function table(Table $table): Table
{
return $table
->columns([
TextColumn::make('title'),
])
->filters([
//
])
->headerActions([
CreateAction::make(),
])
->recordActions([
EditAction::make(),
DeleteAction::make(),
])
->toolbarActions([
DeleteBulkAction::make(),
]);
}
}

View File

@@ -1,51 +0,0 @@
<?php
namespace App\Filament\Resources\DocumentationCategoryResource\RelationManagers;
use Filament\Forms;
use Filament\Tables;
use Filament\Resources\Form;
use Filament\Resources\Table;
use Filament\Resources\RelationManagers\RelationManager;
class DocumentationItemsRelationManager extends RelationManager
{
protected static string $relationship = 'items';
protected static ?string $recordTitleAttribute = 'title';
protected static ?string $label = 'Article';
protected static ?string $pluralLabel = 'Articles';
public static function form(Form $form): Form
{
return $form
->schema([
Forms\Components\TextInput::make('title')
->required()
->maxLength(255),
]);
}
public static function table(Table $table): Table
{
return $table
->columns([
Tables\Columns\TextColumn::make('title'),
])
->filters([
//
])
->headerActions([
Tables\Actions\CreateAction::make(),
])
->actions([
Tables\Actions\EditAction::make(),
Tables\Actions\DeleteAction::make(),
])
->bulkActions([
Tables\Actions\DeleteBulkAction::make(),
]);
}
}

View File

@@ -1,24 +1,29 @@
<?php <?php
namespace App\Filament\Resources; namespace App\Filament\Resources\DocumentationItems;
use Filament\Resources\Form; use Filament\Schemas\Schema;
use Filament\Resources\Table; use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\MarkdownEditor;
use Filament\Tables\Columns\TextColumn;
use App\Filament\Resources\DocumentationItems\Pages\ListDocumentationItems;
use App\Filament\Resources\DocumentationItems\Pages\CreateDocumentationItem;
use App\Filament\Resources\DocumentationItems\Pages\EditDocumentationItem;
use Filament\Forms;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Resources\Resource; use Filament\Resources\Resource;
use App\Models\DocumentationItem; use App\Models\DocumentationItem;
use Filament\Forms\Components\Select;
use Filament\Tables\Columns\TextColumn;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\MarkdownEditor;
use App\Filament\Resources\DocumentationItemResource\Pages; use App\Filament\Resources\DocumentationItemResource\Pages;
class DocumentationItemResource extends Resource class DocumentationItemResource extends Resource
{ {
protected static ?string $model = DocumentationItem::class; protected static ?string $model = DocumentationItem::class;
protected static ?string $navigationIcon = 'heroicon-o-document-duplicate'; protected static string | \BackedEnum | null $navigationIcon = 'heroicon-o-document-duplicate';
protected static ?string $navigationGroup = 'Documentation'; protected static string | \UnitEnum | null $navigationGroup = 'Documentation';
protected static ?int $navigationSort = 1; protected static ?int $navigationSort = 1;
@@ -26,15 +31,15 @@ class DocumentationItemResource extends Resource
protected static ?string $label = 'Article'; protected static ?string $label = 'Article';
protected static function shouldRegisterNavigation(): bool public static function shouldRegisterNavigation(): bool
{ {
return (bool) setting('documentation'); return (bool)setting('documentation');
} }
public static function form(Form $form): Form public static function form(Schema $schema): Schema
{ {
return $form return $schema
->schema([ ->components([
TextInput::make('title') TextInput::make('title')
->label(__('Title')) ->label(__('Title'))
->required(), ->required(),
@@ -56,7 +61,6 @@ class DocumentationItemResource extends Resource
TextColumn::make('title') TextColumn::make('title')
->searchable() ->searchable()
->sortable(), ->sortable(),
TextColumn::make('category.title') TextColumn::make('category.title')
->searchable() ->searchable()
->sortable(), ->sortable(),
@@ -66,9 +70,9 @@ class DocumentationItemResource extends Resource
public static function getPages(): array public static function getPages(): array
{ {
return [ return [
'index' => Pages\ListDocumentationItems::route('/'), 'index' => ListDocumentationItems::route('/'),
'create' => Pages\CreateDocumentationItem::route('/create'), 'create' => CreateDocumentationItem::route('/create'),
'edit' => Pages\EditDocumentationItem::route('/{record}/edit'), 'edit' => EditDocumentationItem::route('/{record}/edit'),
]; ];
} }
} }

View File

@@ -1,9 +1,9 @@
<?php <?php
namespace App\Filament\Resources\DocumentationItemResource\Pages; namespace App\Filament\Resources\DocumentationItems\Pages;
use Filament\Resources\Pages\CreateRecord; use Filament\Resources\Pages\CreateRecord;
use App\Filament\Resources\DocumentationItemResource; use App\Filament\Resources\DocumentationItems\DocumentationItemResource;
class CreateDocumentationItem extends CreateRecord class CreateDocumentationItem extends CreateRecord
{ {

View File

@@ -1,16 +1,17 @@
<?php <?php
namespace App\Filament\Resources\DocumentationItemResource\Pages; namespace App\Filament\Resources\DocumentationItems\Pages;
use Filament\Pages\Actions\DeleteAction; use Filament\Actions\DeleteAction;
use Filament\Actions;
use Filament\Resources\Pages\EditRecord; use Filament\Resources\Pages\EditRecord;
use App\Filament\Resources\DocumentationItemResource; use App\Filament\Resources\DocumentationItems\DocumentationItemResource;
class EditDocumentationItem extends EditRecord class EditDocumentationItem extends EditRecord
{ {
protected static string $resource = DocumentationItemResource::class; protected static string $resource = DocumentationItemResource::class;
protected function getActions(): array protected function getHeaderActions(): array
{ {
return [ return [
DeleteAction::make(), DeleteAction::make(),

View File

@@ -1,16 +1,17 @@
<?php <?php
namespace App\Filament\Resources\DocumentationItemResource\Pages; namespace App\Filament\Resources\DocumentationItems\Pages;
use Filament\Pages\Actions\CreateAction; use Filament\Actions\CreateAction;
use Filament\Actions;
use Filament\Resources\Pages\ListRecords; use Filament\Resources\Pages\ListRecords;
use App\Filament\Resources\DocumentationItemResource; use App\Filament\Resources\DocumentationItems\DocumentationItemResource;
class ListDocumentationItems extends ListRecords class ListDocumentationItems extends ListRecords
{ {
protected static string $resource = DocumentationItemResource::class; protected static string $resource = DocumentationItemResource::class;
protected function getActions(): array protected function getHeaderActions(): array
{ {
return [ return [
CreateAction::make(), CreateAction::make(),

View File

@@ -1,167 +0,0 @@
<?php
namespace App\Filament\Resources;
use Filament\Tables;
use App\Models\Package;
use Filament\Resources\Form;
use Filament\Resources\Table;
use Filament\Resources\Resource;
use Filament\Forms\Components\Grid;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\Checkbox;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\CheckboxList;
use App\Filament\Resources\PackageResource\Pages;
use App\Filament\Resources\PackageResource\RelationManagers;
class PackageResource extends Resource
{
protected static ?string $model = Package::class;
protected static ?string $navigationIcon = 'heroicon-o-color-swatch';
protected static ?int $navigationSort = 3;
public static function form(Form $form): Form
{
return $form
->schema([
TextInput::make('name')
->label(__('Name'))
->required()
->columnSpan(2),
TextInput::make('maximum_sites')
->helperText(__('Set to 0 for unlimited'))
->integer()
->required(),
TextInput::make('maximum_servers')
->helperText(__('Set to 0 for unlimited'))
->integer()
->required(),
TextInput::make('stripe_plan_id')
->helperText(__('Enter the pricing ID from Stripe here') . ' - <a href="https://docs.ploi-core.io/digging-deeper/using-stripe" target="ploi-docs-stripe" class="text-primary-500">How does this work?</a>')
->label(__('Stripe ID'))
->columnSpan(2),
TextInput::make('price_monthly')
->numeric()
->label(__('Monthly price'))
->helperText(__('Fill this in if you want it to be monthly payments'))
->required(),
TextInput::make('price_yearly')
->numeric()
->label(__('Yearly price'))
->helperText(__('Fill this in if you want it to be yearly payments'))
->required(),
Select::make('currency')
->label(__('Currency'))
->options([
'usd' => 'USD $',
'eur' => 'Euro €',
'gbp' => 'GBP £',
'nok' => 'NOK (Norwegian Krone)',
'aud' => 'AUD (Australian dollar)',
'cad' => 'CAD (Canadian dollar)',
'inr' => 'INR (Indian ₹ rupee)',
'thb' => 'THB (Thai Baht)',
'brl' => 'BRL R$ (Brazilian Real)',
])
->required(),
Grid::make()
->schema([
Section::make(__('Server permissions'))
->schema([
Checkbox::make('server_permissions.create')
->reactive()
->label('Allow server creation')
->helperText('This will allow users to create servers'),
Checkbox::make('server_permissions.update')
->label('Allow server updates')
->helperText('This will allow users to update servers'),
Checkbox::make('server_permissions.delete')
->label('Allow server deletion')
->helperText('This will allow users to delete servers'),
])
->columnSpan(1),
Section::make(__('Site permissions'))
->schema([
Checkbox::make('site_permissions.create')
->label('Allow site creation')
->helperText('This will allow users to create sites'),
Checkbox::make('site_permissions.update')
->label('Allow site updates')
->helperText('This will allow users to update sites'),
Checkbox::make('site_permissions.delete')
->label('Allow site deletion')
->helperText('This will allow users to delete sites'),
])
->columnSpan(1),
]),
Grid::make()
->schema([
Section::make(__('Available server providers'))
->description(__('These server providers will be available for users that are attached to this package.'))
->schema([
CheckboxList::make('providers')
->relationship('providers', 'name')
])
->columnSpan(1)
])
->visible(function ($get) {
return $get('server_permissions')['create'];
})
]);
}
public static function table(Table $table): Table
{
return $table
->columns([
Tables\Columns\TextColumn::make('id')->label('ID')->searchable(),
Tables\Columns\TextColumn::make('name')
->label(__('Name'))
->description(function (Package $record) {
if (!$record->stripe_plan_id) {
return __('Not attached to Stripe.');
}
return "Attached to stripe - {$record->price_monthly} {$record->currency}";
}),
Tables\Columns\TextColumn::make('maximum_sites')
->formatStateUsing(fn (int $state) => $state === 0 ? __('Unlimited') : $state)
->label(__('Maximum sites')),
Tables\Columns\TextColumn::make('maximum_servers')
->formatStateUsing(fn (int $state) => $state === 0 ? __('Unlimited') : $state)
->label(__('Maximum servers')),
Tables\Columns\TextColumn::make('users_count')
->counts('users'),
])
->filters([
//
])
->actions([
Tables\Actions\EditAction::make(),
])
->bulkActions([
Tables\Actions\DeleteBulkAction::make(),
]);
}
public static function getRelations(): array
{
return [
RelationManagers\UsersRelationManager::class,
];
}
public static function getPages(): array
{
return [
'index' => Pages\ListPackages::route('/'),
'create' => Pages\CreatePackage::route('/create'),
'edit' => Pages\EditPackage::route('/{record}/edit'),
];
}
}

View File

@@ -1,19 +0,0 @@
<?php
namespace App\Filament\Resources\PackageResource\Pages;
use Filament\Pages\Actions;
use Filament\Resources\Pages\EditRecord;
use App\Filament\Resources\PackageResource;
class EditPackage extends EditRecord
{
protected static string $resource = PackageResource::class;
protected function getActions(): array
{
return [
Actions\DeleteAction::make(),
];
}
}

View File

@@ -1,19 +0,0 @@
<?php
namespace App\Filament\Resources\PackageResource\Pages;
use Filament\Pages\Actions;
use Filament\Resources\Pages\ListRecords;
use App\Filament\Resources\PackageResource;
class ListPackages extends ListRecords
{
protected static string $resource = PackageResource::class;
protected function getActions(): array
{
return [
Actions\CreateAction::make(),
];
}
}

View File

@@ -0,0 +1,279 @@
<?php
namespace App\Filament\Resources\Packages;
use Filament\Schemas\Schema;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Select;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Components\Section;
use Filament\Forms\Components\Checkbox;
use Filament\Forms\Components\CheckboxList;
use Filament\Schemas\Components\Actions;
use Filament\Actions\Action;
use Filament\Forms\Components\Toggle;
use Filament\Schemas\Components\Utilities\Set;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Forms\Components\Placeholder;
use Filament\Tables\Columns\TextColumn;
use Filament\Actions\EditAction;
use Filament\Actions\DeleteAction;
use Filament\Actions\DeleteBulkAction;
use App\Filament\Resources\Packages\RelationManagers\UsersRelationManager;
use App\Filament\Resources\Packages\Pages\ListPackages;
use App\Filament\Resources\Packages\Pages\CreatePackage;
use App\Filament\Resources\Packages\Pages\EditPackage;
use Filament\Forms;
use Filament\Tables;
use App\Models\Package;
use App\Models\Provider;
use Filament\Tables\Table;
use App\Models\ProviderPlan;
use Filament\Resources\Resource;
use Illuminate\Support\HtmlString;
use Filament\Notifications\Notification;
use App\Filament\Resources\Servers\ServerResource;
use App\Filament\Resources\Sites\SiteResource;
use App\Filament\Resources\Providers\ProviderResource;
use App\Filament\Resources\PackageResource\Pages;
use App\Filament\Resources\PackageResource\RelationManagers;
class PackageResource extends Resource
{
protected static ?string $model = Package::class;
protected static string | \BackedEnum | null $navigationIcon = 'heroicon-o-swatch';
protected static ?int $navigationSort = 3;
public static function form(Schema $schema): Schema
{
return $schema
->components([
TextInput::make('name')
->label(__('Name'))
->required()
->columnSpan(2),
TextInput::make('maximum_sites')
->helperText(__('Set to 0 for unlimited'))
->integer()
->required(),
TextInput::make('maximum_servers')
->helperText(__('Set to 0 for unlimited'))
->integer()
->required(),
TextInput::make('stripe_plan_id')
->helperText(new HtmlString(__('Enter the pricing ID from Stripe here') . ' - <a href="https://docs.ploi-core.io/263-digging-deeper/743-using-stripe" target="ploi-docs-stripe" class="text-primary-500">How does this work?</a>'))
->label(__('Stripe ID'))
->columnSpan(2),
TextInput::make('price_monthly')
->label(__('Monthly price'))
->helperText(__('Fill this in if you want it to be monthly payments'))
->required(),
TextInput::make('price_yearly')
->label(__('Yearly price'))
->helperText(__('Fill this in if you want it to be yearly payments'))
->required(),
Select::make('currency')
->label(__('Currency'))
->options([
'usd' => 'USD $',
'eur' => 'Euro €',
'gbp' => 'GBP £',
'nok' => 'NOK (Norwegian Krone)',
'aud' => 'AUD (Australian dollar)',
'cad' => 'CAD (Canadian dollar)',
'inr' => 'INR (Indian ₹ rupee)',
'thb' => 'THB (Thai Baht)',
'brl' => 'BRL R$ (Brazilian Real)',
'nz' => 'NZD $ (New Zealand Dollar)',
])
->required(),
Grid::make()
->schema([
Section::make(__('Server permissions'))
->icon(ServerResource::getNavigationIcon())
->schema([
Checkbox::make('server_permissions.create')
->reactive()
->label('Allow server creation')
->helperText('This will allow users to create servers'),
Checkbox::make('server_permissions.update')
->label('Allow server updates')
->helperText('This will allow users to update servers'),
Checkbox::make('server_permissions.delete')
->label('Allow server deletion')
->helperText('This will allow users to delete servers'),
])
->columnSpan(1),
Section::make(__('Site permissions'))
->icon(SiteResource::getNavigationIcon())
->schema([
Checkbox::make('site_permissions.create')
->label('Allow site creation')
->helperText('This will allow users to create sites'),
Checkbox::make('site_permissions.update')
->label('Allow site updates')
->helperText('This will allow users to update sites'),
Checkbox::make('site_permissions.delete')
->label('Allow site deletion')
->helperText('This will allow users to delete sites'),
])
->columnSpan(1),
]),
Grid::make()
->schema([
Section::make(__('Available server providers'))
->description(__('These server providers will be available for users that are attached to this package.'))
->icon(ProviderResource::getNavigationIcon())
->schema([
CheckboxList::make('providers')
->relationship('providers', 'name')
->reactive(),
Grid::make(1)
->schema([
Actions::make([
Action::make('manage_provider_plans')
->label(__('Manage provider plans'))
->icon('heroicon-o-adjustments-horizontal')
->schema(function (Package $record) {
return $record->providers->sortBy('name')->map(function (Provider $provider) {
return Section::make($provider->label)
->description(__('Select the plans that should be available for this provider on this package.'))
->icon(ProviderResource::getNavigationIcon())
->statePath($provider->id)
->schema([
Toggle::make('select_specific_provider_plans')
->label(__('Select subset'))
->helperText(__('Check this box if you want to limit the provider plans available on this package.'))
->default(false)
->reactive()
->afterStateUpdated(function (Toggle $component, Set $set) use ($provider) {
$set(
path: "provider_plans",
state: $component->getState() ? $provider->plans->pluck('id') : [],
);
}),
CheckboxList::make("provider_plans")
->label(__('Select plans'))
->options(fn () => $provider->plans->mapWithKeys(fn (ProviderPlan $providerPlan) => [$providerPlan->id => $providerPlan->label ?? $providerPlan->plan_id])->all())
->visible(fn (Get $get) => $get('select_specific_provider_plans'))
->reactive()
->bulkToggleable()
->columns(2)
])
->collapsible();
})->all();
})
->fillForm(function (Package $record) {
return $record->providers->mapWithKeys(function (Provider $provider) use ($record) {
$providerPlanIds = $record->providerPlans()->whereBelongsTo($provider)->pluck('provider_plans.id');
return [$provider->id => [
'select_specific_provider_plans' => $providerPlanIds->isNotEmpty(),
'provider_plans' => $providerPlanIds->all(),
]];
})->all();
})
->action(function (Package $record, array $data) {
$providerPlanIds = collect($data)
// If `select_specific_provider_plans`, all provider plans are available. It could be that this
// option was deselected, and that we have some left over provider plans in the field that
// is now hidden. We will not include theSE IDs so that they ARE detached automatically.
->where('select_specific_provider_plans', true)
->pluck('provider_plans')
->flatten();
// Detaches provider plans not specifically selected.
$record->providerPlans()->sync($providerPlanIds);
Notification::make()
->title(__('Provider plans saved'))
->success()
->send();
})
->modalSubmitActionLabel(__('Save'))
->color('gray')
->disabled(function (Package $record, Get $get) {
$providers = collect($get('providers'))
->map(fn (string $id): int => (int)$id)
->sort();
return $record->providers->pluck('id')->map(fn (string $id): int => (int)$id)->sort()->toArray() !== $providers->all();
})
]),
Placeholder::make('save_warning')
->content(__('You\'ve changed the available server providers. Please save your changes before you can manage the provider plans.'))
->visible(function (Package $record, Get $get) {
$providers = collect($get('providers'))
->map(fn (string $id): int => (int)$id)
->sort();
return $record->providers->pluck('id')->map(fn (string $id): int => (int)$id)->sort()->toArray() !== $providers->all();
})
->hiddenLabel(),
])
->hiddenOn('create'),
])
->columnSpan(1)
])
->visible(function ($get) {
return $get('server_permissions')['create'];
})
]);
}
public static function table(Table $table): Table
{
return $table
->columns([
TextColumn::make('id')
->label('ID')
->searchable(),
TextColumn::make('name')
->label(__('Name'))
->description(function (Package $record) {
if (!$record->stripe_plan_id) {
return __('Not attached to Stripe.');
}
return "Attached to stripe - {$record->price_monthly} {$record->currency}";
}),
TextColumn::make('maximum_sites')
->formatStateUsing(fn (int $state) => $state === 0 ? __('Unlimited') : $state)
->label(__('Maximum sites')),
TextColumn::make('maximum_servers')
->formatStateUsing(fn (int $state) => $state === 0 ? __('Unlimited') : $state)
->label(__('Maximum servers')),
TextColumn::make('users_count')
->counts('users'),
])
->filters([
//
])
->recordActions([
EditAction::make(),
DeleteAction::make(),
])
->toolbarActions([
DeleteBulkAction::make(),
]);
}
public static function getRelations(): array
{
return [
UsersRelationManager::class,
];
}
public static function getPages(): array
{
return [
'index' => ListPackages::route('/'),
'create' => CreatePackage::route('/create'),
'edit' => EditPackage::route('/{record}/edit'),
];
}
}

View File

@@ -1,9 +1,9 @@
<?php <?php
namespace App\Filament\Resources\PackageResource\Pages; namespace App\Filament\Resources\Packages\Pages;
use Filament\Resources\Pages\CreateRecord; use Filament\Resources\Pages\CreateRecord;
use App\Filament\Resources\PackageResource; use App\Filament\Resources\Packages\PackageResource;
class CreatePackage extends CreateRecord class CreatePackage extends CreateRecord
{ {

View File

@@ -0,0 +1,27 @@
<?php
namespace App\Filament\Resources\Packages\Pages;
use Filament\Actions\DeleteAction;
use Filament\Actions;
use Filament\Resources\Pages\EditRecord;
use App\Filament\Resources\Packages\PackageResource;
class EditPackage extends EditRecord
{
protected static string $resource = PackageResource::class;
protected function getHeaderActions(): array
{
return [
DeleteAction::make(),
];
}
public function afterSave(): void
{
// Necessary to refresh, in order to load the updated saved relationships and
// correctly show or hide the "manage provider plans" warning placeholder.
$this->getRecord()->refresh();
}
}

View File

@@ -0,0 +1,20 @@
<?php
namespace App\Filament\Resources\Packages\Pages;
use Filament\Actions\CreateAction;
use Filament\Actions;
use Filament\Resources\Pages\ListRecords;
use App\Filament\Resources\Packages\PackageResource;
class ListPackages extends ListRecords
{
protected static string $resource = PackageResource::class;
protected function getHeaderActions(): array
{
return [
CreateAction::make(),
];
}
}

View File

@@ -1,13 +1,13 @@
<?php <?php
namespace App\Filament\Resources\PackageResource\RelationManagers; namespace App\Filament\Resources\Packages\RelationManagers;
use Filament\Schemas\Schema;
use Filament\Actions\Action;
use App\Models\User; use App\Models\User;
use Filament\Resources\Form; use Filament\Tables\Table;
use Filament\Resources\Table;
use Filament\Tables\Actions\Action;
use Filament\Forms\Components\Select; use Filament\Forms\Components\Select;
use App\Filament\Resources\UserResource; use App\Filament\Resources\Users\UserResource;
use Filament\Resources\RelationManagers\RelationManager; use Filament\Resources\RelationManagers\RelationManager;
class UsersRelationManager extends RelationManager class UsersRelationManager extends RelationManager
@@ -16,18 +16,19 @@ class UsersRelationManager extends RelationManager
protected static ?string $recordTitleAttribute = 'name'; protected static ?string $recordTitleAttribute = 'name';
public static function form(Form $form): Form public function form(Schema $schema): Schema
{ {
return UserResource::form($form); return UserResource::form($schema);
} }
public static function table(Table $table): Table public function table(Table $table): Table
{ {
return UserResource::table($table) return UserResource::table($table)
->appendHeaderActions([ ->headerActions([
...$table->getHeaderActions(),
Action::make('add_user') Action::make('add_user')
->label(__('Add user')) ->label(__('Add user'))
->form(fn (self $livewire) => [ ->schema(fn (self $livewire) => [
Select::make('user_id') Select::make('user_id')
->label('User') ->label('User')
->options(User::orderBy('name')->get()->mapWithKeys(fn (User $user) => [$user->id => $user->name])) ->options(User::orderBy('name')->get()->mapWithKeys(fn (User $user) => [$user->id => $user->name]))

View File

@@ -1,15 +1,15 @@
<?php <?php
namespace App\Filament\Resources\ProviderPlanResource\Pages; namespace App\Filament\Resources\ProviderPlans\Pages;
use Filament\Resources\Pages\ListRecords; use Filament\Resources\Pages\ListRecords;
use App\Filament\Resources\ProviderPlanResource; use App\Filament\Resources\ProviderPlans\ProviderPlanResource;
class ListProviderPlans extends ListRecords class ListProviderPlans extends ListRecords
{ {
protected static string $resource = ProviderPlanResource::class; protected static string $resource = ProviderPlanResource::class;
protected function getActions(): array protected function getHeaderActions(): array
{ {
return [ return [
// //

View File

@@ -1,30 +1,35 @@
<?php <?php
namespace App\Filament\Resources; namespace App\Filament\Resources\ProviderPlans;
use Filament\Schemas\Schema;
use Filament\Forms\Components\TextInput;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Actions\EditAction;
use App\Filament\Resources\ProviderPlans\Pages\ListProviderPlans;
use Filament\Forms;
use Filament\Tables; use Filament\Tables;
use App\Models\Provider; use App\Models\Provider;
use Filament\Tables\Table;
use App\Models\ProviderPlan; use App\Models\ProviderPlan;
use Filament\Resources\Form;
use Filament\Resources\Table;
use Filament\Resources\Resource; use Filament\Resources\Resource;
use Filament\Forms\Components\TextInput;
use App\Filament\Resources\ProviderPlanResource\Pages; use App\Filament\Resources\ProviderPlanResource\Pages;
class ProviderPlanResource extends Resource class ProviderPlanResource extends Resource
{ {
protected static ?string $model = ProviderPlan::class; protected static ?string $model = ProviderPlan::class;
protected static ?string $navigationIcon = 'heroicon-o-cube'; protected static string | \BackedEnum | null $navigationIcon = 'heroicon-o-cube';
protected static ?string $navigationGroup = 'Providers'; protected static string | \UnitEnum | null $navigationGroup = 'Providers';
protected static ?int $navigationSort = 2; protected static ?int $navigationSort = 2;
public static function form(Form $form): Form public static function form(Schema $schema): Schema
{ {
return $form return $schema
->schema([ ->components([
TextInput::make('label'), TextInput::make('label'),
]); ]);
} }
@@ -33,30 +38,32 @@ class ProviderPlanResource extends Resource
{ {
return $table return $table
->columns([ ->columns([
Tables\Columns\TextColumn::make('id')->label('ID')->searchable(), TextColumn::make('id')
Tables\Columns\TextColumn::make('provider.name') ->label('ID')
->searchable(),
TextColumn::make('provider.name')
->label(__('Provider')) ->label(__('Provider'))
->searchable(), ->searchable(),
Tables\Columns\TextColumn::make('plan_id') TextColumn::make('plan_id')
->label(__('Plan ID')) ->label(__('Plan ID'))
->searchable(), ->searchable(),
Tables\Columns\TextColumn::make('label') TextColumn::make('label')
->label(__('Label')) ->label(__('Label'))
->searchable(), ->searchable(),
Tables\Columns\TextColumn::make('created_at') TextColumn::make('created_at')
->label(__('Date')) ->label(__('Date'))
->sortable() ->sortable()
->dateTime(), ->dateTime(),
]) ])
->filters([ ->filters([
Tables\Filters\SelectFilter::make('provider_id') SelectFilter::make('provider_id')
->label(__('Provider')) ->label(__('Provider'))
->options(fn () => Provider::orderBy('name')->get()->mapWithKeys(fn (Provider $provider) => [$provider->id => $provider->name])), ->options(fn () => Provider::orderBy('name')->get()->mapWithKeys(fn (Provider $provider) => [$provider->id => $provider->name])),
]) ])
->actions([ ->recordActions([
Tables\Actions\EditAction::make(), EditAction::make(),
]) ])
->bulkActions([ ->toolbarActions([
// //
]) ])
->defaultSort('created_at', 'desc'); ->defaultSort('created_at', 'desc');
@@ -72,7 +79,7 @@ class ProviderPlanResource extends Resource
public static function getPages(): array public static function getPages(): array
{ {
return [ return [
'index' => Pages\ListProviderPlans::route('/'), 'index' => ListProviderPlans::route('/'),
]; ];
} }
} }

View File

@@ -1,19 +0,0 @@
<?php
namespace App\Filament\Resources\ProviderRegionResource\Pages;
use Filament\Pages\Actions;
use Filament\Resources\Pages\ListRecords;
use App\Filament\Resources\ProviderRegionResource;
class ListProviderRegions extends ListRecords
{
protected static string $resource = ProviderRegionResource::class;
protected function getActions(): array
{
return [
Actions\CreateAction::make(),
];
}
}

View File

@@ -0,0 +1,20 @@
<?php
namespace App\Filament\Resources\ProviderRegions\Pages;
use Filament\Actions\CreateAction;
use Filament\Actions;
use Filament\Resources\Pages\ListRecords;
use App\Filament\Resources\ProviderRegions\ProviderRegionResource;
class ListProviderRegions extends ListRecords
{
protected static string $resource = ProviderRegionResource::class;
protected function getHeaderActions(): array
{
return [
CreateAction::make(),
];
}
}

View File

@@ -1,11 +1,14 @@
<?php <?php
namespace App\Filament\Resources; namespace App\Filament\Resources\ProviderRegions;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use App\Filament\Resources\ProviderRegions\Pages\ListProviderRegions;
use Filament\Tables; use Filament\Tables;
use App\Models\Provider; use App\Models\Provider;
use Filament\Resources\Form; use Filament\Tables\Table;
use Filament\Resources\Table;
use App\Models\ProviderRegion; use App\Models\ProviderRegion;
use Filament\Resources\Resource; use Filament\Resources\Resource;
use App\Filament\Resources\ProviderRegionResource\Pages; use App\Filament\Resources\ProviderRegionResource\Pages;
@@ -14,16 +17,16 @@ class ProviderRegionResource extends Resource
{ {
protected static ?string $model = ProviderRegion::class; protected static ?string $model = ProviderRegion::class;
protected static ?string $navigationIcon = 'heroicon-o-globe'; protected static string | \BackedEnum | null $navigationIcon = 'heroicon-o-globe-americas';
protected static ?string $navigationGroup = 'Providers'; protected static string | \UnitEnum | null $navigationGroup = 'Providers';
protected static ?int $navigationSort = 3; protected static ?int $navigationSort = 3;
public static function form(Form $form): Form public static function form(Schema $schema): Schema
{ {
return $form return $schema
->schema([ ->components([
// //
]); ]);
} }
@@ -32,26 +35,28 @@ class ProviderRegionResource extends Resource
{ {
return $table return $table
->columns([ ->columns([
Tables\Columns\TextColumn::make('id')->label('ID')->searchable(), TextColumn::make('id')
Tables\Columns\TextColumn::make('provider.name') ->label('ID')
->searchable(),
TextColumn::make('provider.name')
->label(__('Provider')) ->label(__('Provider'))
->searchable(), ->searchable(),
Tables\Columns\TextColumn::make('region_id') TextColumn::make('region_id')
->searchable() ->searchable()
->label(__('Region')), ->label(__('Region')),
Tables\Columns\TextColumn::make('label') TextColumn::make('label')
->searchable() ->searchable()
->label(__('Label')), ->label(__('Label')),
]) ])
->filters([ ->filters([
Tables\Filters\SelectFilter::make('provider_id') SelectFilter::make('provider_id')
->label(__('Provider')) ->label(__('Provider'))
->options(fn () => Provider::orderBy('name')->get()->mapWithKeys(fn (Provider $provider) => [$provider->id => $provider->name])), ->options(fn () => Provider::orderBy('name')->pluck('name', 'id'))
]) ])
->actions([ ->recordActions([
// //
]) ])
->bulkActions([ ->toolbarActions([
// //
]); ]);
} }
@@ -66,7 +71,7 @@ class ProviderRegionResource extends Resource
public static function getPages(): array public static function getPages(): array
{ {
return [ return [
'index' => Pages\ListProviderRegions::route('/'), 'index' => ListProviderRegions::route('/'),
]; ];
} }
} }

View File

@@ -1,27 +0,0 @@
<?php
namespace App\Filament\Resources\ProviderResource\Pages;
use Filament\Pages\Actions\Action;
use Filament\Resources\Pages\ListRecords;
use App\Filament\Resources\ProviderResource;
class ListProviders extends ListRecords
{
protected $listeners = [
'$refresh',
];
protected static string $resource = ProviderResource::class;
protected function getActions(): array
{
return [
Action::make('synchronize_providers')
->label(__('Synchronize providers'))
->icon('heroicon-o-refresh')
->color('secondary')
->url(route('filament.resources.providers.synchronize')),
];
}
}

View File

@@ -1,29 +0,0 @@
<?php
namespace App\Filament\Resources\ProviderResource\Pages;
use Filament\Resources\Pages\Page;
use App\Filament\Resources\ProviderResource;
class SynchronizeProviders extends Page
{
protected static string $resource = ProviderResource::class;
protected static string $view = 'filament.resources.provider-resource.pages.synchronize-providers';
protected static ?string $title = 'Synchronize providers';
protected function getHeaderWidgets(): array
{
return [
ProviderResource\Widgets\AvailableProvidersOverview::class,
];
}
protected function getActions(): array
{
return [
//
];
}
}

View File

@@ -1,9 +1,9 @@
<?php <?php
namespace App\Filament\Resources\ProviderResource\Pages; namespace App\Filament\Resources\Providers\Pages;
use Filament\Resources\Pages\EditRecord; use Filament\Resources\Pages\EditRecord;
use App\Filament\Resources\ProviderResource; use App\Filament\Resources\Providers\ProviderResource;
class EditProvider extends EditRecord class EditProvider extends EditRecord
{ {

View File

@@ -0,0 +1,24 @@
<?php
namespace App\Filament\Resources\Providers\Pages;
use Filament\Actions\Action;
use Filament\Actions;
use Filament\Resources\Pages\ListRecords;
use App\Filament\Resources\Providers\ProviderResource;
class ListProviders extends ListRecords
{
protected static string $resource = ProviderResource::class;
protected function getHeaderActions(): array
{
return [
Action::make('synchronize_providers')
->label(__('Synchronize providers'))
->icon('heroicon-o-arrow-path')
->color('gray')
->url(ProviderResource::getUrl('synchronize')),
];
}
}

View File

@@ -0,0 +1,30 @@
<?php
namespace App\Filament\Resources\Providers\Pages;
use App\Filament\Resources\Providers\Widgets\AvailableProvidersOverview;
use Filament\Resources\Pages\Page;
use App\Filament\Resources\Providers\ProviderResource;
class SynchronizeProviders extends Page
{
protected static string $resource = ProviderResource::class;
protected string $view = 'filament.resources.provider-resource.pages.synchronize-providers';
protected static ?string $title = 'Synchronize providers';
protected function getHeaderWidgets(): array
{
return [
AvailableProvidersOverview::class,
];
}
protected function getHeaderActions(): array
{
return [
//
];
}
}

View File

@@ -1,44 +1,52 @@
<?php <?php
namespace App\Filament\Resources; namespace App\Filament\Resources\Providers;
use Filament\Schemas\Schema;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\CheckboxList;
use Filament\Tables\Columns\TextColumn;
use Filament\Actions\EditAction;
use Filament\Actions\Action;
use App\Filament\Resources\Providers\Pages\ListProviders;
use App\Filament\Resources\Providers\Pages\SynchronizeProviders;
use App\Filament\Resources\Providers\Pages\EditProvider;
use Filament\Forms; use Filament\Forms;
use Filament\Tables; use Filament\Tables;
use App\Models\Provider; use App\Models\Provider;
use Filament\Tables\Table;
use App\Models\ProviderPlan; use App\Models\ProviderPlan;
use Filament\Resources\Form;
use Filament\Resources\Table;
use Filament\Resources\Resource; use Filament\Resources\Resource;
use Filament\Notifications\Notification; use Filament\Notifications\Notification;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use App\Filament\Resources\ProviderResource\Pages; use App\Filament\Resources\ProviderResource\Pages;
use App\Actions\Provider\SynchronizeProviderAction; use App\Actions\Provider\SynchronizeProviderAction;
use App\Filament\Resources\ProviderResource\Widgets\AvailableProvidersOverview; use App\Filament\Resources\Providers\Widgets\AvailableProvidersOverview;
class ProviderResource extends Resource class ProviderResource extends Resource
{ {
protected static ?string $model = Provider::class; protected static ?string $model = Provider::class;
protected static ?string $navigationIcon = 'heroicon-o-cloud-upload'; protected static string | \BackedEnum | null $navigationIcon = 'heroicon-o-cloud-arrow-up';
protected static ?string $navigationGroup = 'Providers'; protected static string | \UnitEnum | null $navigationGroup = 'Providers';
protected static ?int $navigationSort = 1; protected static ?int $navigationSort = 1;
public static function form(Form $form): Form public static function form(Schema $schema): Schema
{ {
return $form return $schema
->schema([ ->components([
Forms\Components\TextInput::make('name') TextInput::make('name')
->label(__('Name')) ->label(__('Name'))
->required() ->required()
->columnSpan(2), ->columnSpan(2),
Forms\Components\CheckboxList::make('allowed_plans') CheckboxList::make('allowed_plans')
->options(function (Provider $record) { ->options(function (Provider $record) {
return $record->plans->mapWithKeys(fn (ProviderPlan $plan) => [$plan->id => $plan->label ?? $plan->plan_id]); return $record->plans->mapWithKeys(fn (ProviderPlan $plan) => [$plan->id => $plan->label ?? $plan->plan_id]);
}) })
->label(__('Allowed Plans')), ->label(__('Allowed Plans')),
Forms\Components\CheckboxList::make('allowed_regions') CheckboxList::make('allowed_regions')
->options(fn (Provider $record) => $record->regions->pluck('label', 'id')) ->options(fn (Provider $record) => $record->regions->pluck('label', 'id'))
->label(__('Allowed Regions')), ->label(__('Allowed Regions')),
]); ]);
@@ -48,17 +56,19 @@ class ProviderResource extends Resource
{ {
return $table return $table
->columns([ ->columns([
Tables\Columns\TextColumn::make('id')->label('ID')->searchable(), TextColumn::make('id')
Tables\Columns\TextColumn::make('name') ->label('ID')
->searchable(),
TextColumn::make('name')
->description(function (Provider $record) { ->description(function (Provider $record) {
return "{$record->plans_count} plan(s) · {$record->regions_count} region(s)"; return "{$record->plans_count} plan(s) · {$record->regions_count} region(s)";
}) })
->label(__('Name')) ->label(__('Name'))
->searchable(), ->searchable(),
Tables\Columns\TextColumn::make('label') TextColumn::make('label')
->label(__('Label')) ->label(__('Label'))
->searchable(), ->searchable(),
Tables\Columns\TextColumn::make('created_at') TextColumn::make('created_at')
->label(__('Date')) ->label(__('Date'))
->sortable() ->sortable()
->dateTime(), ->dateTime(),
@@ -66,22 +76,22 @@ class ProviderResource extends Resource
->filters([ ->filters([
// //
]) ])
->actions([ ->recordActions([
Tables\Actions\EditAction::make(), EditAction::make(),
Tables\Actions\Action::make('synchronize_provider') Action::make('synchronize_provider')
->label(__('Synchronize')) ->label(__('Synchronize'))
->tooltip(__('This will synchronize the latest data from this provider to your Ploi Core installation')) ->tooltip(__('This will synchronize the latest data from this provider to your Ploi Core installation'))
->icon('heroicon-o-refresh') ->icon('heroicon-o-arrow-path')
->action(function (Provider $record) { ->action(function (Provider $record) {
$provider = app(SynchronizeProviderAction::class)->execute($record->ploi_id); $provider = app(SynchronizeProviderAction::class)->execute($record->ploi_id);
Notification::make() Notification::make()
->body(__('Provider :provider synchronized successfully.', ['provider' => $provider->name])) ->title(__('Provider :provider synchronized successfully.', ['provider' => $provider->name]))
->success() ->success()
->send(); ->send();
}), }),
]) ])
->bulkActions([ ->toolbarActions([
// //
]) ])
->defaultSort('created_at', 'desc'); ->defaultSort('created_at', 'desc');
@@ -110,9 +120,9 @@ class ProviderResource extends Resource
public static function getPages(): array public static function getPages(): array
{ {
return [ return [
'index' => Pages\ListProviders::route('/'), 'index' => ListProviders::route('/'),
'synchronize' => Pages\SynchronizeProviders::route('/synchronize'), 'synchronize' => SynchronizeProviders::route('/synchronize'),
'edit' => Pages\EditProvider::route('/{record}'), 'edit' => EditProvider::route('/{record}'),
]; ];
} }
} }

View File

@@ -1,10 +1,10 @@
<?php <?php
namespace App\Filament\Resources\ProviderResource\Widgets; namespace App\Filament\Resources\Providers\Widgets;
use Filament\Actions\Action;
use App\Models\AvailableProvider; use App\Models\AvailableProvider;
use Filament\Widgets\TableWidget; use Filament\Widgets\TableWidget;
use Filament\Tables\Actions\Action;
use Filament\Tables\Columns\TextColumn; use Filament\Tables\Columns\TextColumn;
use Filament\Notifications\Notification; use Filament\Notifications\Notification;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
@@ -13,10 +13,6 @@ use Illuminate\Database\Eloquent\Relations\Relation;
class AvailableProvidersOverview extends TableWidget class AvailableProvidersOverview extends TableWidget
{ {
protected $listeners = [
'$refresh',
];
protected int|string|array $columnSpan = 'full'; protected int|string|array $columnSpan = 'full';
protected static ?string $heading = 'Available Providers'; protected static ?string $heading = 'Available Providers';
@@ -46,14 +42,14 @@ class AvailableProvidersOverview extends TableWidget
return [ return [
Action::make('synchronize_provider') Action::make('synchronize_provider')
->label(__('Synchronize')) ->label(__('Synchronize'))
->icon('heroicon-o-refresh') ->icon('heroicon-o-arrow-path')
->action(function (AvailableProvider $record, self $livewire) { ->action(function (AvailableProvider $record, self $livewire) {
$provider = app(SynchronizeProviderAction::class)->execute($record->id); $provider = app(SynchronizeProviderAction::class)->execute($record->id);
$livewire->emit('$refresh'); $livewire->dispatch('$refresh');
Notification::make() Notification::make()
->body(__('Provider :provider synchronized successfully.', ['provider' => $provider->name])) ->title(__('Provider :provider synchronized successfully.', ['provider' => $provider->name]))
->success() ->success()
->send(); ->send();
}), }),

View File

@@ -1,19 +0,0 @@
<?php
namespace App\Filament\Resources\RedirectResource\Pages;
use Filament\Pages\Actions;
use Filament\Resources\Pages\ListRecords;
use App\Filament\Resources\RedirectResource;
class ListRedirects extends ListRecords
{
protected static string $resource = RedirectResource::class;
protected function getActions(): array
{
return [
Actions\CreateAction::make(),
];
}
}

View File

@@ -0,0 +1,20 @@
<?php
namespace App\Filament\Resources\Redirects\Pages;
use Filament\Actions\CreateAction;
use Filament\Actions;
use Filament\Resources\Pages\ListRecords;
use App\Filament\Resources\Redirects\RedirectResource;
class ListRedirects extends ListRecords
{
protected static string $resource = RedirectResource::class;
protected function getHeaderActions(): array
{
return [
CreateAction::make(),
];
}
}

View File

@@ -1,12 +1,15 @@
<?php <?php
namespace App\Filament\Resources; namespace App\Filament\Resources\Redirects;
use Filament\Schemas\Schema;
use Filament\Forms\Components\TextInput;
use Filament\Tables\Columns\TextColumn;
use App\Filament\Resources\Redirects\Pages\ListRedirects;
use Filament\Forms; use Filament\Forms;
use Filament\Tables; use Filament\Tables;
use App\Models\Redirect; use App\Models\Redirect;
use Filament\Resources\Form; use Filament\Tables\Table;
use Filament\Resources\Table;
use Filament\Resources\Resource; use Filament\Resources\Resource;
use App\Filament\Resources\RedirectResource\Pages; use App\Filament\Resources\RedirectResource\Pages;
@@ -14,27 +17,23 @@ class RedirectResource extends Resource
{ {
protected static ?string $model = Redirect::class; protected static ?string $model = Redirect::class;
protected static ?string $navigationIcon = 'heroicon-o-external-link'; protected static string | \BackedEnum | null $navigationIcon = 'heroicon-o-arrow-top-right-on-square';
protected static ?string $navigationGroup = 'Site management'; protected static string | \UnitEnum | null $navigationGroup = 'Site management';
protected static ?int $navigationSort = 5; protected static ?int $navigationSort = 5;
public static function form(Form $form): Form public static function form(Schema $schema): Schema
{ {
return $form return $schema
->schema([ ->components([
Forms\Components\TextInput::make('site_id'), TextInput::make('site_id'),
Forms\Components\TextInput::make('server_id'), TextInput::make('server_id'),
Forms\Components\TextInput::make('status') TextInput::make('status'),
->maxLength(255), TextInput::make('ploi_id'),
Forms\Components\TextInput::make('ploi_id'), TextInput::make('redirect_from'),
Forms\Components\TextInput::make('redirect_from') TextInput::make('redirect_to'),
->maxLength(255), TextInput::make('type'),
Forms\Components\TextInput::make('redirect_to')
->maxLength(255),
Forms\Components\TextInput::make('type')
->maxLength(255),
]); ]);
} }
@@ -42,33 +41,35 @@ class RedirectResource extends Resource
{ {
return $table return $table
->columns([ ->columns([
Tables\Columns\TextColumn::make('redirect_from') TextColumn::make('redirect_from')
->wrap() ->wrap()
->label(__('Redirect from')) ->label(__('Redirect from'))
->searchable(), ->searchable(),
Tables\Columns\TextColumn::make('redirect_to') TextColumn::make('redirect_to')
->wrap() ->wrap()
->label(__('Redirect to')) ->label(__('Redirect to'))
->searchable(), ->searchable(),
Tables\Columns\TextColumn::make('server.name') TextColumn::make('server.name')
->label(__('Server')) ->label(__('Server'))
->searchable(), ->searchable(),
Tables\Columns\TextColumn::make('site.domain') TextColumn::make('site.domain')
->label(__('Site')) ->label(__('Site'))
->searchable(), ->searchable(),
Tables\Columns\TextColumn::make('type') TextColumn::make('type')
->label(__('Type')), ->label(__('Type')),
Tables\Columns\BadgeColumn::make('status') TextColumn::make('status')
->enum([ ->badge()
->formatStateUsing(fn (string $state) => match ($state) {
Redirect::STATUS_BUSY => __('Busy'), Redirect::STATUS_BUSY => __('Busy'),
Redirect::STATUS_ACTIVE => __('Active'), Redirect::STATUS_ACTIVE => __('Active'),
]) default => __('Unknown status')
})
->colors([ ->colors([
'warning' => Redirect::STATUS_BUSY, 'warning' => Redirect::STATUS_BUSY,
'success' => Redirect::STATUS_ACTIVE, 'success' => Redirect::STATUS_ACTIVE,
]) ])
->label(__('Status')), ->label(__('Status')),
Tables\Columns\TextColumn::make('created_at') TextColumn::make('created_at')
->label(__('Date')) ->label(__('Date'))
->sortable() ->sortable()
->dateTime(), ->dateTime(),
@@ -76,10 +77,10 @@ class RedirectResource extends Resource
->filters([ ->filters([
// //
]) ])
->actions([ ->recordActions([
// //
]) ])
->bulkActions([ ->toolbarActions([
// //
]) ])
->defaultSort('created_at', 'desc'); ->defaultSort('created_at', 'desc');
@@ -95,7 +96,7 @@ class RedirectResource extends Resource
public static function getPages(): array public static function getPages(): array
{ {
return [ return [
'index' => Pages\ListRedirects::route('/'), 'index' => ListRedirects::route('/'),
]; ];
} }
} }

View File

@@ -1,19 +0,0 @@
<?php
namespace App\Filament\Resources\ServerResource\Pages;
use Filament\Pages\Actions;
use Filament\Resources\Pages\EditRecord;
use App\Filament\Resources\ServerResource;
class EditServer extends EditRecord
{
protected static string $resource = ServerResource::class;
protected function getActions(): array
{
return [
Actions\DeleteAction::make(),
];
}
}

View File

@@ -1,37 +0,0 @@
<?php
namespace App\Filament\Resources\ServerResource\Pages;
use Filament\Pages\Actions\Action;
use Filament\Resources\Pages\ListRecords;
use Illuminate\Database\Eloquent\Builder;
use App\Filament\Resources\ServerResource;
class ListServers extends ListRecords
{
protected static string $resource = ServerResource::class;
protected function getActions(): array
{
return [
Action::make('synchronize_servers')
->label(__('Synchronize servers'))
->icon('heroicon-o-refresh')
->color('secondary')
->url(route('filament.resources.servers.synchronize')),
...parent::getActions(),
];
}
protected function applySearchToTableQuery(Builder $query): Builder
{
if (filled($searchTerm = $this->getTableSearchQuery())) {
$query
->where('domain', 'LIKE', "%{$searchTerm}%")
->orWhereHas('users', fn (Builder $query) => $query->where('name', 'LIKE', "%{$searchTerm}%"))
->orWhereHas('users', fn (Builder $query) => $query->where('email', 'LIKE', "%{$searchTerm}%"));
}
return $query;
}
}

View File

@@ -1,42 +0,0 @@
<?php
namespace App\Filament\Resources\ServerResource\RelationManagers;
use Filament\Tables;
use Filament\Resources\Form;
use Filament\Resources\Table;
use App\Filament\Resources\UserResource;
use Filament\Resources\RelationManagers\RelationManager;
class UsersRelationManager extends RelationManager
{
protected static string $relationship = 'users';
protected static ?string $recordTitleAttribute = 'name';
public static function getLabel(): ?string
{
return __('User');
}
protected static function getPluralModelLabel(): string
{
return __('Users');
}
public static function form(Form $form): Form
{
return UserResource::form($form);
}
public static function table(Table $table): Table
{
return UserResource::table($table)
->appendHeaderActions([
Tables\Actions\AttachAction::make()->preloadRecordSelect(),
])
->appendActions([
Tables\Actions\DetachAction::make(),
]);
}
}

View File

@@ -1,8 +1,8 @@
<?php <?php
namespace App\Filament\Resources\ServerResource\Pages; namespace App\Filament\Resources\Servers\Pages;
use App\Filament\Resources\ServerResource; use App\Filament\Resources\Servers\ServerResource;
use Filament\Resources\Pages\CreateRecord; use Filament\Resources\Pages\CreateRecord;
class CreateServer extends CreateRecord class CreateServer extends CreateRecord

View File

@@ -0,0 +1,20 @@
<?php
namespace App\Filament\Resources\Servers\Pages;
use Filament\Actions\DeleteAction;
use Filament\Actions;
use Filament\Resources\Pages\EditRecord;
use App\Filament\Resources\Servers\ServerResource;
class EditServer extends EditRecord
{
protected static string $resource = ServerResource::class;
protected function getHeaderActions(): array
{
return [
DeleteAction::make(),
];
}
}

View File

@@ -0,0 +1,25 @@
<?php
namespace App\Filament\Resources\Servers\Pages;
use Filament\Actions\Action;
use Filament\Actions;
use Filament\Resources\Pages\ListRecords;
use App\Filament\Resources\Servers\ServerResource;
class ListServers extends ListRecords
{
protected static string $resource = ServerResource::class;
protected function getHeaderActions(): array
{
return [
Action::make('synchronize_servers')
->label(__('Synchronize servers'))
->icon('heroicon-o-arrow-path')
->color('gray')
->url(ServerResource::getUrl('synchronize')),
...parent::getHeaderActions(),
];
}
}

View File

@@ -1,38 +1,40 @@
<?php <?php
namespace App\Filament\Resources\ServerResource\Pages; namespace App\Filament\Resources\Servers\Pages;
use App\Filament\Resources\Servers\Widgets\AvailableServersOverview;
use Filament\Actions\Action;
use Filament\Actions;
use App\Models\Server; use App\Models\Server;
use App\Services\Ploi\Ploi; use App\Services\Ploi\Ploi;
use Filament\Pages\Actions\Action;
use Filament\Resources\Pages\Page; use Filament\Resources\Pages\Page;
use Filament\Notifications\Notification; use Filament\Notifications\Notification;
use App\Filament\Resources\ServerResource; use App\Filament\Resources\Servers\ServerResource;
class SynchronizeServers extends Page class SynchronizeServers extends Page
{ {
protected static string $resource = ServerResource::class; protected static string $resource = ServerResource::class;
protected static string $view = 'filament.resources.server-resource.pages.synchronize-servers'; protected string $view = 'filament.resources.server-resource.pages.synchronize-servers';
protected static ?string $title = 'Synchronize servers'; protected static ?string $title = 'Synchronize servers';
protected function getHeaderWidgets(): array protected function getHeaderWidgets(): array
{ {
return [ return [
ServerResource\Widgets\AvailableServersOverview::class, AvailableServersOverview::class,
]; ];
} }
protected function getActions(): array protected function getHeaderActions(): array
{ {
return [ return [
Action::make('synchronize_servers') Action::make('synchronize_servers')
->label(__('Synchronize all servers')) ->label(__('Synchronize all servers'))
->icon('heroicon-o-refresh') ->icon('heroicon-o-arrow-path')
->requiresConfirmation() ->requiresConfirmation()
->modalHeading('Synchronize servers') ->modalHeading('Synchronize servers')
->modalSubheading('This will synchronize all the servers that are listed in the table, to your Ploi Core installation.') ->modalDescription('This will synchronize all the servers that are listed in the table, to your Ploi Core installation.')
->action(function () { ->action(function () {
$availableServers = Ploi::make()->synchronize()->servers()->getData(); $availableServers = Ploi::make()->synchronize()->servers()->getData();
@@ -51,7 +53,7 @@ class SynchronizeServers extends Page
} }
Notification::make() Notification::make()
->body(__('Servers synchronized successfully.')) ->title(__('Servers synchronized successfully.'))
->success() ->success()
->send(); ->send();
}), }),

View File

@@ -1,10 +1,10 @@
<?php <?php
namespace App\Filament\Resources\ServerResource\RelationManagers; namespace App\Filament\Resources\Servers\RelationManagers;
use Filament\Resources\Form; use Filament\Schemas\Schema;
use Filament\Resources\Table; use Filament\Tables\Table;
use App\Filament\Resources\SiteResource; use App\Filament\Resources\Sites\SiteResource;
use Filament\Resources\RelationManagers\RelationManager; use Filament\Resources\RelationManagers\RelationManager;
class SitesRelationManager extends RelationManager class SitesRelationManager extends RelationManager
@@ -23,12 +23,12 @@ class SitesRelationManager extends RelationManager
return __('Sites'); return __('Sites');
} }
public static function form(Form $form): Form public function form(Schema $schema): Schema
{ {
return SiteResource::form($form); return SiteResource::form($schema);
} }
public static function table(Table $table): Table public function table(Table $table): Table
{ {
return SiteResource::table($table); return SiteResource::table($table);
} }

View File

@@ -0,0 +1,47 @@
<?php
namespace App\Filament\Resources\Servers\RelationManagers;
use Filament\Schemas\Schema;
use Filament\Actions\AttachAction;
use Filament\Actions\DetachAction;
use Filament\Tables;
use Filament\Tables\Table;
use App\Filament\Resources\Users\UserResource;
use Filament\Resources\RelationManagers\RelationManager;
class UsersRelationManager extends RelationManager
{
protected static string $relationship = 'users';
protected static ?string $recordTitleAttribute = 'name';
public static function getLabel(): ?string
{
return __('User');
}
protected static function getPluralModelLabel(): string
{
return __('Users');
}
public function form(Schema $schema): Schema
{
return UserResource::form($schema);
}
public function table(Table $table): Table
{
return UserResource::table($table)
->headerActions([
...$table->getHeaderActions(),
AttachAction::make()
->preloadRecordSelect(),
])
->recordActions([
...$table->getActions(),
DetachAction::make(),
]);
}
}

View File

@@ -1,13 +1,24 @@
<?php <?php
namespace App\Filament\Resources; namespace App\Filament\Resources\Servers;
use Filament\Schemas\Schema;
use Filament\Forms\Components\TextInput;
use Filament\Tables\Columns\TextColumn;
use Filament\Actions\EditAction;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use Filament\Actions\DeleteBulkAction;
use App\Filament\Resources\Servers\RelationManagers\UsersRelationManager;
use App\Filament\Resources\Servers\RelationManagers\SitesRelationManager;
use App\Filament\Resources\Servers\Pages\ListServers;
use App\Filament\Resources\Servers\Pages\EditServer;
use App\Filament\Resources\Servers\Pages\SynchronizeServers;
use Filament\Forms; use Filament\Forms;
use App\Models\User; use App\Models\User;
use Filament\Tables; use Filament\Tables;
use App\Models\Server; use App\Models\Server;
use Filament\Resources\Form; use Filament\Tables\Table;
use Filament\Resources\Table;
use Filament\Resources\Resource; use Filament\Resources\Resource;
use Illuminate\Support\HtmlString; use Illuminate\Support\HtmlString;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
@@ -19,9 +30,9 @@ class ServerResource extends Resource
{ {
protected static ?string $model = Server::class; protected static ?string $model = Server::class;
protected static ?string $navigationIcon = 'heroicon-o-server'; protected static string | \BackedEnum | null $navigationIcon = 'heroicon-o-server';
protected static ?string $navigationGroup = 'Server management'; protected static string | \UnitEnum | null $navigationGroup = 'Server management';
protected static ?string $recordTitleAttribute = 'name'; protected static ?string $recordTitleAttribute = 'name';
@@ -30,23 +41,23 @@ class ServerResource extends Resource
return ['name', 'ip', 'internal_ip', 'id']; return ['name', 'ip', 'internal_ip', 'id'];
} }
public static function form(Form $form): Form public static function form(Schema $schema): Schema
{ {
return $form return $schema
->schema([ ->components([
Forms\Components\TextInput::make('name') TextInput::make('name')
->required() ->required()
->label(__('Name')) ->label(__('Name'))
->columnSpan(2), ->columnSpan(2),
Forms\Components\TextInput::make('ip') TextInput::make('ip')
->required() ->required()
->label('IP address') ->label('IP address')
->columnSpan(2), ->columnSpan(2),
Forms\Components\TextInput::make('internal_ip') TextInput::make('internal_ip')
->required() ->required()
->label('Internal IP address') ->label('Internal IP address')
->columnSpan(2), ->columnSpan(2),
Forms\Components\TextInput::make('maximum_sites') TextInput::make('maximum_sites')
->label(__('Maximum sites')) ->label(__('Maximum sites'))
->integer() ->integer()
->required() ->required()
@@ -58,55 +69,66 @@ class ServerResource extends Resource
{ {
return $table return $table
->columns([ ->columns([
Tables\Columns\TextColumn::make('name') TextColumn::make('name')
->label(__('Name')) ->label(__('Name'))
->searchable(), ->searchable(),
Tables\Columns\BadgeColumn::make('status') TextColumn::make('status')
->label(__('Status')) ->label(__('Status'))
->enum([ ->badge()
->formatStateUsing(fn (string $state) => match ($state) {
Server::STATUS_BUSY => __('Busy'), Server::STATUS_BUSY => __('Busy'),
Server::STATUS_ACTIVE => __('Active'), Server::STATUS_ACTIVE => __('Active'),
]) default => __('Unknown status')
})
->colors([ ->colors([
'warning' => Server::STATUS_BUSY, 'warning' => Server::STATUS_BUSY,
'success' => Server::STATUS_ACTIVE, 'success' => Server::STATUS_ACTIVE,
]), ]),
Tables\Columns\TextColumn::make('users') TextColumn::make('users')
->label(__('Users')) ->label(__('Users'))
->wrap() ->wrap()
->getStateUsing(function (Server $record) { ->formatStateUsing(function (Server $record) {
$state = $record $state = $record
->users ->users
->map(function (User $user) { ->map(function (User $user) {
return '<a href="' . route('filament.resources.users.edit', ['record' => $user]) . '" class="text-primary-600">' . $user->name . '</a>'; return '<a href="' . UserResource::getUrl('edit', ['record' => $user]) . '" class="text-primary-600" style="white-space: nowrap">' . $user->name . '</a>';
}) })
->implode(', ') ?: '-'; ->implode(', ') ?: '-';
return new HtmlString($state); return new HtmlString($state);
})
->searchable(query: function (Builder $query, string $search) {
return $query->whereHas('users', function (Builder $query) use ($search) {
return $query
->where('name', 'LIKE', "%{$search}%")
->orWhere('email', 'LIKE', "%{$search}%");
});
}), }),
Tables\Columns\TextColumn::make('maximum_sites') TextColumn::make('maximum_sites')
->label(__('Max sites')) ->label(__('Max sites'))
->formatStateUsing(fn (Server $record) => $record->maximum_sites . " (Current: {$record->sites_count})"), ->formatStateUsing(fn (Server $record) => $record->maximum_sites . " (Current: {$record->sites_count})")
Tables\Columns\TextColumn::make('ip') ->counts('sites'),
TextColumn::make('ip')
->label(__('IP')), ->label(__('IP')),
Tables\Columns\TextColumn::make('created_at') TextColumn::make('created_at')
->label(__('Date')) ->label(__('Date'))
->dateTime(), ->dateTime(),
]) ])
->filters([ ->filters([
// //
]) ])
->actions([ ->recordActions([
Tables\Actions\EditAction::make(), EditAction::make(),
Tables\Actions\Action::make('synchronize_server') Action::make('synchronize_server')
->label(__('Synchronize')) ->label(__('Synchronize'))
->tooltip(__('This will synchronize the latest data from this provider to your Ploi Core installation')) ->tooltip(__('This will synchronize the latest data from this provider to your Ploi Core installation'))
->icon('heroicon-o-refresh') ->icon('heroicon-o-arrow-path')
->action(fn (Server $record) => app(SynchronizeServerAction::class)->execute($record->ploi_id)) ->action(fn (Server $record) => app(SynchronizeServerAction::class)->execute($record->ploi_id))
->visible(fn (Server $record) => $record->status === Server::STATUS_ACTIVE), ->visible(fn (Server $record) => $record->status === Server::STATUS_ACTIVE),
DeleteAction::make(),
]) ])
->bulkActions([ ->toolbarActions([
Tables\Actions\DeleteBulkAction::make(), DeleteBulkAction::make(),
]); ]);
} }
@@ -120,17 +142,17 @@ class ServerResource extends Resource
public static function getRelations(): array public static function getRelations(): array
{ {
return [ return [
RelationManagers\UsersRelationManager::class, UsersRelationManager::class,
RelationManagers\SitesRelationManager::class, SitesRelationManager::class,
]; ];
} }
public static function getPages(): array public static function getPages(): array
{ {
return [ return [
'index' => Pages\ListServers::route('/'), 'index' => ListServers::route('/'),
'edit' => Pages\EditServer::route('/{record}/edit'), 'edit' => EditServer::route('/{record}/edit'),
'synchronize' => Pages\SynchronizeServers::route('/synchronize'), 'synchronize' => SynchronizeServers::route('/synchronize'),
]; ];
} }
} }

View File

@@ -1,10 +1,10 @@
<?php <?php
namespace App\Filament\Resources\ServerResource\Widgets; namespace App\Filament\Resources\Servers\Widgets;
use Filament\Actions\Action;
use App\Models\AvailableServer; use App\Models\AvailableServer;
use Filament\Widgets\TableWidget; use Filament\Widgets\TableWidget;
use Filament\Tables\Actions\Action;
use Filament\Tables\Columns\TextColumn; use Filament\Tables\Columns\TextColumn;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use App\Actions\Server\SynchronizeServerAction; use App\Actions\Server\SynchronizeServerAction;
@@ -12,10 +12,6 @@ use Illuminate\Database\Eloquent\Relations\Relation;
class AvailableServersOverview extends TableWidget class AvailableServersOverview extends TableWidget
{ {
protected $listeners = [
'$refresh',
];
protected int|string|array $columnSpan = 'full'; protected int|string|array $columnSpan = 'full';
protected static ?string $heading = 'Available servers'; protected static ?string $heading = 'Available servers';
@@ -44,7 +40,7 @@ class AvailableServersOverview extends TableWidget
return [ return [
Action::make('synchronize_server') Action::make('synchronize_server')
->label(__('Synchronize')) ->label(__('Synchronize'))
->icon('heroicon-o-refresh') ->icon('heroicon-o-arrow-path')
->action(function (AvailableServer $record) { ->action(function (AvailableServer $record) {
app(SynchronizeServerAction::class)->execute($record->id); app(SynchronizeServerAction::class)->execute($record->id);
}), }),

View File

@@ -1,19 +0,0 @@
<?php
namespace App\Filament\Resources\SiteResource\Pages;
use Filament\Pages\Actions;
use App\Filament\Resources\SiteResource;
use Filament\Resources\Pages\EditRecord;
class EditSite extends EditRecord
{
protected static string $resource = SiteResource::class;
protected function getActions(): array
{
return [
Actions\DeleteAction::make(),
];
}
}

View File

@@ -1,41 +0,0 @@
<?php
namespace App\Filament\Resources\SiteResource\Pages;
use App\Traits\HasPloi;
use Filament\Pages\Actions\Action;
use App\Filament\Resources\SiteResource;
use Filament\Resources\Pages\ListRecords;
use Illuminate\Database\Eloquent\Builder;
class ListSites extends ListRecords
{
use HasPloi;
protected static string $resource = SiteResource::class;
protected function getActions(): array
{
return [
Action::make('synchronize_sites')
->label(__('Synchronize sites'))
->icon('heroicon-o-refresh')
->color('secondary')
->url(route('filament.resources.sites.synchronize')),
...parent::getActions()
];
}
protected function applySearchToTableQuery(Builder $query): Builder
{
if (filled($searchTerm = $this->getTableSearchQuery())) {
$query
->where('domain', 'LIKE', "%{$searchTerm}%")
->orWhereHas('users', fn (Builder $query) => $query->where('name', 'LIKE', "%{$searchTerm}%"))
->orWhereHas('users', fn (Builder $query) => $query->where('email', 'LIKE', "%{$searchTerm}%"));
}
return $query;
}
}

View File

@@ -1,19 +0,0 @@
<?php
namespace App\Filament\Resources\SiteSystemUserResource\Pages;
use Filament\Pages\Actions;
use Filament\Resources\Pages\ListRecords;
use App\Filament\Resources\SiteSystemUserResource;
class ListSiteSystemUsers extends ListRecords
{
protected static string $resource = SiteSystemUserResource::class;
protected function getActions(): array
{
return [
Actions\CreateAction::make(),
];
}
}

View File

@@ -0,0 +1,20 @@
<?php
namespace App\Filament\Resources\SiteSystemUsers\Pages;
use Filament\Actions\CreateAction;
use Filament\Actions;
use Filament\Resources\Pages\ListRecords;
use App\Filament\Resources\SiteSystemUsers\SiteSystemUserResource;
class ListSiteSystemUsers extends ListRecords
{
protected static string $resource = SiteSystemUserResource::class;
protected function getHeaderActions(): array
{
return [
CreateAction::make(),
];
}
}

View File

@@ -1,10 +1,12 @@
<?php <?php
namespace App\Filament\Resources; namespace App\Filament\Resources\SiteSystemUsers;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use App\Filament\Resources\SiteSystemUsers\Pages\ListSiteSystemUsers;
use Filament\Tables; use Filament\Tables;
use Filament\Resources\Form; use Filament\Tables\Table;
use Filament\Resources\Table;
use App\Models\SiteSystemUser; use App\Models\SiteSystemUser;
use Filament\Resources\Resource; use Filament\Resources\Resource;
use App\Filament\Resources\SiteSystemUserResource\Pages; use App\Filament\Resources\SiteSystemUserResource\Pages;
@@ -13,16 +15,16 @@ class SiteSystemUserResource extends Resource
{ {
protected static ?string $model = SiteSystemUser::class; protected static ?string $model = SiteSystemUser::class;
protected static ?string $navigationIcon = 'heroicon-o-user-group'; protected static string | \BackedEnum | null $navigationIcon = 'heroicon-o-user-group';
protected static ?string $navigationGroup = 'Site management'; protected static string | \UnitEnum | null $navigationGroup = 'Site management';
protected static ?int $navigationSort = 6; protected static ?int $navigationSort = 6;
public static function form(Form $form): Form public static function form(Schema $schema): Schema
{ {
return $form return $schema
->schema([ ->components([
// //
]); ]);
} }
@@ -31,13 +33,13 @@ class SiteSystemUserResource extends Resource
{ {
return $table return $table
->columns([ ->columns([
Tables\Columns\TextColumn::make('user_name') TextColumn::make('user_name')
->label(__('Username')) ->label(__('Username'))
->searchable(), ->searchable(),
Tables\Columns\TextColumn::make('site.domain') TextColumn::make('site.domain')
->label(__('Site')) ->label(__('Site'))
->searchable(), ->searchable(),
Tables\Columns\TextColumn::make('created_at') TextColumn::make('created_at')
->label(__('Date')) ->label(__('Date'))
->dateTime() ->dateTime()
->sortable(), ->sortable(),
@@ -45,10 +47,10 @@ class SiteSystemUserResource extends Resource
->filters([ ->filters([
// //
]) ])
->actions([ ->recordActions([
// //
]) ])
->bulkActions([ ->toolbarActions([
// //
]) ])
->defaultSort('created_at', 'desc'); ->defaultSort('created_at', 'desc');
@@ -64,7 +66,7 @@ class SiteSystemUserResource extends Resource
public static function getPages(): array public static function getPages(): array
{ {
return [ return [
'index' => Pages\ListSiteSystemUsers::route('/'), 'index' => ListSiteSystemUsers::route('/'),
]; ];
} }
} }

View File

@@ -1,8 +1,8 @@
<?php <?php
namespace App\Filament\Resources\SiteResource\Pages; namespace App\Filament\Resources\Sites\Pages;
use App\Filament\Resources\SiteResource; use App\Filament\Resources\Sites\SiteResource;
use Filament\Resources\Pages\CreateRecord; use Filament\Resources\Pages\CreateRecord;
class CreateSite extends CreateRecord class CreateSite extends CreateRecord

View File

@@ -0,0 +1,20 @@
<?php
namespace App\Filament\Resources\Sites\Pages;
use Filament\Actions\DeleteAction;
use Filament\Actions;
use App\Filament\Resources\Sites\SiteResource;
use Filament\Resources\Pages\EditRecord;
class EditSite extends EditRecord
{
protected static string $resource = SiteResource::class;
protected function getHeaderActions(): array
{
return [
DeleteAction::make(),
];
}
}

View File

@@ -0,0 +1,28 @@
<?php
namespace App\Filament\Resources\Sites\Pages;
use Filament\Actions\Action;
use Filament\Actions;
use App\Traits\HasPloi;
use App\Filament\Resources\Sites\SiteResource;
use Filament\Resources\Pages\ListRecords;
class ListSites extends ListRecords
{
use HasPloi;
protected static string $resource = SiteResource::class;
protected function getHeaderActions(): array
{
return [
Action::make('synchronize_sites')
->label(__('Synchronize sites'))
->icon('heroicon-o-arrow-path')
->color('gray')
->url(SiteResource::getUrl('synchronize')),
...parent::getHeaderActions()
];
}
}

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