ResourcePriceInput::run()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 0
cts 9
cp 0
rs 9.9332
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 2
1
<?php
2
/**
3
 * Finance module for HiPanel
4
 *
5
 * @link      https://github.com/hiqdev/hipanel-module-finance
6
 * @package   hipanel-module-finance
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2015-2019, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hipanel\modules\finance\widgets;
12
13
use yii\base\Widget;
14
15
class ResourcePriceInput extends Widget
16
{
17
    public $basePrice = 0;
18
    public $activeField;
19
    public $minPrice = 0.00;
20
21
    public function run()
22
    {
23
        $this->registerClientScript();
24
25
        return $this->render('ResourcePriceInput', [
26
            'basePrice' => $this->basePrice,
27
            'activeField' => $this->activeField,
28
            'minPrice' => $this->minPrice,
29
        ]);
30
    }
31
32
    public function registerClientScript()
33
    {
34
        $this->view->registerJs(<<<'JS'
35
            $('.price-input').on('change mouseup', function () {
36
                var price = parseFloat($(this).val());
37
                if (isNaN(price)) return false;
38
                var base = $(this).closest('td').find('.base-price'),
39
                    basePrice = parseFloat(base.attr('data-original-price')),
40
                    minValue = parseFloat($(this).attr('data-min-price')),
41
                    delta = price - basePrice;
42
                
43
                if (delta <= -basePrice && basePrice > 0) {
44
                    $(this).val(minValue).trigger('change');
45
                    return false;
46
                }
47
                
48
                base.removeClass('text-success text-danger');
49
                
50
                base.text(delta.toFixed(2)).addClass(delta >= 0 ? 'text-success' : 'text-danger');
51
            });
52
        
53
            $('.price-input').trigger('change');
54
JS
55
        );
56
57
        $this->view->registerCss('
58
            .base-price { font-weight: bold; }
59
            .form-group.form-group-sm { margin-bottom: 0; }
60
        ');
61
    }
62
}
63