├── .github └── workflows │ └── ci.yml ├── .gitignore ├── .styleci.yml ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE.md ├── README.md ├── composer.json ├── dist ├── css │ └── field.css ├── js │ ├── field.js │ ├── field.js.LICENSE.txt │ └── field.mjs └── mix-manifest.json ├── migrations ├── 2019_05_22_142633_create_nova_chartjs_metric_values_table.php └── 2020_10_28_105921_add_chart_name_to_nova_chartjs_metric_values.php ├── mix.js ├── package.json ├── phpunit.xml.dist ├── resources ├── css │ └── field.css ├── imgs │ └── banner.png └── js │ ├── components │ ├── ChartjsBarChart.vue │ ├── ChartjsLineChart.vue │ ├── DetailField.vue │ ├── FormField.vue │ ├── IndexField.vue │ ├── IndexViewChart.vue │ └── ParameterEditor.vue │ ├── field.js │ └── mixins │ ├── charts.js │ ├── colors.js │ └── datasetHandler.js ├── routes └── api.php ├── screenshots ├── AsRelationship.jpg ├── ChartablePanel.jpg ├── ComparisonDropdown.jpg ├── CoverImage.jpg ├── EditView.jpg ├── IndexView.jpg ├── InlineMode.jpg ├── ModelComparison.jpg ├── PanelWithLabel.jpg └── WithAdditionalDatasets.jpg ├── src ├── Contracts │ └── Chartable.php ├── Http │ └── Controllers │ │ ├── GetAdditionalDatasetsController.php │ │ └── RetrieveModelComparisonDataController.php ├── InlinePanel.php ├── Models │ └── NovaChartjsMetricValue.php ├── Nova │ └── MetricValue.php ├── NovaChartjs.php ├── NovaChartjsServiceProvider.php ├── RelationshipPanel.php └── Traits │ ├── HasChart.php │ └── RedirectsOnCreate.php ├── tests ├── Chartable.php ├── TestCase.php ├── Unit │ └── ChartableTest.php └── factories │ └── NovaChartjsMetricValueFactory.php └── webpack.mix.js /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | on: push 2 | name: CI 3 | 4 | jobs: 5 | phpunit: 6 | runs-on: ubuntu-latest 7 | container: 8 | image: kirschbaumdevelopment/laravel-test-runner:8.0 9 | 10 | services: 11 | mysql: 12 | image: mysql:5.7 13 | env: 14 | MYSQL_ROOT_PASSWORD: password 15 | MYSQL_DATABASE: test 16 | ports: 17 | - 33306:3306 18 | options: --health-cmd="mysqladmin ping" --health-interval=10s --health-timeout=5s --health-retries=3 19 | 20 | steps: 21 | - uses: actions/checkout@v1 22 | with: 23 | fetch-depth: 1 24 | 25 | - name: Configure composer for Nova 26 | run: composer config 'http-basic.nova.laravel.com' '${{ secrets.NOVA_USERNAME }}' '${{ secrets.NOVA_LICENSE_KEY }}' 27 | 28 | - name: Install composer dependencies 29 | run: | 30 | composer install --prefer-dist --no-interaction --no-scripts 31 | 32 | - name: Run Testsuite 33 | run: vendor/bin/phpunit tests/ 34 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /.idea 2 | /vendor 3 | /node_modules 4 | package-lock.json 5 | composer.phar 6 | composer.lock 7 | phpunit.xml 8 | .phpunit.result.cache 9 | .DS_Store 10 | Thumbs.db 11 | auth.json 12 | 13 | -------------------------------------------------------------------------------- /.styleci.yml: -------------------------------------------------------------------------------- 1 | preset: laravel 2 | 3 | enabled: 4 | - combine_consecutive_unsets 5 | - explicit_string_variable 6 | - length_ordered_imports 7 | - method_chaining_indentation 8 | - no_empty_comment 9 | - ordered_class_elements 10 | - phpdoc_add_missing_param_annotation 11 | - phpdoc_no_empty_return 12 | - phpdoc_order 13 | - phpdoc_separation 14 | - property_separation 15 | - ternary_to_null_coalescing 16 | 17 | disabled: 18 | - concat_without_spaces 19 | - alpha_ordered_imports 20 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # ChangeLog 2 | This document is meant for tracking notable changes to `nova-chartjs` 3 | 4 | ## 0.1.0 5 | 1. Chart metric values can now directly be added while creating new Chartable model. 6 | 2. Deprecated `RedirectsOnCreate` Trait 7 | 8 | ## 0.2.0 9 | 1. Deprecated `chartable` method on `NovaChartjs` 10 | 2. Added `hideFromIndex` option to `InlinePanel` 11 | 12 | ## 0.3.0 13 | 1. Added Bar Charts 14 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Contributions are **welcome** and will be fully **credited**. 4 | 5 | Please read and understand the contribution guide before creating an issue or pull request. 6 | 7 | ## Etiquette 8 | 9 | This project is open source, and as such, the maintainers give their free time to build and maintain the source code 10 | held within. They make the code freely available in the hope that it will be of use to other developers. It would be 11 | extremely unfair for them to suffer abuse or anger for their hard work. 12 | 13 | Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the 14 | world that developers are civilized and selfless people. 15 | 16 | It's the duty of the maintainer to ensure that all submissions to the project are of sufficient 17 | quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used. 18 | 19 | ## Viability 20 | 21 | When requesting or submitting new features, first consider whether it might be useful to others. Open 22 | source projects are used by many developers, who may have entirely different needs to your own. Think about 23 | whether or not your feature is likely to be used by other users of the project. 24 | 25 | ## Procedure 26 | 27 | Before filing an issue: 28 | 29 | - Attempt to replicate the problem, to ensure that it wasn't a coincidental incident. 30 | - Check to make sure your feature suggestion isn't already present within the project. 31 | - Check the pull requests tab to ensure that the bug doesn't have a fix in progress. 32 | - Check the pull requests tab to ensure that the feature isn't already in progress. 33 | 34 | Before submitting a pull request: 35 | 36 | - Check the codebase to ensure that your feature doesn't already exist. 37 | - Check the pull requests to ensure that another person hasn't already submitted the feature or fix. 38 | 39 | ## Requirements 40 | 41 | If the project maintainer has any additional requirements, you will find them listed here. 42 | 43 | - **[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](http://pear.php.net/package/PHP_CodeSniffer). 44 | 45 | - **Add tests!** - Your patch won't be accepted if it doesn't have tests. 46 | 47 | - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. 48 | 49 | - **Consider our release cycle** - We try to follow [SemVer v2.0.0](http://semver.org/). Randomly breaking public APIs is not an option. 50 | 51 | - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. 52 | 53 | - **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](http://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. 54 | 55 | **Happy coding**! 56 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) Kirschbaum Development Group, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Banner](resources/imgs/banner.png "Banner") 2 | 3 | # Nova Chart.js 4 | 5 | [![Latest Version on Packagist](https://img.shields.io/packagist/v/kirschbaum-development/nova-chartjs.svg)](https://packagist.org/packages/kirschbaum-development/nova-chartjs) 6 | [![Total Downloads](https://img.shields.io/packagist/dt/kirschbaum-development/nova-chartjs.svg)](https://packagist.org/packages/kirschbaum-development/nova-chartjs) 7 | 8 | ## Introduction 9 | This package allows you to easily add chart.js graphs to your nova resources. This project is under active development, and currently only supports Line and Bar Charts. You are welcome to request or contribute additional charts by opening an issue. 10 | 11 | ![Cover Image](screenshots/CoverImage.jpg "Cover Image") 12 | 13 | ## Requirements 14 | 15 | This Nova field requires Nova 2.0 or higher. 16 | 17 | ## Installation 18 | 19 | You can install this package in a Laravel app that uses [Nova](https://nova.laravel.com) via composer: 20 | 21 | ```bash 22 | composer require kirschbaum-development/nova-chartjs 23 | ``` 24 | 25 | You'll also need to run migrations to set up a database table for `NovaChartjsMetricValue` 26 | 27 | ```bash 28 | php artisan migrate 29 | ``` 30 | 31 | ## Setup 32 | 33 | After setup, your model should include the `KirschbaumDevelopment\NovaChartjs\Traits\HasChart` trait and you must implement the `KirschbaumDevelopment\NovaChartjs\Contracts\Chartable` Contract. 34 | 35 | You must also define a static `getNovaChartjsSettings` function in the model which should return the required settings for the Chart. All other required methods and relationship defined in the contract are already defined for you in the included trait. You can also override these trait methods directly on your model. 36 | 37 | ```php 38 | use KirschbaumDevelopment\NovaChartjs\Traits\HasChart; 39 | use KirschbaumDevelopment\NovaChartjs\Contracts\Chartable; 40 | 41 | class Employee extends Model implements Chartable 42 | { 43 | use HasChart; 44 | 45 | /** 46 | * Should return settings for Nova Chart in prescribed format 47 | * 48 | * @return array 49 | */ 50 | public static function getNovaChartjsSettings(): array 51 | { 52 | return [ 53 | 'default' => [ 54 | 'type' => 'line', 55 | 'titleProp' => 'name', 56 | 'identProp' => 'id', 57 | 'height' => 400, 58 | 'indexColor' => '#999999', 59 | 'color' => '#FF0000', 60 | 'parameters' => ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], 61 | 'options' => ['responsive' => true, 'maintainAspectRatio' => false], 62 | ] 63 | ]; 64 | } 65 | 66 | // ... 67 | } 68 | ``` 69 | ## Adding Custom Datsets 70 | 71 | You can also add your own custom datasets to the chart by adding a `getAdditionalDatasets` method on your model 72 | 73 | ![Additional Dataset](screenshots/WithAdditionalDatasets.jpg "With Additional Dataset") 74 | 75 | ```php 76 | use KirschbaumDevelopment\NovaChartjs\Traits\HasChart; 77 | use KirschbaumDevelopment\NovaChartjs\Contracts\Chartable; 78 | 79 | class Employee extends Model implements Chartable 80 | { 81 | use HasChart; 82 | 83 | //... 84 | 85 | /** 86 | * Return a list of additional datasets added to chart 87 | * 88 | * @return array 89 | */ 90 | public function getAdditionalDatasets(): array 91 | { 92 | return [ 93 | 'default' => [ 94 | [ 95 | 'label' => 'Average Sales', 96 | 'borderColor' => '#f87900', 97 | 'data' => [80, 40, 62, 79, 80, 90, 79, 90, 90, 90, 92, 91], 98 | ], 99 | ] 100 | ]; 101 | } 102 | 103 | // ... 104 | } 105 | ``` 106 | You can read more about adding custom datasets in the [official chart.js documentation](https://www.chartjs.org/docs/latest/) 107 | 108 | ### Creating a range chart 109 | 110 | To create a range chart you can pass on two additional datasets representing an upper and lower range and set the fill and background color property for the first data point. 111 | 112 | ```php 113 | use KirschbaumDevelopment\NovaChartjs\Traits\HasChart; 114 | use KirschbaumDevelopment\NovaChartjs\Contracts\Chartable; 115 | 116 | class Employee extends Model implements Chartable 117 | { 118 | use HasChart; 119 | 120 | //... 121 | 122 | /** 123 | * Return a list of additional datasets added to chart 124 | * 125 | * @return array 126 | */ 127 | public function getAdditionalDatasets(): array 128 | { 129 | return [ 130 | 'default' => [ 131 | [ 132 | 'label' => 'Minimum Required', 133 | 'borderColor' => '#f87900', 134 | 'fill' => '+1', 135 | 'backgroundColor' => 'rgba(20,20,20,0.2)',//For bar charts, this will be the fill color of the bar 136 | 'data' => [8, 7, 12, 19, 12, 10, 19, 9, 10, 20, 12, 11], 137 | ], 138 | [ 139 | 'label' => 'Target', 140 | 'borderColor' => '#007979', 141 | 'fill' => false, 142 | 'data' => [80, 40, 62, 79, 80, 90, 79, 90, 90, 90, 92, 91], 143 | ], 144 | ] 145 | ]; 146 | } 147 | 148 | // ... 149 | } 150 | ``` 151 | 152 | ## Adding Chart 153 | 154 | You can add the chart to your Nova resource in three ways 155 | 156 | 1. Our recommended way of using Nova Chartjs Chart is to add the included Panel `KirschbaumDevelopment\NovaChartjs\InlinePanel` to your resource's Nova fields 157 | 158 | ![Chartable Panel](screenshots/ChartablePanel.jpg "Chartable Panel") 159 | 160 | ```php 161 | namespace App\Nova; 162 | 163 | use KirschbaumDevelopment\NovaChartjs\InlinePanel; 164 | 165 | class Employee extends Resource 166 | { 167 | 168 | //... 169 | public function fields(Request $request) 170 | { 171 | return [ 172 | //... 173 | 174 | InlinePanel::make($this, $request, 'Chart Name'), 175 | ]; 176 | } 177 | } 178 | ``` 179 | **_NOTE:_** You must pass the `Resource` (i.e. `$this`) and `$request` to the `InlinePanel` component. 180 | 181 | As an optional argument you can pass a chart name as the third argument, `showLabel` as fourth argument, `notEditable` as the fifth argument and `hideFromIndex` as the sixth argument. 182 | 183 | ![Panel with Label](screenshots/PanelWithLabel.jpg "Panel with Label") 184 | 185 | 2. If you instead want to use the Chart inline without a panel you can do so using this code: 186 | 187 | ```php 188 | namespace App\Nova; 189 | 190 | use KirschbaumDevelopment\NovaChartjs\NovaChartjs; 191 | 192 | class Employee extends Resource 193 | { 194 | 195 | //... 196 | public function fields(Request $request) 197 | { 198 | return [ 199 | //... 200 | 201 | NovaChartjs::make('Panel Name', 'novaChartjsMetricValue', function () { 202 | return optional($this->novaChartjsMetricValue()->where('chart_name', $chartName)->first())->metric_values ?? []; 203 | }), 204 | ]; 205 | } 206 | } 207 | ``` 208 | ![Inline Chart without Label](screenshots/InlineMode.jpg "Inline Chart without Label") 209 | 210 | **_NOTE:_** You can pass the name of the chart as the first argument for the `make()` function. You can also chain the `showLabel()` and `notEditable()` methods to show the label and prevent editing the model data via the resource. 211 | 212 | Without `showLabel()` chart will occupy the full width even in Inline Mode. 213 | 214 | 3. You can also display the chart as a relationship table and manage it on a separate page 215 | 216 | ```php 217 | 218 | namespace App\Nova; 219 | 220 | use KirschbaumDevelopment\NovaChartjs\RelationshipPanel; 221 | 222 | class Employee extends Resource 223 | { 224 | 225 | //... 226 | public function fields(Request $request) 227 | { 228 | return [ 229 | //... 230 | 231 | RelationshipPanel::make('Chart Name'), 232 | ]; 233 | } 234 | } 235 | ``` 236 | ![Chart Panel with Relationship](screenshots/AsRelationship.jpg "Chart Panel with Relationship") 237 | 238 | ## Adding Multiple Charts 239 | 240 | You can add multiple charts to your Nova resource by specifying a chart identifier. 241 | 242 | ```php 243 | namespace App\Nova; 244 | 245 | use KirschbaumDevelopment\NovaChartjs\InlinePanel; 246 | 247 | class Employee extends Resource 248 | { 249 | 250 | //... 251 | public function fields(Request $request) 252 | { 253 | return [ 254 | //... 255 | 256 | InlinePanel::make($this, $request, 'First Chart'), 257 | InlinePanel::make($this, $request, 'Second Chart', 'second_chart') 258 | ->showLabel() 259 | ->notEditable() 260 | ->hideFromIndex(), 261 | ]; 262 | } 263 | } 264 | ``` 265 | **_NOTE:_** If no explicit identifier is specified `default` will be used as the identifier for that chart. 266 | 267 | You can use the chart identifiers to specify separate additional datasets and settings for each charts. 268 | 269 | ```php 270 | use KirschbaumDevelopment\NovaChartjs\Traits\HasChart; 271 | use KirschbaumDevelopment\NovaChartjs\Contracts\Chartable; 272 | 273 | class Employee extends Model implements Chartable 274 | { 275 | use HasChart; 276 | 277 | /** 278 | * Should return settings for Nova Chart in prescribed format 279 | * 280 | * @return array 281 | */ 282 | public static function getNovaChartjsSettings(): array 283 | { 284 | return [ 285 | 'default' => [ 286 | 'type' => 'line', 287 | 'titleProp' => 'name', 288 | 'identProp' => 'id', 289 | 'height' => 400, 290 | 'indexColor' => '#999999', 291 | 'color' => '#FF0000', 292 | 'parameters' => ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], 293 | 'options' => ['responsive' => true, 'maintainAspectRatio' => false], 294 | ], 295 | 'second_chart' => [ 296 | 'type' => 'bar', 297 | 'titleProp' => 'name', 298 | 'identProp' => 'id', 299 | 'height' => 400, 300 | 'indexColor' => '#999999', 301 | 'color' => '#FF0000', 302 | 'parameters' => ['Q1', 'Q2', 'Q3', 'Q4'], 303 | 'options' => ['responsive' => true, 'maintainAspectRatio' => false], 304 | ] 305 | ]; 306 | } 307 | 308 | // ... 309 | } 310 | ``` 311 | 312 | ## Settings 313 | 314 | You can add following settings to model settings 315 | 1. `parameters`: It is a list of parameters label for which chart data will be collected. It should be passed as an array. e.g., ["January, "February", "March"] 316 | 2. `height` and `width`: Dimensions of chart. It is recommended to set height and let chart adjust according to width. 317 | 3. `color`: Color value for the base model in chart. 318 | 4. `identProp`: Model property representing the primary key. defaults to `id`. 319 | 5. `labelProp`: Model property used for display label in chart. defaults to `id`. 320 | 6. `indexColor`: Bar Chart color in index view. Falls back to `color` 321 | 7. `type`: `line` or `bar`. defaults to `line`. 322 | 8. `options`: Options are passed directly to ChartJS instance can be used to customize your Chart as detailed in the [documentation](https://www.chartjs.org/docs/latest/) 323 | 324 | ## Adding Chart Data 325 | 326 | After setup, to add chart data for any model, all you need to do is to edit the model after creating it. You will get a list of numeric inputs to add values for each parameter specified in settings. 327 | 328 | ![Adding Chart data](screenshots/EditView.jpg "Adding Chart Data") 329 | 330 | Chart data will also show on Model Index page as a Simple Bar Chart 331 | 332 | ![Index view](screenshots/IndexView.jpg "Index View") 333 | 334 | ## Comparing Models 335 | You can compare other related models to the current model using the comparison dropdown 336 | 337 | ![Comparison dropdown](screenshots/ComparisonDropdown.jpg "Comparison dropdown") 338 | 339 | You can add or remove any model to comparison to checkout how models are stacked against each other. 340 | 341 | ![Comparison chart](screenshots/ModelComparison.jpg "Comparison chart") 342 | 343 | ## Changing Comparison Data 344 | 345 | Chart comparison data is fetched through trait using a static function `getNovaChartjsComparisonData`. You can override this function in your model to change the comparison data. 346 | ```php 347 | namespace App; 348 | 349 | use KirschbaumDevelopment\NovaChartjs\Traits\HasChart; 350 | use KirschbaumDevelopment\NovaChartjs\Contracts\Chartable; 351 | 352 | class Employee extends Model implements Chartable 353 | { 354 | use HasChart; 355 | 356 | //... 357 | 358 | 359 | /** 360 | * Return a list of all models available for comparison to root model 361 | * 362 | * @return \Illuminate\Database\Eloquent\Collection 363 | */ 364 | public static function getNovaChartjsComparisonData(): array 365 | { 366 | return static::with('novaChartjsMetricValue') 367 | ->has('novaChartjsMetricValue') 368 | ->get() 369 | ->map(function ($chartData) use ($chartName) { 370 | $chartData->setAttribute( 371 | 'novaChartjsComparisonData', 372 | optional($chartData->novaChartjsMetricValue()->where('chart_name', $chartName)->first())->metric_values 373 | ); 374 | return $chartData; 375 | }) 376 | ->reject(function ($chartData) { 377 | return empty($chartData->novaChartjsComparisonData); 378 | }) 379 | ->values() 380 | ->toArray(); 381 | } 382 | } 383 | ``` 384 | 385 | ## Changelog 386 | 387 | Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently. 388 | 389 | ## Contributing 390 | 391 | Please see [CONTRIBUTING](CONTRIBUTING.md) for details. 392 | 393 | ## Security 394 | 395 | If you discover any security related issues, please email brandon@kirschbaumdevelopment.com or nathan@kirschbaumdevelopment.com instead of using the issue tracker. 396 | 397 | ## Sponsorship 398 | 399 | Development of this package is sponsored by Kirschbaum Development Group, a developer driven company focused on problem solving, team building, and community. Learn more [about us](https://kirschbaumdevelopment.com) or [join us](https://careers.kirschbaumdevelopment.com)! 400 | 401 | ## License 402 | 403 | The MIT License (MIT). Please see [License File](LICENSE.md) for more information. 404 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "kirschbaum-development/nova-chartjs", 3 | "description": "chart.js Chart Field for Laravel Nova", 4 | "keywords": [ 5 | "laravel", 6 | "nova", 7 | "chart.js" 8 | ], 9 | "license": "MIT", 10 | "require": { 11 | "php": "^8.0" 12 | }, 13 | "repositories": [ 14 | { 15 | "type": "composer", 16 | "url": "https://nova.laravel.com" 17 | } 18 | ], 19 | "require-dev": { 20 | "doctrine/dbal": "^2.12", 21 | "laravel/legacy-factories": "^1.3", 22 | "laravel/nova": "^4.2", 23 | "mockery/mockery": "^1.1", 24 | "orchestra/testbench": "^7.4", 25 | "phpunit/phpunit": "^9.5.10" 26 | }, 27 | "autoload": { 28 | "psr-4": { 29 | "KirschbaumDevelopment\\NovaChartjs\\": "src/" 30 | } 31 | }, 32 | "autoload-dev": { 33 | "psr-4": { 34 | "KirschbaumDevelopment\\NovaChartjs\\Tests\\": "tests/" 35 | } 36 | }, 37 | "extra": { 38 | "laravel": { 39 | "providers": [ 40 | "KirschbaumDevelopment\\NovaChartjs\\NovaChartjsServiceProvider" 41 | ] 42 | } 43 | }, 44 | "config": { 45 | "sort-packages": true 46 | }, 47 | "minimum-stability": "dev", 48 | "prefer-stable": true 49 | } 50 | -------------------------------------------------------------------------------- /dist/css/field.css: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /dist/js/field.js.LICENSE.txt: -------------------------------------------------------------------------------- 1 | /*! 2 | * @kurkle/color v0.2.1 3 | * https://github.com/kurkle/color#readme 4 | * (c) 2022 Jukka Kurkela 5 | * Released under the MIT License 6 | */ 7 | 8 | /*! 9 | * Chart.js v3.9.1 10 | * https://www.chartjs.org 11 | * (c) 2022 Chart.js Contributors 12 | * Released under the MIT License 13 | */ 14 | 15 | /*! 16 | * The buffer module from node.js, for the browser. 17 | * 18 | * @author Feross Aboukhadijeh 19 | * @license MIT 20 | */ 21 | 22 | /*! 23 | * vuex v4.1.0 24 | * (c) 2022 Evan You 25 | * @license MIT 26 | */ 27 | 28 | /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ 29 | 30 | /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ 31 | -------------------------------------------------------------------------------- /dist/mix-manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "/js/field.js": "/js/field.js", 3 | "/css/field.css": "/css/field.css" 4 | } 5 | -------------------------------------------------------------------------------- /migrations/2019_05_22_142633_create_nova_chartjs_metric_values_table.php: -------------------------------------------------------------------------------- 1 | bigIncrements('id'); 16 | $table->morphs('chartable'); 17 | $table->json('metric_values')->nullable(); 18 | $table->timestamps(); 19 | 20 | $table->unique(['chartable_type', 'chartable_id']); 21 | }); 22 | } 23 | 24 | /** 25 | * Reverse the migrations. 26 | */ 27 | public function down() 28 | { 29 | Schema::dropIfExists('nova_chartjs_metric_values'); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /migrations/2020_10_28_105921_add_chart_name_to_nova_chartjs_metric_values.php: -------------------------------------------------------------------------------- 1 | string('chart_name', 100)->after('metric_values')->default('default'); 16 | 17 | $table->dropUnique('nova_chartjs_metric_values_chartable_type_chartable_id_unique'); 18 | $table->unique(['chartable_type', 'chartable_id', 'chart_name'], 'nova_chartjs_metric_values_chart_unique'); 19 | }); 20 | } 21 | 22 | /** 23 | * Reverse the migrations. 24 | */ 25 | public function down() 26 | { 27 | Schema::table('nova_chartjs_metric_values', function (Blueprint $table) { 28 | $table->dropUnique('nova_chartjs_metric_values_chart_unique'); 29 | 30 | $table->unique(['chartable_type', 'chartable_id']); 31 | }); 32 | 33 | Schema::table('nova_chartjs_metric_values', function (Blueprint $table) { 34 | $table->dropColumn('chart_name'); 35 | }); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /mix.js: -------------------------------------------------------------------------------- 1 | const mix = require("laravel-mix"); 2 | const webpack = require("webpack"); 3 | const path = require("path"); 4 | 5 | class NovaExtension { 6 | name() { 7 | return "nova-extension"; 8 | } 9 | 10 | register(name) { 11 | this.name = name; 12 | } 13 | 14 | webpackPlugins() { 15 | return new webpack.ProvidePlugin({ 16 | _: "lodash", 17 | Errors: "form-backend-validation", 18 | }); 19 | } 20 | 21 | webpackConfig(webpackConfig) { 22 | webpackConfig.externals = { 23 | vue: "Vue", 24 | }; 25 | 26 | webpackConfig.resolve.alias = { 27 | ...(webpackConfig.resolve.alias || {}), 28 | "laravel-nova": path.join( 29 | __dirname, 30 | "../../vendor/laravel/nova/resources/js/mixins/packages.js" 31 | ), 32 | }; 33 | 34 | webpackConfig.output = { 35 | uniqueName: this.name, 36 | }; 37 | } 38 | } 39 | 40 | mix.extend("nova", new NovaExtension()); 41 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "private": true, 3 | "scripts": { 4 | "dev": "npm run development", 5 | "development": "mix", 6 | "watch": "mix watch", 7 | "watch-poll": "mix watch -- --watch-options-poll=1000", 8 | "hot": "mix watch --hot", 9 | "prod": "npm run production", 10 | "production": "mix --production" 11 | }, 12 | "devDependencies": { 13 | "@inertiajs/inertia": "^0.11.0", 14 | "@vue/babel-plugin-jsx": "^1.1.0", 15 | "@vue/compiler-sfc": "^3.2.22", 16 | "form-backend-validation": "^2.3.3", 17 | "inflector-js": "^1.0.1", 18 | "laravel-mix": "^6.0.41", 19 | "lodash": "^4.17.21", 20 | "postcss": "^8.3.11", 21 | "vue-loader": "^16.8.3", 22 | "vuex": "^4.0.2" 23 | }, 24 | "dependencies": { 25 | "chart.js": "^3.7.0", 26 | "vue": "^3.2.47", 27 | "vue-chartjs": "^4", 28 | "vue-multiselect": "^3.0.0-beta.1" 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /phpunit.xml.dist: -------------------------------------------------------------------------------- 1 | 2 | 12 | 13 | 14 | tests 15 | 16 | 17 | 18 | 19 | src/ 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /resources/css/field.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kirschbaum-development/nova-chartjs/58a6b216be56ea71fe8d199ea629e27e2a4d9dea/resources/css/field.css -------------------------------------------------------------------------------- /resources/imgs/banner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kirschbaum-development/nova-chartjs/58a6b216be56ea71fe8d199ea629e27e2a4d9dea/resources/imgs/banner.png -------------------------------------------------------------------------------- /resources/js/components/ChartjsBarChart.vue: -------------------------------------------------------------------------------- 1 | 9 | 10 | 33 | -------------------------------------------------------------------------------- /resources/js/components/ChartjsLineChart.vue: -------------------------------------------------------------------------------- 1 | 9 | 10 | 33 | -------------------------------------------------------------------------------- /resources/js/components/DetailField.vue: -------------------------------------------------------------------------------- 1 | 47 | 48 | 198 | -------------------------------------------------------------------------------- /resources/js/components/FormField.vue: -------------------------------------------------------------------------------- 1 | 8 | 9 | 55 | -------------------------------------------------------------------------------- /resources/js/components/IndexField.vue: -------------------------------------------------------------------------------- 1 | 6 | 7 | 45 | -------------------------------------------------------------------------------- /resources/js/components/IndexViewChart.vue: -------------------------------------------------------------------------------- 1 | 9 | 10 | 52 | -------------------------------------------------------------------------------- /resources/js/components/ParameterEditor.vue: -------------------------------------------------------------------------------- 1 | 22 | 23 | 31 | -------------------------------------------------------------------------------- /resources/js/field.js: -------------------------------------------------------------------------------- 1 | import IndexField from './components/IndexField'; 2 | import DetailField from './components/DetailField'; 3 | import FormField from './components/FormField'; 4 | 5 | Nova.booting(Vue => { 6 | Vue.component('index-nova-chartjs', IndexField); 7 | Vue.component('detail-nova-chartjs', DetailField); 8 | Vue.component('form-nova-chartjs', FormField); 9 | }); 10 | -------------------------------------------------------------------------------- /resources/js/mixins/charts.js: -------------------------------------------------------------------------------- 1 | export default{ 2 | methods:{ 3 | createChartDataset: function(){ 4 | let datasets = [...this.additionalDatasets]; 5 | 6 | for (let data in this.dataset) { 7 | datasets.unshift( 8 | { 9 | ...this.dataset[data], 10 | ...{fill:false} 11 | } 12 | ); 13 | } 14 | 15 | return { 16 | labels: this.settings.parameters, 17 | datasets: datasets 18 | } 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /resources/js/mixins/colors.js: -------------------------------------------------------------------------------- 1 | export default{ 2 | methods:{ 3 | getRandomColor: function() { 4 | return "#"+((1<<24)*Math.random()|0).toString(16); 5 | }, 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /resources/js/mixins/datasetHandler.js: -------------------------------------------------------------------------------- 1 | export default{ 2 | methods:{ 3 | getAllowedParametersFromDataset: function(parameters, dataset = []) { 4 | return parameters.map(key => dataset[key] || 0); 5 | } 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /routes/api.php: -------------------------------------------------------------------------------- 1 | all(); 12 | $resource = resolve($field["model"])->find($field["ident"]); 13 | 14 | return response()->json([ 15 | 'additionalDatasets' => data_get( 16 | $resource->getAdditionalDatasets(), 17 | $field["chartName"], 18 | [] 19 | ), 20 | ]); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/Http/Controllers/RetrieveModelComparisonDataController.php: -------------------------------------------------------------------------------- 1 | all(); 12 | $resource = resolve(data_get($request, "field.model"))->find(data_get($request,"field.ident")); 13 | 14 | return response()->json([ 15 | 'comparison' => $resource::getNovaChartjsComparisonData( 16 | data_get($request, "field.chartName"), 17 | data_get($request, "searchFields"), 18 | data_get($request, "searchValue"), 19 | ), 20 | ]); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/InlinePanel.php: -------------------------------------------------------------------------------- 1 | prepareFields( 32 | $this->fields($resource->resource, $request, $panelTitle, $chartName) 33 | ) 34 | ); 35 | } 36 | 37 | /** 38 | * Fields for the inline chart panel. 39 | * 40 | * @param Chartable $chartable 41 | * @param Request $request 42 | * @param mixed $panelTitle 43 | * @param bool $showLabel 44 | * @param bool $notEditable 45 | * @param bool $hideFromIndex 46 | * @param string $chartName 47 | * 48 | * @return array 49 | */ 50 | protected function fields( 51 | Chartable $chartable, 52 | Request $request, 53 | $panelTitle = 'Chart Metric Values', 54 | $chartName = 'default' 55 | ): array { 56 | $field = NovaChartjs::make($panelTitle, 'novaChartjsMetricValue', function () use ($chartable, $chartName) { 57 | return optional( 58 | $chartable->novaChartjsMetricValue() 59 | ->where('chart_name', $chartName) 60 | ->first() 61 | )->metric_values ?? []; 62 | }); 63 | 64 | $field->chartName($chartName); 65 | 66 | return [$field]; 67 | } 68 | 69 | /** 70 | * Specify that the fields should be hidden from the index view. 71 | * 72 | * @return $this 73 | */ 74 | public function hideFromIndex() 75 | { 76 | foreach ($this->data as $field) { 77 | $field->hideFromIndex(); 78 | } 79 | 80 | return $this; 81 | } 82 | 83 | /** 84 | * Specify that the fields should be editable. 85 | * 86 | * @return $this 87 | */ 88 | public function notEditable() 89 | { 90 | foreach ($this->data as $field) { 91 | $field->notEditable(); 92 | } 93 | 94 | return $this; 95 | } 96 | 97 | /** 98 | * Specify that the fields should show the label. 99 | * 100 | * @return $this 101 | */ 102 | public function showLabel() 103 | { 104 | foreach ($this->data as $field) { 105 | $field->showLabel(); 106 | } 107 | 108 | return $this; 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /src/Models/NovaChartjsMetricValue.php: -------------------------------------------------------------------------------- 1 | 'array', 27 | ]; 28 | 29 | /** 30 | * Return Chartable model for which this Metric Values are stored. 31 | * 32 | * @return MorphTo 33 | */ 34 | public function chartable(): MorphTo 35 | { 36 | return $this->morphTo(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/Nova/MetricValue.php: -------------------------------------------------------------------------------- 1 | rules('required', 'json'); 46 | $field->showOnCreation = true; 47 | $field->chartName($this->chart_name ?? 'default'); 48 | 49 | return [ 50 | $field, 51 | Text::make('Chart Name'), 52 | MorphTo::make('Chartable')->onlyOnIndex(), 53 | ]; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/NovaChartjs.php: -------------------------------------------------------------------------------- 1 | withMeta([ 32 | 'showLabel' => false, 33 | 'notEditable' => false, 34 | 'chartName' => 'default', 35 | 'searchFields' => 'id', 36 | ]); 37 | } 38 | 39 | /** 40 | * @deprecated This method has been deprecated and will be removed in next major update. 41 | * 42 | * Pass chartable model to NovaChartjs to fetch settings. 43 | * 44 | * @return NovaChartjs 45 | */ 46 | public function chartable(): self 47 | { 48 | return $this; 49 | } 50 | 51 | /** 52 | * Resolve the field's value. 53 | * 54 | * @param mixed $resource 55 | * @param string|null $attribute 56 | */ 57 | public function resolve($resource, $attribute = null) 58 | { 59 | parent::resolve($resource, $attribute); 60 | 61 | if ($resource instanceof NovaChartjsMetricValue) { 62 | $resource = $resource->chartable; 63 | } 64 | 65 | if (! empty($resource)) { 66 | $settings = data_get($resource::getNovaChartjsSettings(), $this->getChartName(), []); 67 | 68 | $this->withMeta([ 69 | 'settings' => $settings, 70 | 'model' => get_class($resource), 71 | 'searchFields' => data_get($this->meta(), 'searchFields', data_get($settings, 'titleProp', 'id')), 72 | 'chartableName' => Str::singular(Str::title(Str::snake(class_basename($resource), ' '))), 73 | 'title' => $this->getChartableProp($resource, $settings['titleProp'] ?? $resource->getKeyName()), 74 | 'ident' => $this->getChartableProp($resource, $settings['identProp'] ?? $resource->getKeyName()), 75 | ]); 76 | } 77 | } 78 | 79 | /** 80 | * Set chart name for the chart. 81 | * 82 | * @param string $chartName 83 | * 84 | * @return NovaChartjs 85 | */ 86 | public function chartName($chartName = 'default'): self 87 | { 88 | return $this->withMeta([ 89 | 'chartName' => $chartName, 90 | ]); 91 | } 92 | 93 | /** 94 | * Hide Label to make Chart occupy full width. 95 | * 96 | * @return NovaChartjs 97 | */ 98 | public function showLabel(): self 99 | { 100 | return $this->withMeta([ 101 | 'showLabel' => true, 102 | ]); 103 | } 104 | 105 | /** 106 | * set whether a user can edit a model data. 107 | * 108 | * @return NovaChartjs 109 | */ 110 | public function notEditable(): self 111 | { 112 | $this->hideWhenUpdating() 113 | ->hideFromIndex(); 114 | 115 | return $this->withMeta([ 116 | 'notEditable' => true, 117 | ]); 118 | } 119 | 120 | /** 121 | * Fetch a property from Chartable. 122 | * 123 | * @param Chartable $chartable 124 | * @param string $prop 125 | * 126 | * @return string 127 | */ 128 | public function getChartableProp(Chartable $chartable, string $prop = 'id'): string 129 | { 130 | return $chartable->{$prop} ?? 'Unknown'; 131 | } 132 | 133 | /** 134 | * Hydrate the given attribute on the model based on the incoming request. 135 | * 136 | * @param \Laravel\Nova\Http\Requests\NovaRequest $request 137 | * @param string $requestAttribute 138 | * @param object $model 139 | * @param string $attribute 140 | * 141 | * @return mixed 142 | */ 143 | protected function fillAttributeFromRequest(NovaRequest $request, $requestAttribute, $model, $attribute) 144 | { 145 | if ($model instanceof NovaChartjsMetricValue) { 146 | $value = json_decode($request[$requestAttribute], true); 147 | $model->{$attribute} = $this->isNullValue($value) ? null : $value; 148 | } 149 | 150 | $chartName = $this->getChartName(); 151 | $attributeName = sprintf('%s_%s', $requestAttribute, $chartName); 152 | 153 | if ($request->exists($attributeName)) { 154 | $value = json_decode($request[$attributeName], true); 155 | $model->{$attribute} = [ 156 | 'chartName' => $chartName, 157 | 'chartValue' => $this->isNullValue($value) ? null : $value, 158 | ]; 159 | } 160 | } 161 | 162 | /** 163 | * Returns chartname for current chart. 164 | * 165 | * @return string 166 | */ 167 | protected function getChartName() 168 | { 169 | return data_get($this->meta(), 'chartName', 'default'); 170 | } 171 | } 172 | -------------------------------------------------------------------------------- /src/NovaChartjsServiceProvider.php: -------------------------------------------------------------------------------- 1 | loadMigrations(); 18 | $this->registerResources(); 19 | $this->serveField(); 20 | $this->app->booted(function () { 21 | $this->routes(); 22 | }); 23 | } 24 | 25 | protected function loadMigrations() 26 | { 27 | $this->loadMigrationsFrom(__DIR__ . '/../migrations'); 28 | } 29 | 30 | protected function serveField(): void 31 | { 32 | Nova::serving(function () { 33 | Nova::script('nova-chartjs', __DIR__ . '/../dist/js/field.js'); 34 | Nova::style('nova-chartjs', __DIR__ . '/../dist/css/field.css'); 35 | }); 36 | } 37 | 38 | protected function registerResources(): void 39 | { 40 | Nova::resources([ 41 | MetricValue::class, 42 | ]); 43 | } 44 | 45 | /** 46 | * Register package routes. 47 | * 48 | * @return void 49 | */ 50 | protected function routes() 51 | { 52 | if ($this->app->routesAreCached()) { 53 | return; 54 | } 55 | 56 | Route::middleware(['nova']) 57 | ->prefix('nova-chartjs') 58 | ->group(__DIR__.'/../routes/api.php'); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/RelationshipPanel.php: -------------------------------------------------------------------------------- 1 | prepareFields($this->fields($panelTitle)) 21 | ); 22 | } 23 | 24 | /** 25 | * Fields for the chart panel. 26 | * 27 | * @param mixed $panelTitle 28 | * 29 | * @return array 30 | */ 31 | protected function fields($panelTitle = 'Chart Metric Values'): array 32 | { 33 | return [ 34 | MorphMany::make($panelTitle, 'novaChartjsMetricValue', MetricValue::class), 35 | ]; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/Traits/HasChart.php: -------------------------------------------------------------------------------- 1 | MorphMany(NovaChartjsMetricValue::class, 'chartable'); 21 | } 22 | 23 | /** 24 | * Delete a models chart data before model is deleted. 25 | */ 26 | public static function bootHasChart() 27 | { 28 | static::deleting(function ($model) { 29 | if ($model->novaChartjsMetricValue) { 30 | $model->novaChartjsMetricValue->each->delete(); 31 | } 32 | }); 33 | 34 | static::created(function ($model) { 35 | collect($model->unsavedMetricValues)->each(function ($chartData) use ($model) { 36 | $model->novaChartjsMetricValue()->create($chartData); 37 | }); 38 | }); 39 | } 40 | 41 | /** 42 | * Mutator to set Metric Values from Chartable model. 43 | * 44 | * @param $value 45 | */ 46 | public function setNovaChartjsMetricValueAttribute($value): void 47 | { 48 | $chartName = data_get($value, 'chartName', 'default'); 49 | $chartValue = data_get($value, 'chartValue', []); 50 | 51 | $chartInstance = $this->novaChartjsMetricValue()->where('chart_name', $chartName)->first(); 52 | 53 | if (empty($chartInstance)) { 54 | $this->getKey() 55 | ? $this->novaChartjsMetricValue()->create([ 56 | 'metric_values' => $chartValue, 57 | 'chart_name' => $chartName, 58 | ]) 59 | : $this->unsavedMetricValues[] = [ 60 | 'metric_values' => $chartValue, 61 | 'chart_name' => $chartName, 62 | ]; 63 | 64 | return; 65 | } 66 | 67 | $chartInstance->metric_values = $chartValue; 68 | $chartInstance->save(); 69 | } 70 | 71 | /** 72 | * Return a list of all models available for comparison to root model. 73 | * 74 | * @param string $chartName 75 | * 76 | * @return array 77 | */ 78 | public static function getNovaChartjsComparisonData($chartName = 'default', $searchFields = 'id', $searchValue = ''): array 79 | { 80 | $resources = static::query() 81 | ->has('novaChartjsMetricValue') 82 | ->when($searchFields && $searchValue, function ($query) use ($searchFields, $searchValue){ 83 | return static::resolveSearchQuery($query, $searchFields, $searchValue); 84 | }) 85 | ->get(); 86 | 87 | $charts = NovaChartjsMetricValue::query() 88 | ->select('chartable_id', 'metric_values') 89 | ->whereIn('chartable_id', $resources->pluck('id')) 90 | ->where('chartable_type', static::class) 91 | ->where('chart_name', $chartName) 92 | ->toBase() 93 | ->get(); 94 | 95 | return $resources->map(function ($resource) use ($charts) { 96 | $data = optional($charts->first(function ($chart) use ($resource) { 97 | return $chart->chartable_id === $resource->id; 98 | }))->metric_values; 99 | 100 | $resource->setAttribute( 101 | 'novaChartjsComparisonData', 102 | $data ? json_decode($data, true) : null, 103 | ); 104 | 105 | return $resource; 106 | }) 107 | ->values() 108 | ->toArray(); 109 | } 110 | 111 | public static function resolveSearchQuery($query, $searchFields, $searchValue) 112 | { 113 | if (is_array($searchFields)) { 114 | $firstField = Arr::pull($searchFields, 0); 115 | $query->where($firstField, 'like', "%{$searchValue}%"); 116 | 117 | foreach ($searchFields as $field) { 118 | $query->orWhere(function ($query) use ($field, $searchValue) { 119 | return $query->where($field, 'like', "%{$searchValue}%"); 120 | }); 121 | } 122 | return $query; 123 | } 124 | 125 | return $query->where($searchFields, 'like', "%{$searchValue}%"); 126 | } 127 | 128 | /** 129 | * Return a list of additional datasets added to chart. 130 | * 131 | * @return array 132 | */ 133 | public function getAdditionalDatasets(): array 134 | { 135 | return [ 136 | 'default' => [], 137 | ]; 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /src/Traits/RedirectsOnCreate.php: -------------------------------------------------------------------------------- 1 | getKey() . '/edit'; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /tests/Chartable.php: -------------------------------------------------------------------------------- 1 | [ 32 | 'Bananna', 33 | 'Apple', 34 | 'Pear', 35 | ], 36 | ]; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /tests/TestCase.php: -------------------------------------------------------------------------------- 1 | withFactories(realpath(dirname(__DIR__) . '/tests/factories')); 21 | 22 | $this->loadMigrationsFrom(realpath(dirname(__DIR__)) . '/migrations'); 23 | 24 | $this->setUpDatabase($this->app); 25 | 26 | $this->createTestModels(); 27 | 28 | $this->testChartable = Chartable::first(); 29 | } 30 | 31 | /** 32 | * Set up the environment. 33 | * 34 | * @param \Illuminate\Foundation\Application $app 35 | */ 36 | protected function getEnvironmentSetUp($app): void 37 | { 38 | $app['config']->set('app.key', 'AckfSECXIvnK5r28GVIWUAxmbBSjTsmF'); 39 | $app['config']->set('database.default', 'sqlite'); 40 | $app['config']->set('database.connections.sqlite', [ 41 | 'driver' => 'sqlite', 42 | 'database' => ':memory:', 43 | 'prefix' => '', 44 | ]); 45 | } 46 | 47 | /** 48 | * Set up the database. 49 | * 50 | * @param \Illuminate\Foundation\Application $app 51 | */ 52 | protected function setUpDatabase($app): void 53 | { 54 | $app['db']->connection()->getSchemaBuilder()->create('chartables', function (Blueprint $table) { 55 | $table->increments('id'); 56 | $table->string('name'); 57 | $table->softDeletes(); 58 | }); 59 | } 60 | 61 | /** 62 | * Create Chartable Model for Testing. 63 | */ 64 | protected function createTestModels(): void 65 | { 66 | Chartable::create(['name' => 'TestChartable']); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /tests/Unit/ChartableTest.php: -------------------------------------------------------------------------------- 1 | make(); 28 | $secondMetricValue = factory(NovaChartjsMetricValue::class)->make(); 29 | 30 | $this->assertCount(0, $this->testChartable->novaChartjsMetricValue); 31 | $this->addNovaChartjsMetricValueToChartable($firstMetricValue); 32 | $this->testChartable->fresh(); 33 | $this->assertNotNull($this->testChartable->novaChartjsMetricValue()->where('chart_name', 'default')->first()); 34 | 35 | $this->expectException(QueryException::class); 36 | $this->addNovaChartjsMetricValueToChartable($secondMetricValue); 37 | } 38 | 39 | public function testChartableCanReturnHisMetricValue() 40 | { 41 | $this->addNovaChartjsMetricValueToChartable(); 42 | 43 | $this->assertInstanceOf(NovaChartjsMetricValue::class, $this->testChartable->novaChartjsMetricValue()->first()); 44 | } 45 | 46 | public function testChartableCanAutomaticallyCreateMetricValuesInRelationshipIfPassedBeforeCreating() 47 | { 48 | $chartable = new Chartable(['name' => 'Unsaved Chartable']); 49 | $testArray = ['chartName' => 'default', 'chartValue' => ['January' => 10, 'February' => 30]]; 50 | $chartable->novaChartjsMetricValue = $testArray; 51 | 52 | $this->assertCount(0, $this->testChartable->novaChartjsMetricValue); 53 | $chartable->save(); 54 | 55 | tap($chartable->fresh(), function ($chartable) use ($testArray) { 56 | $this->assertInstanceOf( 57 | NovaChartjsMetricValue::class, 58 | $chartable->novaChartjsMetricValue()->first() 59 | ); 60 | $this->assertEquals( 61 | $testArray['chartValue'], 62 | $chartable->novaChartjsMetricValue()->first()->metric_values 63 | ); 64 | }); 65 | } 66 | 67 | public function testChartableCanAutomaticallyCreateNewMetricValuesInRelationshipIfNeededAndPassedBeforeUpdating() 68 | { 69 | $this->assertCount(0, $this->testChartable->novaChartjsMetricValue); 70 | 71 | $testArray = ['chartName' => 'default', 'chartValue' => ['January' => 10, 'February' => 30]]; 72 | $this->testChartable->novaChartjsMetricValue = $testArray; 73 | $this->testChartable->save(); 74 | 75 | tap($this->testChartable->fresh(), function ($chartable) use ($testArray) { 76 | $this->assertInstanceOf( 77 | NovaChartjsMetricValue::class, 78 | $chartable->novaChartjsMetricValue()->first() 79 | ); 80 | $this->assertEquals( 81 | $testArray['chartValue'], 82 | $chartable->novaChartjsMetricValue()->first()->metric_values 83 | ); 84 | }); 85 | } 86 | 87 | public function testChartableCanAutomaticallyUpdateMetricValuesInRelationshipIfPassedBeforeUpdating() 88 | { 89 | $metricValue = factory(NovaChartjsMetricValue::class)->make(); 90 | $this->addNovaChartjsMetricValueToChartable($metricValue); 91 | $this->assertInstanceOf( 92 | NovaChartjsMetricValue::class, 93 | $this->testChartable->novaChartjsMetricValue()->first() 94 | ); 95 | $this->assertEquals( 96 | $metricValue->metric_values, 97 | $this->testChartable->novaChartjsMetricValue()->first()->metric_values 98 | ); 99 | 100 | $testArray = ['chartName' => 'default', 'chartValue' => ['January' => 10, 'February' => 30]]; 101 | $this->testChartable->novaChartjsMetricValue = $testArray; 102 | $this->testChartable->save(); 103 | 104 | tap($this->testChartable->fresh(), function ($chartable) use ($testArray, $metricValue) { 105 | $this->assertNotEquals( 106 | $metricValue->metric_values, 107 | $chartable->novaChartjsMetricValue()->first()->metric_values 108 | ); 109 | $this->assertEquals( 110 | $testArray['chartValue'], 111 | $chartable->novaChartjsMetricValue()->first()->metric_values 112 | ); 113 | }); 114 | } 115 | 116 | public function testChartableAdditionOfMoreThanOneMetricValues() 117 | { 118 | $metricValue = factory(NovaChartjsMetricValue::class)->make(); 119 | $this->addNovaChartjsMetricValueToChartable($metricValue); 120 | $secondaryMetricValue = factory(NovaChartjsMetricValue::class)->make(['chart_name' => 'second']); 121 | $this->addNovaChartjsMetricValueToChartable($secondaryMetricValue); 122 | 123 | $this->assertCount(2, $this->testChartable->novaChartjsMetricValue); 124 | } 125 | 126 | public function testChartableCanUpdateTheRightInstaceOfMetricValues() 127 | { 128 | $metricValue = factory(NovaChartjsMetricValue::class)->make(); 129 | $this->addNovaChartjsMetricValueToChartable($metricValue); 130 | $secondaryMetricValue = factory(NovaChartjsMetricValue::class)->make(['chart_name' => 'second']); 131 | $this->addNovaChartjsMetricValueToChartable($secondaryMetricValue); 132 | 133 | $this->assertCount(2, $this->testChartable->novaChartjsMetricValue); 134 | 135 | $testArray = ['chartName' => 'second', 'chartValue' => ['January' => 10, 'February' => 30]]; 136 | $this->testChartable->novaChartjsMetricValue = $testArray; 137 | $this->testChartable->save(); 138 | 139 | tap($this->testChartable->fresh(), function ($chartable) use ($secondaryMetricValue, $testArray) { 140 | $this->assertNotEquals( 141 | $secondaryMetricValue->metric_values, 142 | $chartable->novaChartjsMetricValue()->where('chart_name', 'second')->first()->metric_values 143 | ); 144 | $this->assertEquals( 145 | $testArray['chartValue'], 146 | $chartable->novaChartjsMetricValue()->where('chart_name', 'second')->first()->metric_values 147 | ); 148 | }); 149 | } 150 | 151 | /** 152 | * Adds a NovaChartjsMetricValue to a Chartable Model. 153 | * 154 | * @param NovaChartjsMetricValue|null $metricValue 155 | * @param Chartable|null $chartable 156 | */ 157 | protected function addNovaChartjsMetricValueToChartable( 158 | NovaChartjsMetricValue $metricValue = null, 159 | Chartable $chartable = null 160 | ): void { 161 | if (empty($metricValue)) { 162 | $metricValue = factory(NovaChartjsMetricValue::class)->make(); 163 | } 164 | 165 | if (empty($chartable)) { 166 | $chartable = $this->testChartable; 167 | } 168 | 169 | $chartable->novaChartjsMetricValue()->create($metricValue->toArray()); 170 | } 171 | } 172 | -------------------------------------------------------------------------------- /tests/factories/NovaChartjsMetricValueFactory.php: -------------------------------------------------------------------------------- 1 | define(NovaChartjsMetricValue::class, function (Faker $faker) { 7 | return [ 8 | 'chart_name' => 'default', 9 | 'metric_values' => [ 10 | 'Banana' => $faker->numberBetween(0, 100), 11 | 'Apple' => $faker->numberBetween(0, 100), 12 | 'Pear' => $faker->numberBetween(0, 100), 13 | ], 14 | ]; 15 | }); 16 | -------------------------------------------------------------------------------- /webpack.mix.js: -------------------------------------------------------------------------------- 1 | let mix = require('laravel-mix'); 2 | let path = require('path'); 3 | 4 | 5 | mix.alias({ 6 | 'laravel-nova$': path.join(__dirname, 'vendor/laravel/nova/resources/js/mixins/packages.js'), 7 | '@': path.join(__dirname, 'vendor/laravel/nova/resources/js') 8 | }); 9 | 10 | require('./mix.js'); 11 | 12 | mix.setPublicPath('dist') 13 | .js('resources/js/field.js', 'js') 14 | .vue({ version: 3 }) 15 | .css('resources/css/field.css', 'css') 16 | .nova('kirschbaum-development/nova-chartjs'); 17 | --------------------------------------------------------------------------------