WorkflowTransitionSimplifiedButtonsWidget.php 11.1 KB
Newer Older
Marcello Pivanti's avatar
Marcello Pivanti committed
1
<?php
Aster's avatar
Aster committed
2

Marcello Pivanti's avatar
Marcello Pivanti committed
3
/**
Aster's avatar
Aster committed
4
5
 * Emilia Romagna Open Innovation
 * Arter
Marcello Pivanti's avatar
Marcello Pivanti committed
6
7
 *
 *
Aster's avatar
Aster committed
8
 * @package    arter\amos\workflow\widgets
Marcello Pivanti's avatar
Marcello Pivanti committed
9
10
11
 * @category   CategoryName
 */

Aster's avatar
Aster committed
12
namespace arter\amos\workflow\widgets;
Marcello Pivanti's avatar
Marcello Pivanti committed
13
14

use DOMDocument;
Aster's avatar
Aster committed
15
16
17
use arter\amos\core\forms\CloseSaveButtonWidget;
use arter\amos\core\module\BaseAmosModule;
use arter\amos\core\record\Record;
Marcello Pivanti's avatar
Marcello Pivanti committed
18
19
20
21
22
23
24
25
use raoul2000\workflow\base\Status;
use yii\base\InvalidConfigException;

/**
 * Class WorkflowTransitionSimplifiedButtonsWidget
 * Renders the widget useful to change a model workflow status showing
 * only a save button for the user.
 *
Aster's avatar
Aster committed
26
 * @package arter\amos\workflow\widgets
Marcello Pivanti's avatar
Marcello Pivanti committed
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
 */
class WorkflowTransitionSimplifiedButtonsWidget extends WorkflowTransitionButtonsWidget
{
    public $transitionStatuses = [];
    public $buttonLabel;

    /**
     * @inheritdoc
     */
    public function run()
    {
        if (!$this->model->isNewRecord || $this->model->isNewRecord && $this->viewWidgetOnNewRecord) {

            if (isset(\Yii::$app->params['hideWorkflowTransitionWidget']) && \Yii::$app->params['hideWorkflowTransitionWidget']) {
                return '';
            }

            /*
             * Buttons to display in page
             */
            $btns = [];

            /*
             * Retrieve reset and save button
             */

            $hiddenActions = null;

            /*
             * Retrieve generated buttons from workflow, passed to the view
             */

            // Se ho lo status settato, mostro i bottoni generati dal workflow

            if ($this->model->hasWorkflowStatus()) {
                $buttonsGot = $this->getButtonToRender();

                $js = "
                $('form').on('submit', function (e) {
                    var buttonId = $('[clicked=true]').attr('id');
                    if (!buttonId) {
                        buttonId = '" . $this->model->getWorkflowStatus()->getId() . "'
                    }
                    $('#workflow-status_id').val(buttonId);
                });
                
                $('[type=submit]').on('click', function(){
                    $('[type=submit]').removeAttr('clicked');
                    $(this).attr('clicked', true);
                });
                "
                    . ((isset($this->customJs)) ? $this->customJs : "");

            } else {
                // Altrimenti passo dei "fake status" (passati come parametro in _NEWform) per generare i vari
                // pulsanti
                $buttonsGot = $this->getButtonToRender();

                $js = "
                $('form').on('submit', function (e) {
                    var buttonId = $('[clicked=true]').attr('id');
                    if (!buttonId) {
                        buttonId = '" . $this->model->getWorkflowSource()->getWorkflow($this->workflowId)->getInitialStatusId() . "'
                    }
                    $('#workflow-status_id').val(buttonId);
                });
                
                $('[type=submit]').on('click', function(){
                    $('[type=submit]').removeAttr('clicked');
                    $(this).attr('clicked', true);
                });
                "
                    . ((isset($this->customJs)) ? $this->customJs : "");
            }

            //$buttonsDom = new DOMDocument();
            //$buttonsDom->loadHTML($buttonsGot);

            $this->getView()->registerJs($js, \yii\web\View::POS_READY);

            // Per ogni bottone generato attraverso il workflow widget (e inserito nella variabile $buttonsGot)
            // attraverso il dom lo estraggo e lo inserisco in un array (in modo tale da ottenere il bottone
            // separato dallo stateDescriptor e renderizzare separatamente i due componenti. Questa suddivisione
            // è stata fatta per non stravolgere il funzionamento attuale della funzione di generazione dei pulsanti
            foreach ($buttonsGot as $key => $button) {

                $buttonsDom = new DOMDocument();
                $buttonsDom->loadHTML($button['button']);
                $buttonsDom->getElementsByTagName('button')[0]->setAttribute('class', $buttonsDom->getElementsByTagName('button')[0]->getAttribute('class') . ' ' . (($key == sizeof($buttonsGot) - 1) ? 'btn-navigation-primary' : 'btn-workflow'));
                $btn = $buttonsDom->saveHTML($buttonsDom->getElementsByTagName('button')[0]);

                $btns[] = [
                    "button" => $btn,
                    "stateDescriptor" => $button['stateDescriptor']
                ];

            }

            $hiddenActions = $this->form->field($this->model, 'status')->hiddenInput(['id' => 'workflow-status_id'])->label(false);

            $notificationInput = $this->renderInputForNotify();

            // Renderizzo separatamente una view con tutti i bottoni
            return $this->render("transition-buttons-render", [
                'widgetClass' => $this->containerWidgetClass,
                'resetButton' => $this->closeButton,
                'buttons' => $btns,
                'hiddenActions' => $hiddenActions,
                'notificationInput' => $notificationInput
            ]);
        } else {
            return '';
        }
    }

    /**
     * @param string $fakeStatus
     * @return array
     * @throws InvalidConfigException
     */
    protected function getButtonToRender()
    {
        $this->statuses = $this->getStatuses();

        $module = ($this->module);

        $User = \Yii::$app->getUser();
        //$inState = !$fakeStatus ? $this->model->getWorkflowStatus()->getId() : $fakeStatus;

        $currentStatus = '';
        if (!$this->model->isNewRecord) {
            $currentStatus = $this->getCurrentStatus();
        }

        /** @var Record $nameClass */
        $nameClass = $this->model->className();
        $pk = $this->model->getPrimaryKey();
        $findOneKey = (!empty($pk) ? $pk : $this->model->id);
        $realState = $nameClass::findOne($findOneKey);

        if ($realState) {
            $this->model->status = $realState->status;
        } else {
            $this->model->status = $this->model->status;
        }

        $inState = $this->model->status;

        if (!is_array($this->transitionStatuses)) {
Aster's avatar
Aster committed
176
            throw new InvalidConfigException("\\arter\amos\workflow\widgets\WorkflowTransitionSimplifiedButtonsWidget:\n the param transitionStatuses must be an array.");
Marcello Pivanti's avatar
Marcello Pivanti committed
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
        }

        $saveButton = [];
        if (empty($this->buttonLabel)) {
            $buttonLabel = $module::t($this->translationCategory, "Salva");
        } else {
            $buttonLabel = $module::t($this->translationCategory, $this->buttonLabel);
        }
        $stateDescriptor = $module::t($this->translationCategory, "#workflow_simplified_button_default_description");

        if (array_key_exists($this->model->status, $this->transitionStatuses)) {

            /** @var Status $state */
            $state = $this->model->getWorkflowSource()->getStatus($this->transitionStatuses[$this->model->status], $this->model);
            $currentState = $this->model->getWorkflowSource()->getStatus($this->model->status, $this->model);
            if ($state && ($this->transitionStatuses[$this->model->status] != $inState)) {
                if ($User->can($state->getId(), ['model' => $this->model])) {
                    $statusesArr[$this->transitionStatuses[$this->model->status]] = $state;
                    $metadati = $state->getMetaData();
                    $metadatiCurrentStatus = $currentState->getMetadata();
                    $hiddenRoles = false;
                    if (isset($metadati['hiddenRoles'])) {
                        if (strpos($metadati['hiddenRoles'], ',')) {
                            $arrRoles = explode(',', $metadati['hiddenRoles']);
                            foreach ($arrRoles as $Role) {
                                if ($User->can(trim($Role))) {
                                    $hiddenRoles = TRUE;
                                }
                            }
                        } else {
                            $hiddenRoles = $User->can($metadati['hiddenRoles']);
                        }
                    }
                    if ((!isset($metadati['hidden']) || (isset($metadati['hidden']) && strtolower($metadati['hidden']) != 'true')) && !$hiddenRoles) {

                        if (isset($metadati[$currentStatus . '_simplifiedDescription'])) {
                            $stateDescriptor = $module::t($this->translationCategory, $metadati[$currentStatus . '_simplifiedDescription']);
                        } elseif (isset($metadati['simplifiedDescription'])) {
                            $stateDescriptor = $module::t($this->translationCategory, $metadati['simplifiedDescription']);
                        }

                        $simplifiedDataConfirm = '';
                        if (isset($metadati[$currentStatus . '_simplifiedMessage'])) {
                            $simplifiedDataConfirm = $module::t($this->translationCategory, $metadati[$currentStatus . '_simplifiedMessage']);
                        } elseif (isset($metadati['simplifiedMessage'])) {
                            $simplifiedDataConfirm = $module::t($this->translationCategory, $metadati['simplifiedMessage']);
                        } else {
                            $simplifiedDataConfirm = (isset($this->dataConfirm) ? $this->dataConfirm : BaseAmosModule::t('amoscore', 'Are you sure you want to change status?'));
                        }

                        $saveButton[] = [
                            'button' => CloseSaveButtonWidget::widget([
                                'model' => $this->model,
                                'layout' => $this->buttonLayout,
                                'buttonSaveLabel' => $buttonLabel,
                                'buttonNewSaveLabel' => $buttonLabel,
                                'buttonClassSave' => 'btn',
                                'buttonId' => $this->transitionStatuses[$this->model->status],
                                'dataConfirm' => $simplifiedDataConfirm
                            ]),

                            'stateDescriptor' => $stateDescriptor,
                        ];
                    } else {

                        $saveButton[] = [
                            'button' => CloseSaveButtonWidget::widget([
                                'model' => $this->model,
                                'layout' => $this->buttonLayout,
                                'buttonSaveLabel' => $buttonLabel,
                                'buttonNewSaveLabel' => $buttonLabel,
                                'buttonClassSave' => 'btn saveBtn',
                            ]),

                            'stateDescriptor' => $stateDescriptor,
                        ];

                    }
                }
            }

        } else {

            $saveButton[] = [
                'button' => CloseSaveButtonWidget::widget([
                    'model' => $this->model,
                    'layout' => $this->buttonLayout,
                    'buttonSaveLabel' => $buttonLabel,
                    'buttonNewSaveLabel' => $buttonLabel,
                    'buttonClassSave' => 'btn saveBtn',
                ]),

                'stateDescriptor' => $stateDescriptor,
            ];

        }

        return $saveButton;
    }
}