OSDN Git Service

Изменение ошибки определения неучтённого оборудования
[invent/invent.git] / models / Moving.php
1 <?php
2
3 namespace app\models;
4
5 use Yii;
6
7 /**
8  * Это класс модели таблицы перемещений оборудования.
9  *
10  * @property int         $id           Идентификатор записи (неизменяемое)
11  * @property string      $date         Дата перемещения
12  * @property int         $item_id      Идентификатор предмета/оборудования
13  * @property int         $location_id  Идентификатор места размещения
14  * @property int         $state_id     Идентификатор состояния
15  * @property string|null $comment      Комментарии
16  * @property string|null $itemModel    Название модели предмета/оборудования
17  * @property string|null $locationName Наименование места размещения
18  * @property string|null $statusName   Наименование состояния предмета/оборудования
19  * @property string|null $regionName   Наименование региона/подразделения
20  *
21  * @property Items       $item         Предметы/оборудование
22  * @property Locations   $location     Места размещения
23  * @property Status      $state        Состояния
24  * @property Regions     $region       Регион/подразделение
25  */
26 class Moving extends \yii\db\ActiveRecord
27 {
28
29     public $itemModel;
30     public $locationName;
31     public $statusName;
32     public $regionName;
33     
34     /**
35      * {@inheritdoc}
36      */
37     public static function tableName()
38     {
39         return '{{%moving}}';
40     }
41
42     /**
43      * {@inheritdoc}
44      */
45     public function rules()
46     {
47         return [
48             [[ 'date', 'item_id', 'location_id', 'state_id'], 'required' ],
49             [[ 'date', 'itemModel' ], 'safe' ],
50             [[ 'date'],        'date', 'format' => 'dd.MM.yyyy' ],
51             [[ 'date'],        'checkValidDate' ],
52             [[ 'item_id', 'location_id', 'state_id' ], 'default', 'value' => NULL ],
53             [[ 'id', 'item_id', 'location_id', 'state_id' ], 'integer' ],
54             [[ 'comment' ],     'string'],
55             [[ 'item_id' ],     'exist', 'skipOnError' => true, 'targetClass' => Items::className(),     'targetAttribute' => [ 'item_id' => 'id' ]],
56             [[ 'location_id' ], 'exist', 'skipOnError' => true, 'targetClass' => Locations::className(), 'targetAttribute' => [ 'location_id' => 'id' ]],
57             [[ 'state_id' ],    'exist', 'skipOnError' => true, 'targetClass' => Status::className(),    'targetAttribute' => [ 'state_id' => 'id' ]],
58         ];
59     }
60
61     /**
62      * {@inheritdoc}
63      * Подписи в заголовке таблицы
64      */
65     public function attributeLabels()
66     {
67         return [
68             'comment'      => Yii::t('moving',    'Comment'),
69             'date'         => Yii::t('moving',    'Moving date'),
70             'id'           => Yii::t('app',       'Identifier'),
71             'item_id'      => Yii::t('moving',    'Item ID'),
72             'itemModel'    => Yii::t('items',     'Model'),
73             'location_id'  => Yii::t('moving',    'Location ID'),
74             'locationName' => Yii::t('locations', 'Locations'),
75             'regionName'   => Yii::t('regions',   'Region'),
76             'state_id'     => Yii::t('moving',    'Status ID'),
77             'statusName'   => Yii::t('status',    'Status'),
78         ];
79     }
80
81     /**
82      * Проверка даты на следующие условия:
83      * 1. Дата не больше текущей
84      * 2. Если это первая запись о перемещении предмета/оборудования, то дата не меньше 1 января 1990 года
85      * 3. Если есть более ранние перемещения, то дата не меньше самой поздей даты предыдущих перемещений
86      * 4. Если есть более поздние перемещения, то дата не больше самой ранней даты последующих перемещений
87      */
88     public function checkValidDate()
89     {
90         if (!empty($this->date))
91         {
92             $date = strtotime($this->date);
93             //$this->date = date($date);
94             if ($date > strtotime(date('d.m.Y')))
95             {
96                 $this->addError('date', Yii::t('moving', 'The date cannot be more than today'));
97             } else
98             {
99                 if ($date < strtotime('01.01.1900'))
100                 {
101                     $this->addError('date', Yii::t('moving', 'Date cannot be less than {date}', [ 'date' => '01.01.1900' ]));
102                 } else
103                 {
104                     $item_id = $this->item_id;
105
106                     $query = Moving::find()
107                         ->select('MAX(date) AS date, id')
108                         ->groupBy('id')
109                         ->where(['item_id' => $item_id]);
110                     if (!empty($this->id))
111                     {
112                         $query = $query->andWhere(['<', 'id', $this->id]);
113                     }
114                     $query = $query->all();
115
116                     if ((count($query) > 0) && ($date < strtotime($query[0]->date)))
117                     {
118                         $this->addError('date', Yii::t('moving', 'The date cannot be less than {date}', [ 'date' => date('d.m.Y', strtotime($query[0]->date)) ]));
119                     }
120
121                     if (!empty($this->id))
122                     {
123                         $query = Moving::find()
124                             ->select('MIN(date) AS date, id')
125                             ->groupBy('id')
126                             ->where(['item_id' => $item_id])
127                             ->andWhere(['>', 'id', $this->id])
128                             ->all();
129                         if ((count($query) > 0) && ($date > strtotime($query[0]->date)))
130                         {
131                             $this->addError('date', Yii::t('moving', 'The date cannot be more than {date}', [ 'date' => date('d.m.Y', strtotime($query[0]->date)) ]));
132                         }
133                     }
134                 }
135             }
136         }
137     }
138
139     public function beforeSave($insert)
140     {
141         if (!parent::beforeSave($insert))
142         {
143             return false;
144         }
145         $date = strtotime($this->date);
146         $this->date = date('Y-m-d', $date);
147         return true;
148     }
149
150     /**
151      * Получение связанной таблицы предметов/оборудования.
152      *
153      * @return \yii\db\ActiveQuery
154      */
155     public function getItems()
156     {
157         return $this->hasOne(Items::className(), [ 'id' => 'item_id' ]);
158     }
159
160     public function getModels()
161     {
162         return $this->getItems()->select(Models::tableName() . '.*')->joinWith('models');
163     }
164
165     public function getTypes()
166     {
167         return $this->getModels()->select(Types::tableName() . '.*')->joinWith('types');
168     }
169
170     /**
171      * Получение связанной таблицы места размещения.
172      *
173      * @return \yii\db\ActiveQuery
174      */
175     public function getLocations()
176     {
177         return $this->hasOne(Locations::className(), [ 'id' => 'location_id' ]);
178     }
179
180     /**
181      * Получение связанной таблицы региона/подразделения.
182      *
183      * @return \yii\db\ActiveQuery
184      */
185     public function getRegions()
186     {
187         return $this->getLocations()->select(Regions::tableName() . '.*')->joinWith('regions');
188     }
189
190     /**
191      * Получение связанной таблицы состояния.
192      *
193      * @return \yii\db\ActiveQuery
194      */
195     public function getStatus()
196     {
197         return $this->hasOne(Status::className(), [ 'id' => 'state_id' ]);
198     }
199 }