diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..dd9a2b5 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,15 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +indent_size = 4 +indent_style = space +insert_final_newline = true +trim_trailing_whitespace = true + +[*.md] +trim_trailing_whitespace = false + +[*.{yml,yaml}] +indent_size = 2 diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..9c9472b --- /dev/null +++ b/.gitattributes @@ -0,0 +1,28 @@ +# Path-based git attributes +# https://www.kernel.org/pub/software/scm/git/docs/gitattributes.html + +# Ignore all test and documentation with "export-ignore". +/.github export-ignore +/.gitattributes export-ignore +/.gitignore export-ignore +/.idea export-ignore +/.prettierrc export-ignore +/.package-lock.json export-ignore +/.editorconfig export-ignore +/.php_cs.dist.php export-ignore +/.vscode export-ignore +/art export-ignore +/docs export-ignore +/images export-ignore +/tests export-ignore +/package.json export-ignore +/phpstan-baseline.neon export-ignore +/phpstan.neon.dist export-ignore +/postcss.config.js export-ignore +/phpunit.xml.dist export-ignore +/pint.json export-ignore +/psalm.xml export-ignore +/psalm.xml.dist export-ignore +/tailwind.config.js export-ignore +/testbench.yaml export-ignore +/UPGRADING.md export-ignore diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md new file mode 100644 index 0000000..b0ee5d8 --- /dev/null +++ b/.github/CONTRIBUTING.md @@ -0,0 +1,55 @@ +# Contributing + +Contributions are **welcome** and will be fully **credited**. + +Please read and understand the contribution guide before creating an issue or pull request. + +## Etiquette + +This project is open source, and as such, the maintainers give their free time to build and maintain the source code +held within. They make the code freely available in the hope that it will be of use to other developers. It would be +extremely unfair for them to suffer abuse or anger for their hard work. + +Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the +world that developers are civilized and selfless people. + +It's the duty of the maintainer to ensure that all submissions to the project are of sufficient +quality to benefit the project. Many developers have different skills, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used. + +## Viability + +When requesting or submitting new features, first consider whether it might be useful to others. Open +source projects are used by many developers, who may have entirely different needs to your own. Think about +whether or not your feature is likely to be used by other users of the project. + +## Procedure + +Before filing an issue: + +- Attempt to replicate the problem, to ensure that it wasn't a coincidental incident. +- Check to make sure your feature suggestion isn't already present within the project. +- Check the pull requests tab to ensure that the bug doesn't have a fix in progress. +- Check the pull requests tab to ensure that the feature isn't already in progress. + +Before submitting a pull request: + +- Check the codebase to ensure that your feature doesn't already exist. +- Check the pull requests to ensure that another person hasn't already submitted the feature or fix. + +## Requirements + +If the project maintainer has any additional requirements, you will find them listed here. + +- **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](https://pear.php.net/package/PHP_CodeSniffer). + +- **Add tests!** - Your patch won't be accepted if it doesn't have tests. + +- **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. + +- **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option. + +- **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. + +- **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. + +**Happy coding**! diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..75d7283 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1 @@ +github: postare diff --git a/.github/ISSUE_TEMPLATE/bug.yml b/.github/ISSUE_TEMPLATE/bug.yml new file mode 100644 index 0000000..8fa85ce --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug.yml @@ -0,0 +1,66 @@ +name: Bug Report +description: Report an Issue or Bug with the Package +title: "[Bug]: " +labels: ["bug"] +body: + - type: markdown + attributes: + value: | + We're sorry to hear you have a problem. Can you help us solve it by providing the following details. + - type: textarea + id: what-happened + attributes: + label: What happened? + description: What did you expect to happen? + placeholder: I cannot currently do X thing because when I do, it breaks X thing. + validations: + required: true + - type: textarea + id: how-to-reproduce + attributes: + label: How to reproduce the bug + description: How did this occur, please add any config values used and provide a set of reliable steps if possible. + placeholder: When I do X I see Y. + validations: + required: true + - type: input + id: package-version + attributes: + label: Package Version + description: What version of our Package are you running? Please be as specific as possible + placeholder: 2.0.0 + validations: + required: true + - type: input + id: php-version + attributes: + label: PHP Version + description: What version of PHP are you running? Please be as specific as possible + placeholder: 8.2.0 + validations: + required: true + - type: input + id: laravel-version + attributes: + label: Laravel Version + description: What version of Laravel are you running? Please be as specific as possible + placeholder: 9.0.0 + validations: + required: true + - type: dropdown + id: operating-systems + attributes: + label: Which operating systems does with happen with? + description: You may select more than one. + multiple: true + options: + - macOS + - Windows + - Linux + - type: textarea + id: notes + attributes: + label: Notes + description: Use this field to provide any other notes that you feel might be relevant to the issue. + validations: + required: false diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..47c8729 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,11 @@ +blank_issues_enabled: false +contact_links: + - name: Ask a question + url: https://github.com/postare/filament-contact-logs/discussions/new?category=q-a + about: Ask the community for help + - name: Request a feature + url: https://github.com/postare/filament-contact-logs/discussions/new?category=ideas + about: Share ideas for new features + - name: Report a security issue + url: https://github.com/postare/filament-contact-logs/security/policy + about: Learn how to notify us for sensitive bugs diff --git a/.github/SECURITY.md b/.github/SECURITY.md new file mode 100644 index 0000000..5e978cd --- /dev/null +++ b/.github/SECURITY.md @@ -0,0 +1,3 @@ +# Security Policy + +If you discover any security related issues, please email inerba@gmail.com instead of using the issue tracker. diff --git a/.github/workflows/fix-php-code-styling.yml b/.github/workflows/fix-php-code-styling.yml new file mode 100644 index 0000000..a17569a --- /dev/null +++ b/.github/workflows/fix-php-code-styling.yml @@ -0,0 +1,27 @@ +name: "Fix PHP Code Styling" + +on: + push: + paths: + - '**.php' + +permissions: + contents: write + +jobs: + php-code-styling: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v4 + with: + ref: ${{ github.head_ref }} + + - name: Fix PHP code style issues + uses: aglipanci/laravel-pint-action@2.3.0 + + - name: Commit changes + uses: stefanzweifel/git-auto-commit-action@v5 + with: + commit_message: Fix styling diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml new file mode 100644 index 0000000..7fefe35 --- /dev/null +++ b/.github/workflows/run-tests.yml @@ -0,0 +1,51 @@ +name: run-tests + +on: + push: + branches: [main] + pull_request: + branches: [main] + +jobs: + test: + runs-on: ${{ matrix.os }} + strategy: + fail-fast: true + matrix: + os: [ubuntu-latest, windows-latest] + php: [8.2, 8.1] + laravel: [10.*] + stability: [prefer-lowest, prefer-stable] + include: + - laravel: 10.* + testbench: 8.* + carbon: ^2.63 + + name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.stability }} - ${{ matrix.os }} + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, imagick, fileinfo + coverage: none + + - name: Setup problem matchers + run: | + echo "::add-matcher::${{ runner.tool_cache }}/php.json" + echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json" + + - name: Install dependencies + run: | + composer require "laravel/framework:${{ matrix.laravel }}" "orchestra/testbench:${{ matrix.testbench }}" "nesbot/carbon:${{ matrix.carbon }}" --no-interaction --no-update + composer update --${{ matrix.stability }} --prefer-dist --no-interaction + + - name: List Installed Dependencies + run: composer show -D + + - name: Execute tests + run: vendor/bin/pest --ci diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8271e65 --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +.DS_Store +.idea +.phpunit.result.cache +.vscode +build +composer.lock +coverage +docs +node_modules +phpunit.xml +phpstan.neon +testbench.yaml +vendor diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 0000000..98406c6 --- /dev/null +++ b/.prettierrc @@ -0,0 +1,5 @@ +{ + "semi": false, + "singleQuote": true, + "trailingComma": "all" +} diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..e1192e0 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,7 @@ +# Changelog + +All notable changes to `filament-contact-logs` will be documented in this file. + +## 1.0.0 - 202X-XX-XX + +- initial release diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..e34fec8 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) postare + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..1021b89 --- /dev/null +++ b/README.md @@ -0,0 +1,154 @@ +# Filament Contact Logs + +[![Latest Version on Packagist](https://img.shields.io/packagist/v/postare/filament-contact-logs.svg?style=flat-square)](https://packagist.org/packages/postare/filament-contact-logs) +[![GitHub Tests Action Status](https://img.shields.io/github/actions/workflow/status/postare/filament-contact-logs/run-tests.yml?branch=main&label=tests&style=flat-square)](https://github.com/postare/filament-contact-logs/actions?query=workflow%3Arun-tests+branch%3Amain) +[![GitHub Code Style Action Status](https://img.shields.io/github/actions/workflow/status/postare/filament-contact-logs/fix-php-code-style-issues.yml?branch=main&label=code%20style&style=flat-square)](https://github.com/postare/filament-contact-logs/actions?query=workflow%3A"Fix+PHP+code+style+issues"+branch%3Amain) +[![Total Downloads](https://img.shields.io/packagist/dt/postare/filament-contact-logs.svg?style=flat-square)](https://packagist.org/packages/postare/filament-contact-logs) + +Filament Contact Logs is a Filament 3.x plugin that performs a clear and critical function: it records in a log every +time a +contact is sent. Regardless of the contact's final destination, the plugin ensures that each submission is tracked in +detail. This allows operators to have a complete history of all communications received, providing a clear and organized +picture of interactions and feedback. Thus, its main function is to ensure total traceability of contacts, facilitating +management and follow-up by operators. + +## Installation + +Install the package via composer: + +```bash +composer require postare/filament-contact-logs +``` + +Publish and run the migrations: + +```bash +php artisan vendor:publish --tag="filament-contact-logs-migrations" +php artisan migrate +``` + +Publish the config file: + +```bash +php artisan vendor:publish --tag="filament-contact-logs-config" +``` + +Published config file contents: + +```php +return [ + /* + * When the clean-command is executed, all recording activities older than + * the number of days specified here will be deleted. + */ + 'delete_records_older_than_days' => 365, + + /* + * Model to use to log activity. + */ + 'contact_log_model' => \Postare\FilamentContactLogs\Models\ContactLog::class, + + /* + * List of Models associated with contact messages, it is not mandatory + * to specify them, it is for obtaining a more user-friendly table. + */ + 'mappings' => [ + 'App\Models\Miogest\Property' => [ + 'type' => 'Immobile', + 'pluralType' => 'Immobili', + 'label' => 'ID: {id}', + 'urlPrefix' => 'property', + 'titleField' => 'titolo', + 'slugField' => 'slug', + ], + ], +]; +``` + +## Usage + +### Integrating with Filament Panel + +```php +// app\Providers\Filament\AdminPanelProvider.php +$panel + ... + ->plugins([ + ... + \Postare\FilamentContactLogs\FilamentContactLogsPlugin::make(), + ]); +``` + +### Associating Models with Contact Logs + +```php +// Use HasContactLogs trait in your model +use Postare\FilamentContactLogs\Traits\HasContactLogs; +``` + +### Examples + +Add a contact log to a model: + +```php +Property::find(1)->addContactLog([ + 'content' => 'A beautiful message', + 'subject' => 'A subject', + 'sender_id' => auth()?->id(), // optional + 'sender_email' => 'user@email.com', + 'sender_name' => 'John Doe', + 'sender_phone' => '1234567890', // optional +]); +``` + +Add a contact log without a model: + +```php +contactLog([ + 'content' => 'A beautiful message', + 'subject' => 'A subject', + 'sender_id' => auth()?->id(), // optional + 'sender_email' => 'user@email.com', + 'sender_name' => 'John Doe', + 'sender_phone' => '1234567890', // optional +]); +``` + +### Auto-Deleting Logs + +Automatically delete logs based on config settings: + +```php +// Add the following to your app\Console\Kernel.php +protected function schedule(Schedule $schedule): void +{ + $schedule->command('contact-logs:clean')->daily(); +} +``` + +## Testing + +```bash +composer test +``` + +## Changelog + +Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently. + +## Contributing + +Please see [CONTRIBUTING](.github/CONTRIBUTING.md) for details. + +## Security Vulnerabilities + +Please review [our security policy](../../security/policy) on how to report security vulnerabilities. + +## Credits + +- [Francesco Apruzzese](https://github.com/inerba) +- [All Contributors](../../contributors) + +## License + +The MIT License (MIT). Please see [License File](LICENSE.md) for more information. diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..e9a7123 --- /dev/null +++ b/composer.json @@ -0,0 +1,76 @@ +{ + "name": "postare/filament-contact-logs", + "description": "Filament Contact Logs", + "keywords": [ + "postare", + "laravel", + "filament-contact-logs" + ], + "homepage": "https://github.com/postare/filament-contact-logs", + "support": { + "issues": "https://github.com/postare/filament-contact-logs/issues", + "source": "https://github.com/postare/filament-contact-logs" + }, + "license": "MIT", + "authors": [ + { + "name": "Francesco", + "email": "inerba@gmail.com", + "role": "Developer" + } + ], + "require": { + "php": "^8.1", + "filament/filament": "^3.0", + "spatie/laravel-package-tools": "^1.15.0", + "illuminate/contracts": "^10.0" + }, + "require-dev": { + "laravel/pint": "^1.0", + "nunomaduro/collision": "^7.9", + "orchestra/testbench": "^8.0", + "pestphp/pest": "^2.0", + "pestphp/pest-plugin-arch": "^2.0", + "pestphp/pest-plugin-laravel": "^2.0", + "spatie/laravel-ray": "^1.26" + }, + "autoload": { + "psr-4": { + "Postare\\FilamentContactLogs\\": "src/", + "Postare\\FilamentContactLogs\\Database\\Factories\\": "database/factories/" + }, + "files": [ + "src/helpers.php" + ] + }, + "autoload-dev": { + "psr-4": { + "Postare\\FilamentContactLogs\\Tests\\": "tests/" + } + }, + "scripts": { + "post-autoload-dump": "@php ./vendor/bin/testbench package:discover --ansi", + "test": "vendor/bin/pest", + "test-coverage": "vendor/bin/pest --coverage", + "format": "vendor/bin/pint" + }, + "config": { + "sort-packages": true, + "allow-plugins": { + "pestphp/pest-plugin": true, + "phpstan/extension-installer": true + } + }, + "extra": { + "laravel": { + "providers": [ + "Postare\\FilamentContactLogs\\FilamentContactLogsServiceProvider" + ], + "aliases": { + "FilamentContactLogs": "Postare\\FilamentContactLogs\\Facades\\FilamentContactLogs" + } + } + }, + "minimum-stability": "dev", + "prefer-stable": true +} diff --git a/config/contact-logs.php b/config/contact-logs.php new file mode 100644 index 0000000..f1bd5ad --- /dev/null +++ b/config/contact-logs.php @@ -0,0 +1,29 @@ + 365, + + /* + * Model to use to log activity. + */ + 'contact_log_model' => \Postare\FilamentContactLogs\Models\ContactLog::class, + + /* + * List of Models associated with contact messages, it is not mandatory + * to specify them, it is for obtaining a more user-friendly table. + */ + 'mappings' => [ + 'App\Models\Miogest\Property' => [ + 'type' => 'Immobile', + 'pluralType' => 'Immobili', + 'label' => 'ID: {id}', + 'urlPrefix' => 'property', + 'titleField' => 'titolo', + 'slugField' => 'slug', + ], + ], +]; diff --git a/database/factories/ModelFactory.php b/database/factories/ModelFactory.php new file mode 100644 index 0000000..3bd6866 --- /dev/null +++ b/database/factories/ModelFactory.php @@ -0,0 +1,19 @@ +id(); + + $table->text('content'); + $table->string('subject')->nullable(); + $table->foreignId('sender_id')->nullable()->constrained('users')->onDelete('cascade'); + $table->string('sender_email')->nullable(); + $table->string('sender_name')->nullable(); + $table->string('sender_phone')->nullable(); + $table->nullableMorphs('contactable'); + + $table->timestamps(); + }); + } + + public function down() + { + Schema::dropIfExists('contact_logs'); + } +}; diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 0000000..704fb48 --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,38 @@ + + + + + tests + + + + + + + + + + + + + + + ./src + + + diff --git a/pint.json b/pint.json new file mode 100644 index 0000000..c6ddb49 --- /dev/null +++ b/pint.json @@ -0,0 +1,14 @@ +{ + "preset": "laravel", + "rules": { + "blank_line_before_statement": true, + "concat_space": { + "spacing": "one" + }, + "method_argument_space": true, + "single_trait_insert_per_statement": true, + "types_spaces": { + "space": "single" + } + } +} diff --git a/resources/lang/en/contact-logs.php b/resources/lang/en/contact-logs.php new file mode 100644 index 0000000..64fd1c1 --- /dev/null +++ b/resources/lang/en/contact-logs.php @@ -0,0 +1,23 @@ + [ + 'singular' => 'Contact log', + 'plural' => 'Contact logs', + ], + 'list' => [ + 'tabs' => [ + 'all' => 'All', + 'other' => 'Other', + ], + 'contactable_type' => 'Source', + 'contactable_type_default' => 'Other', + 'contactable_id' => 'Source ID', + 'subject' => 'Subject', + 'content' => 'Content', + 'sender' => 'Sender', + 'sender_phone' => 'Sender phone', + 'created_at' => 'Received at', + ], +]; diff --git a/resources/lang/it/contact-logs.php b/resources/lang/it/contact-logs.php new file mode 100644 index 0000000..b1dff24 --- /dev/null +++ b/resources/lang/it/contact-logs.php @@ -0,0 +1,23 @@ + [ + 'singular' => 'Registro contatti', + 'plural' => 'Registro contatti', + ], + 'list' => [ + 'tabs' => [ + 'all' => 'Tutti', + 'other' => 'Altro', + ], + 'contactable_type' => 'Fonte', + 'contactable_type_default' => 'Altro', + 'contactable_id' => 'ID Fonte', + 'subject' => 'Oggetto', + 'content' => 'Contenuto', + 'sender' => 'Mittente', + 'sender_phone' => 'Telefono mittente', + 'created_at' => 'Ricevuto il', + ], +]; diff --git a/src/Commands/FilamentContactLogsCommand.php b/src/Commands/FilamentContactLogsCommand.php new file mode 100644 index 0000000..d97c724 --- /dev/null +++ b/src/Commands/FilamentContactLogsCommand.php @@ -0,0 +1,36 @@ +comment('Cleaning activity log...'); + + $maxAgeInDays = $this->option('days') ?? config('contact-logs.delete_records_older_than_days'); + + $cutOffDate = Carbon::now()->subDays($maxAgeInDays)->format('Y-m-d H:i:s'); + + $contactLogModel = config('contact-logs.contact_log_model') ?? ContactLog::class; + + $amountDeleted = $contactLogModel::query() + ->where('created_at', '<', $cutOffDate) + ->delete(); + + $this->info("Deleted {$amountDeleted} record(s) from the activity log."); + + $this->comment('All done!'); + + return 0; + } +} diff --git a/src/Facades/FilamentContactLogs.php b/src/Facades/FilamentContactLogs.php new file mode 100644 index 0000000..f0b86c9 --- /dev/null +++ b/src/Facades/FilamentContactLogs.php @@ -0,0 +1,16 @@ +resources([ + Resources\ContactLogResource::class, + ]); + } + + public function boot(Panel $panel): void + { + // + } + + public static function make(): static + { + return app(static::class); + } + + public static function get(): static + { + /** @var static $plugin */ + $plugin = filament(app(static::class)->getId()); + + return $plugin; + } +} diff --git a/src/FilamentContactLogsServiceProvider.php b/src/FilamentContactLogsServiceProvider.php new file mode 100644 index 0000000..1134a2a --- /dev/null +++ b/src/FilamentContactLogsServiceProvider.php @@ -0,0 +1,145 @@ +name(static::$name) + ->hasCommands($this->getCommands()) + ->hasInstallCommand(function (InstallCommand $command) { + $command + ->publishConfigFile() + ->publishMigrations() + ->askToRunMigrations() + ->askToStarRepoOnGitHub('postare/filament-contact-logs'); + }); + + $package->hasConfigFile('contact-logs'); + + if (file_exists($package->basePath('/../database/migrations'))) { + $package->hasMigrations($this->getMigrations()); + } + + if (file_exists($package->basePath('/../resources/lang'))) { + $package->hasTranslations(); + } + } + + public function packageRegistered(): void + { + } + + public function packageBooted(): void + { + // // Asset Registration + // FilamentAsset::register( + // $this->getAssets(), + // $this->getAssetPackageName() + // ); + + FilamentAsset::registerScriptData( + $this->getScriptData(), + $this->getAssetPackageName() + ); + + // Icon Registration + FilamentIcon::register($this->getIcons()); + + // Handle Stubs + if (app()->runningInConsole()) { + foreach (app(Filesystem::class)->files(__DIR__ . '/../stubs/') as $file) { + $this->publishes([ + $file->getRealPath() => base_path("stubs/filament-contact-logs/{$file->getFilename()}"), + ], 'filament-contact-logs-stubs'); + } + } + + // Testing + Testable::mixin(new TestsFilamentContactLogs()); + } + + protected function getAssetPackageName(): ?string + { + return 'postare/filament-contact-logs'; + } + + /** + * @return array + */ + protected function getAssets(): array + { + return [ + // AlpineComponent::make('filament-contact-logs', __DIR__ . '/../resources/dist/components/filament-contact-logs.js'), + Css::make('filament-contact-logs-styles', __DIR__ . '/../resources/dist/filament-contact-logs.css'), + Js::make('filament-contact-logs-scripts', __DIR__ . '/../resources/dist/filament-contact-logs.js'), + ]; + } + + /** + * @return array + */ + protected function getCommands(): array + { + return [ + FilamentContactLogsCommand::class, + ]; + } + + /** + * @return array + */ + protected function getIcons(): array + { + return []; + } + + /** + * @return array + */ + protected function getRoutes(): array + { + return []; + } + + /** + * @return array + */ + protected function getScriptData(): array + { + return []; + } + + /** + * @return array + */ + protected function getMigrations(): array + { + return [ + 'create_contact_logs_table', + ]; + } +} diff --git a/src/Models/ContactLog.php b/src/Models/ContactLog.php new file mode 100644 index 0000000..9d4d01a --- /dev/null +++ b/src/Models/ContactLog.php @@ -0,0 +1,61 @@ +morphTo(); + } + + /** + * Utente che ha inviato il messaggio. + */ + public function sender(): BelongsTo + { + return $this->belongsTo(User::class, 'sender_id'); + } + + // Metodo per creare un messaggio di contatto generale + public static function add(array $attributes) + { + $validator = Validator::make($attributes, [ + 'content' => 'required', + 'subject' => 'required', + 'sender_id' => 'nullable|exists:users,id', + 'sender_email' => 'required_without:sender_id|email', + 'sender_name' => 'required', + 'sender_phone' => 'nullable', + ]); + + if ($validator->fails()) { + throw new ValidationException($validator); + } + + return self::create($validator->validated()); + } +} diff --git a/src/Resources/ContactLogResource.php b/src/Resources/ContactLogResource.php new file mode 100644 index 0000000..50fe1c1 --- /dev/null +++ b/src/Resources/ContactLogResource.php @@ -0,0 +1,131 @@ +columns([ + TextColumn::make('contactable_type') + ->label('Sorgente') + ->formatStateUsing(fn ($state) => config("contact-logs.mappings.$state.type", $state)) + ->toggleable(true, false) + ->placeholder(__('filament-contact-logs::contact-logs.list.contactable_type_default')) + ->sortable(), + + TextColumn::make('contactable_id') + ->label(__('filament-contact-logs::contact-logs.list.contactable_id')) + ->formatStateUsing(function ($state, $record) { + // Recupera il formato della label dal file di configurazione + $labelFormat = Arr::get(config('contact-logs.mappings'), "{$record->contactable_type}.label"); + + // Se non esiste un formato di label specifico, usa il valore di default + if (! $labelFormat) { + return $state; + } + + // Sostituisci il placeholder se esiste, altrimenti restituisci il formato di label + return str_contains($labelFormat, '{id}') ? str_replace('{id}', $state, $labelFormat) : $labelFormat; + }) + ->description(function ($state, $record) { + // Usa config con un valore di default + $titleField = config("contact-logs.mappings.{$record->contactable_type}.titleField"); + + return $titleField ? str($record->contactable->{$titleField})->limit(50) : false; + }) + ->url(function ($record) { + // Ottieni la configurazione con un valore di default + $urlPrefix = config("contact-logs.mappings.{$record->contactable_type}.urlPrefix"); + $slugField = config("contact-logs.mappings.{$record->contactable_type}.slugField"); + + if ($urlPrefix && $slugField && $record->contactable) { + return route($urlPrefix, $record->contactable->{$slugField}); + } + + return false; + }, true) + ->wrap() + ->toggleable(true, false), + + TextColumn::make('subject') + ->label(__('filament-contact-logs::contact-logs.list.subject')) + ->toggleable(true, true) + ->sortable(), + + TextColumn::make('content') + ->label(__('filament-contact-logs::contact-logs.list.content')) + ->toggleable(true, false) + ->words(20) + ->wrap() + ->searchable(), + + TextColumn::make('sender_name') + ->label(__('filament-contact-logs::contact-logs.list.sender')) + ->description(fn ($state, $record) => $record->sender_email) + ->searchable(query: function (Builder $query, string $search): Builder { + return $query + ->where('sender_name', 'like', "%{$search}%") + ->orWhere('sender_email', 'like', "%{$search}%"); + }) + ->sortable(), + + TextColumn::make('sender_phone') + ->label(__('filament-contact-logs::contact-logs.list.sender_phone')) + ->toggleable(true, true) + ->searchable(), + + TextColumn::make('created_at') + ->label(__('filament-contact-logs::contact-logs.list.created_at')) + // description in relative format + ->description(fn ($state) => $state->diffForHumans()) + ->date('d/m/Y H:i:s') + ->sortable(), + + ])->actions([ + Tables\Actions\DeleteAction::make(), + ])->bulkActions([ + Tables\Actions\BulkActionGroup::make([ + Tables\Actions\DeleteBulkAction::make(), + ]), + ]) + ->defaultSort('created_at', 'desc'); + } + + public static function getPages(): array + { + return ['index' => ListContactLogs::route('/')]; + } + + // public static function getGloballySearchableAttributes(): array + // { + // return ['sender_name', 'sender_email']; + // } +} diff --git a/src/Resources/ContactLogResource/Pages/ListContactLogs.php b/src/Resources/ContactLogResource/Pages/ListContactLogs.php new file mode 100644 index 0000000..2ac8f19 --- /dev/null +++ b/src/Resources/ContactLogResource/Pages/ListContactLogs.php @@ -0,0 +1,54 @@ +selectRaw('COUNT(*) as total') + ->groupBy('contactable_type') + ->get() + ->keyBy('contactable_type') + ->map(fn ($item) => $item->total); + + $tabs = [ + 'all' => Tab::make(__('filament-contact-logs::contact-logs.list.tabs.all'))->badge($contactLogCount->sum()), + ]; + + foreach ($mapping as $model => $config) { + $typeCount = $contactLogCount[$model] ?? 0; + $tabs[Str::slug($config['pluralType'])] = Tab::make($config['pluralType']) + ->badge($typeCount) + ->modifyQueryUsing(fn ($query) => $query->where('contactable_type', $model)); + } + + $otherCount = $contactLogCount[null] ?? 0; + if ($otherCount > 0) { + $tabs['other'] = Tab::make(__('filament-contact-logs::contact-logs.list.tabs.other'))->badge($otherCount) + ->modifyQueryUsing(fn ($query) => $query->whereNull('contactable_type')); + } + + return $tabs; + } +} diff --git a/src/Testing/TestsFilamentContactLogs.php b/src/Testing/TestsFilamentContactLogs.php new file mode 100644 index 0000000..a007543 --- /dev/null +++ b/src/Testing/TestsFilamentContactLogs.php @@ -0,0 +1,13 @@ +morphMany(ContactLog::class, 'contactable'); + } + + /** + * Add a new message to the model. + * + * @param array $attributes The message attributes to be added. + * @return ContactLog The created message. + * + * @throws ValidationException + */ + public function addContactLog(array $attributes): ContactLog + { + // Validation rules + $validator = Validator::make($attributes, [ + 'content' => 'required', + 'subject' => 'required', + 'sender_id' => 'nullable|exists:users,id', + 'sender_email' => 'required_without:sender_id|email', + 'sender_name' => 'required', + 'sender_phone' => 'nullable', + ]); + + // Throw an exception if validation fails + if ($validator->fails()) { + throw new ValidationException($validator); + } + + // Create and return the message + return $this->contactLogs()->create($validator->validated()); + } +} diff --git a/src/helpers.php b/src/helpers.php new file mode 100644 index 0000000..2f2325d --- /dev/null +++ b/src/helpers.php @@ -0,0 +1,25 @@ + 'required', + 'subject' => 'required', + 'sender_id' => 'nullable|exists:users,id', + 'sender_email' => 'required_without:sender_id|email', + 'sender_name' => 'required', + 'sender_phone' => 'nullable', + ]); + + if ($validator->fails()) { + throw new ValidationException($validator); + } + + return ContactLog::create($validator->validated()); + } +} diff --git a/stubs/.gitkeep b/stubs/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/tests/ArchTest.php b/tests/ArchTest.php new file mode 100644 index 0000000..ccc19b2 --- /dev/null +++ b/tests/ArchTest.php @@ -0,0 +1,5 @@ +expect(['dd', 'dump', 'ray']) + ->each->not->toBeUsed(); diff --git a/tests/ExampleTest.php b/tests/ExampleTest.php new file mode 100644 index 0000000..5d36321 --- /dev/null +++ b/tests/ExampleTest.php @@ -0,0 +1,5 @@ +toBeTrue(); +}); diff --git a/tests/Pest.php b/tests/Pest.php new file mode 100644 index 0000000..4ea9db8 --- /dev/null +++ b/tests/Pest.php @@ -0,0 +1,5 @@ +in(__DIR__); diff --git a/tests/TestCase.php b/tests/TestCase.php new file mode 100644 index 0000000..5ad3b5e --- /dev/null +++ b/tests/TestCase.php @@ -0,0 +1,64 @@ + 'Postare\\FilamentContactLogs\\Database\\Factories\\' . class_basename($modelName) . 'Factory' + ); + } + + protected function getPackageProviders($app) + { + return [ + ActionsServiceProvider::class, + BladeCaptureDirectiveServiceProvider::class, + BladeHeroiconsServiceProvider::class, + BladeIconsServiceProvider::class, + FilamentServiceProvider::class, + FormsServiceProvider::class, + InfolistsServiceProvider::class, + LivewireServiceProvider::class, + NotificationsServiceProvider::class, + SpatieLaravelSettingsPluginServiceProvider::class, + SpatieLaravelTranslatablePluginServiceProvider::class, + SupportServiceProvider::class, + TablesServiceProvider::class, + WidgetsServiceProvider::class, + FilamentContactLogsServiceProvider::class, + ]; + } + + public function getEnvironmentSetUp($app) + { + config()->set('database.default', 'testing'); + + /* + $migration = include __DIR__.'/../database/migrations/create_filament-contact-logs_table.php.stub'; + $migration->up(); + */ + } +}