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'],        '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             $date = strtotime($this->date);
92             if ($date > strtotime(date('d.m.Y'))) {
93                 $this->addError('date', Yii::t('moving', 'The date cannot be more than today'));
94             } else {
95                 if ($date < strtotime('01.01.1990')) {
96                     $this->addError('date', Yii::t('moving', 'Date cannot be less than {date}', ['date' => '01.01.1990']));
97                 } else {
98                     $item_id = $this->item_id;
99
100                     $query = Moving::find()
101                         ->select('MAX(date) AS date, id')
102                         ->groupBy('id')
103                         ->where(['item_id' => $item_id]);
104                     if (!empty($this->id)) {
105                         $query = $query->andWhere(['<', 'id', $this->id]);
106                     }
107                     $query = $query->all();
108
109                     if ((count($query) > 0) && ($date < strtotime($query[0]->date))) {
110                         $this->addError('date', Yii::t('moving', 'The date cannot be less than {date}', ['date' => date('d.m.Y', strtotime($query[0]->date))]));
111                     }
112
113                     if (!empty($this->id)) {
114                         $query = Moving::find()
115                             ->select('MIN(date) AS date, id')
116                             ->groupBy('id')
117                             ->where(['item_id' => $item_id])
118                             ->andWhere(['>', 'id', $this->id])
119                             ->all();
120                         if ((count($query) > 0) && ($date > strtotime($query[0]->date))) {
121                             $this->addError('date', Yii::t('moving', 'The date cannot be more than {date}', ['date' => date('d.m.Y', strtotime($query[0]->date))]));
122                         }
123                     }
124                 }
125             }
126         }
127     }
128
129     /**
130      * Получение связанной таблицы предметов/оборудования.
131      *
132      * @return \yii\db\ActiveQuery
133      */
134     public function getItems()
135     {
136         return $this->hasOne(Items::className(), ['id' => 'item_id']);
137     }
138
139     /**
140      * Получение связанной таблицы места размещения.
141      *
142      * @return \yii\db\ActiveQuery
143      */
144     public function getLocations()
145     {
146         return $this->hasOne(Locations::className(), ['id' => 'location_id']);
147     }
148
149     /**
150      * Получение связанной таблицы региона/подразделения.
151      *
152      * @return \yii\db\ActiveQuery
153      */
154     public function getRegions()
155     {
156         return $this->getLocations()->select(Regions::tableName() . '.*')->joinWith('regions');
157     }
158
159     /**
160      * Получение связанной таблицы состояния.
161      *
162      * @return \yii\db\ActiveQuery
163      */
164     public function getStatus()
165     {
166         return $this->hasOne(Status::className(), ['id' => 'state_id']);
167     }
168 }