Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace app\models;
- use app\behaviors\UploadBehavior;
- use app\components\validators\OgrnValidator;
- use app\helpers\ArrayHelper;
- use app\models\directorySubordinationLevel\DirectorySubordinationLevel;
- use app\models\programs\ProgramFundType;
- use app\models\programs\ProgramStatus;
- use app\models\programs\ProgramVerificationStatus;
- use app\models\search\ProgramsSearch;
- use app\modules\municipalTask\models\MunicipalTaskContract;
- use Yii;
- use app\components\validators\InnValidator;
- use app\components\validators\BikValidator;
- use app\components\validators\RassValidator;
- use app\helpers\PhoneHelper;
- use yii\db\ActiveRecord;
- /**
- * This is the model class for table "organization".
- *
- * @property integer $id
- * @property integer $status
- * @property integer $user_id
- * @property integer $type
- * @property string $name
- * @property string $license_date
- * @property integer $license_number
- * @property string $license_issued
- * @property string $bank_name
- * @property integer $bank_bik
- * @property string $bank_sity
- * @property integer $korr_invoice
- * @property int $correspondent_invoice
- * @property integer $mun
- * @property string $rass_invoice
- * @property string $fio
- * @property string $position
- * @property integer $doc_type
- * @property string $date_proxy
- * @property string $address_legal
- * @property string $address_actual
- * @property string $geocode
- * @property integer $max_child
- * @property integer $amount_child
- * @property integer $inn
- * @property integer $KPP
- * @property integer $OGRN
- * @property integer $okpo
- * @property string $raiting
- * @property string $ground
- * @property string $about
- * @property string $fio_contact
- * @property string $email
- * @property string $full_name
- * @property string $number_proxy
- * @property string $license_issued_dat
- * @property string $refuse_reason
- * @property integer $contracts_count
- * @property string $cratedate
- * @property string $anonymous_update_token
- * @property integer $departament_id
- * @property integer $level_id
- * @property string $svidet
- * @property string $position_min
- * @property int $last
- * @property int $last_year_contract
- * @property string $site
- * @property string $phone
- * @property string $extra_phone
- * @property int $organizational_form
- * @property int $accepted_date
- * @property int $certificate_accounting_limit
- * @property string $receiver
- * @property string $director_name
- * @property int $additional_provider_type_id
- *
- * @property Contracts[] $contracts
- * @property Cooperate[] $cooperates
- * @property Invoices[] $invoices
- * @property Payers $payer
- * @property User $user
- * @property mixed $certprogram
- * @property \yii\db\ActiveQuery $statement
- * @property string $statusName
- * @property bool $isModerating
- * @property \yii\db\ActiveQuery $children
- * @property \yii\db\ActiveQuery $operators
- * @property \yii\db\ActiveQuery $license
- * @property Operators $operator
- * @property string $userName
- * @property \yii\db\ActiveQuery $groups
- * @property Mun $municipality
- * @property \yii\db\ActiveQuery $charter
- * @property \yii\db\ActiveQuery $documents
- * @property bool $requestCanBeUpdated
- * @property bool $isRefused
- * @property \yii\db\ActiveQuery $favorites
- * @property Programs[] $programs
- * @property OrganizationAddress[] $addresses
- * @property OrganizationContractSettings $contractSettings
- * @property string $contractNumber
- * @property DirectoryDepartment $directoryDepartament
- * @property DirectorySubordinationLevel $directorySubordinationLevel
- * @property Payers $suborderPayer
- * @property OrganizationPayerAssignment $organizationPayerAssignment
- * @property AdditionalProviderType $additionalProviderType
- */
- class Organization extends ActiveRecord
- {
- const SCENARIO_GUEST = 'guest';
- const SCENARIO_REFUSING = 'refusing';
- const SCENARIO_MODERATOR = 'moderator';
- const SCENARIO_PAYER = 'payer';
- const SCENARIO_ORGANIZATION = 'organization';
- const SCENARIO_REST_CREATE = 'scenario_rest_create';
- const SCENARIO_REST_UPDATE = 'scenario_rest_update';
- const TYPE_EDUCATION = 1;
- const TYPE_TRAINING = 2;
- const TYPE_IP_WITH_WORKERS = 3;
- const TYPE_IP_WITHOUT_WORKERS = 4;
- const DOC_TYPE_CHARTER = 2;
- const DOC_TYPE_PROXY = 1;
- // Образовательная организация
- const ORGANIZATION_TYPE_EDUCATIONAL = 1;
- // Организация, осуществляющая обучение
- const ORGANIZATION_TYPE_TRAINING = 2;
- // Индивидуальный предприниматель, оказывающий услуги с наймом работников
- const ORGANIZATION_TYPE_IE_WITH_EMPLOYEES = 3;
- // Индивидуальный предприниматель, оказывающий услуги без найма работников
- const ORGANIZATION_TYPE_IE_WITHOUT_EMPLOYEES = 4;
- // Новая организация (не промодерированная)
- const STATUS_NEW = 10;
- // Активная организация
- const STATUS_ACTIVE = 20;
- // Отклоненная организация (можно редактировать заявителю)
- const STATUS_REFUSED = 30;
- // Забаненная организация
- const STATUS_BANNED = 40;
- // Организация без пользователя
- const STATUS_DELETED = 50;
- public $cooperate;
- // Лицензия (документ)
- public $licenseDocument;
- // Устав
- public $charterDocument;
- // Выписка
- public $statementDocument;
- // Иные документы
- public $commonDocuments = [];
- // Капча
- public $verifyCode;
- /**
- * @inheritdoc
- */
- public static function tableName()
- {
- return 'organization';
- }
- public function scenarios()
- {
- $scenarios = parent::scenarios();
- $scenarios[self::SCENARIO_MODERATOR] = $scenarios[self::SCENARIO_DEFAULT];
- $scenarios[self::SCENARIO_GUEST] = [
- 'charterDocument',
- 'statementDocument',
- 'name',
- 'full_name',
- 'organizational_form',
- 'type',
- 'license_date',
- 'license_number',
- 'license_issued',
- 'svidet',
- 'bank_name',
- 'bank_sity',
- 'bank_bik',
- 'korr_invoice',
- 'rass_invoice',
- 'phone',
- 'email',
- 'site',
- 'fio_contact',
- 'address_actual',
- 'address_legal',
- 'inn',
- 'KPP',
- 'OGRN',
- 'last',
- 'mun',
- 'licenseDocument',
- 'commonDocuments',
- 'anonymous_update_token',
- 'departament_id',
- 'level_id',
- 'verifyCode',
- 'additional_provider_type_id'
- ];
- $scenarios[self::SCENARIO_PAYER] = ['certificate_accounting_limit'];
- $scenarios[self::SCENARIO_ORGANIZATION] = [
- 'license_issued_dat',
- 'fio',
- 'position_min',
- 'position',
- 'doc_type',
- 'date_proxy',
- 'number_proxy',
- 'about'
- ];
- $scenarios[self::SCENARIO_REFUSING] = ['refuse_reason'];
- $scenarios[self::SCENARIO_REFUSING] = [];
- $scenarios[self::SCENARIO_REST_CREATE] = [
- 'type',
- 'name',
- 'full_name',
- 'license_date',
- 'license_number',
- 'license_issued',
- 'svidet',
- 'bank_name',
- 'bank_bik',
- 'bank_sity',
- 'korr_invoice',
- 'correspondent_invoice',
- 'rass_invoice',
- 'fio_contact',
- 'address_legal',
- 'address_actual',
- 'inn',
- 'KPP',
- 'OGRN',
- 'okpo',
- 'mun',
- 'email',
- 'site',
- 'phone',
- 'organizational_form',
- 'receiver',
- 'departament_id',
- 'level_id',
- 'director_name',
- 'additional_provider_type_id'
- ];
- $scenarios[self::SCENARIO_REST_UPDATE] = [
- 'type',
- 'name',
- 'full_name',
- 'license_date',
- 'license_number',
- 'license_issued',
- 'svidet',
- 'bank_name',
- 'bank_bik',
- 'bank_sity',
- 'korr_invoice',
- 'correspondent_invoice',
- 'rass_invoice',
- 'fio_contact',
- 'address_legal',
- 'address_actual',
- 'KPP',
- 'OGRN',
- 'okpo',
- 'mun',
- 'email',
- 'site',
- 'phone',
- 'organizational_form',
- 'receiver',
- 'departament_id',
- 'level_id',
- 'director_name',
- 'additional_provider_type_id'
- ];
- return $scenarios;
- }
- /**
- * @inheritdoc
- */
- public function rules()
- {
- return [
- [
- [
- 'name',
- 'bank_name',
- 'bank_bik',
- 'korr_invoice',
- 'rass_invoice',
- 'fio_contact',
- 'address_actual',
- 'email',
- 'full_name',
- 'type',
- 'phone',
- 'address_legal',
- 'mun',
- ],
- 'required',
- 'except' => [self::SCENARIO_REST_CREATE, self::SCENARIO_REST_UPDATE]
- ],
- [['inn', 'name', 'email', 'full_name'], 'required', 'on' => self::SCENARIO_REST_CREATE],
- [['inn'], 'unique', 'on' => self::SCENARIO_REST_CREATE],
- [['organizational_form', 'last', 'bank_sity', 'inn', 'OGRN'], 'required',
- 'except' => [self::SCENARIO_REST_CREATE, self::SCENARIO_REST_UPDATE]],
- [['svidet'], 'required', 'except' => [self::SCENARIO_REST_CREATE, self::SCENARIO_REST_UPDATE],
- 'when' => function($model) {
- return $model->type == self::TYPE_IP_WITH_WORKERS;
- },
- 'whenClient' => "function (attribute, value) {
- return $('#organization-type').val() == 3;
- }"],
- [['license_date', 'license_number', 'license_issued'], 'required', 'except' => [self::SCENARIO_REST_CREATE, self::SCENARIO_REST_UPDATE],
- 'when' => function($model) {
- return $model->type != self::TYPE_IP_WITHOUT_WORKERS;
- },
- 'whenClient' => "function (attribute, value) {
- return $('#organization-type').val() != 4;
- }"],
- [['user_id', 'type', 'doc_type', 'max_child', 'amount_child', 'mun', 'last', 'last_year_contract', 'certprogram', 'status', 'organizational_form', 'certificate_accounting_limit', 'contracts_count'], 'integer'],
- [['license_date', 'date_proxy', 'cratedate', 'accepted_date'], 'safe'],
- [['raiting'], 'number'],
- [['about', 'site', 'refuse_reason', 'anonymous_update_token', 'receiver', 'korr_invoice', 'extra_phone', 'site'], 'string'],
- ['correspondent_invoice', 'integer', 'integerPattern' => '/^[0-9]{20}$/', 'message' => 'Значение должно состоять из 20 цифр'],
- [['email', 'fio', 'bank_sity'], 'string', 'max' => 100],
- [['email'], 'email'],
- [['name', 'license_number', 'license_issued', 'license_issued_dat', 'address_legal', 'address_actual', 'geocode', 'full_name', 'director_name'], 'string', 'max' => 255],
- [[ 'KPP', 'bank_bik'], 'string', 'min' => 9, 'max' => 9],
- [['fio_contact', 'position', 'position_min'], 'string', 'max' => 200],
- [['bank_name',], 'string', 'max' => 150],
- [['ground', 'number_proxy'], 'string', 'max' => 45],
- [['rass_invoice'], 'string', 'max' => 20],
- [['okpo'], 'string', 'min' => 8, 'max' => 10],
- ['rass_invoice', RassValidator::className()],
- [['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'id']],
- [
- ['licenseDocument', 'charterDocument', 'statementDocument', 'commonDocuments'],
- 'safe', 'on' => self::SCENARIO_GUEST
- ],
- ['verifyCode', 'captcha', 'on' => self::SCENARIO_GUEST],
- ['verifyCode', 'required', 'on' => self::SCENARIO_GUEST],
- [['inn'], 'string', 'min' => 10, 'max' => 12],
- [
- ['inn', 'bank_bik', 'rass_invoice', 'OGRN', 'okpo',],
- 'match',
- 'pattern' => '/^\s*[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?\s*$/',
- 'message' => 'Только цифры'
- ],
- [['inn', 'rass_invoice', 'bank_bik'], 'trim'],
- ['inn', InnValidator::className()],
- ['bank_bik', BikValidator::className()],
- [['OGRN'], 'string', 'min' => 13, 'max' => 15],
- ['OGRN', OgrnValidator::className()],
- [['departament_id'], 'exist', 'targetClass' => DirectoryDepartment::className(), 'targetAttribute' => 'id'],
- [['level_id'], 'exist', 'targetClass' => DirectorySubordinationLevel::className(), 'targetAttribute' => 'id'],
- [['additional_provider_type_id'],
- 'required',
- 'whenClient' => self::getIsAdditionalTypeRequiredClient(),
- 'when' => function(Organization $model) {
- return intval($model->type) === self::ORGANIZATION_TYPE_EDUCATIONAL;
- }],
- [['additional_provider_type_id'], 'exist', 'targetClass' => AdditionalProviderType::class, 'targetAttribute' => 'id'],
- ];
- }
- /**
- * @inheritdoc
- */
- public function attributeLabels()
- {
- return [
- 'id' => 'ID',
- 'user_id' => 'User ID',
- 'status' => 'Статус',
- 'organizational_form' => 'Организационно-правовая форма',
- 'type' => 'Тип поставщика',
- 'typeLabel' => 'Тип поставщика',
- 'name' => 'Сокращенное наименование поставщика',
- 'full_name' => 'Полное наименование поставщика',
- 'license_date' => 'Лицензия от',
- 'license_number' => 'Номер лицензии',
- 'license_issued' => 'Кем выдана лицензия',
- 'license_issued_dat' => 'Кем выдана лицензия (в дательном падеже)',
- 'svidet' => 'Cвидетельство о государственной регистрации',
- 'bank_name' => 'Наименование банка',
- 'bank_bik' => 'БИК Банка',
- 'bank_sity' => 'Город банка',
- 'korr_invoice' => 'Лицевой счёт (л/с)',
- 'correspondent_invoice' => 'Корреспондентский счёт (к/с)',
- 'rass_invoice' => 'Расчетный счет',
- 'fio_contact' => 'Контактное лицо',
- 'fio' => 'ФИО представителя поставщика',
- 'position' => 'Должность представителя поставщика',
- 'position_min' => 'Должность представителя поставщика (кратко)',
- 'doc_type' => 'Действующего на основании',
- 'date_proxy' => 'Дата доверенности',
- 'number_proxy' => 'Номер доверенности',
- 'address_legal' => 'Юридический адрес',
- 'address_actual' => 'Фактический адрес',
- 'geocode' => 'Геокод',
- 'max_child' => 'Лимит обучения',
- 'amount_child' => 'Число договоров',
- 'last_year_contract' => 'Число обучающихся за прошлый год',
- 'inn' => 'ИНН',
- 'KPP' => 'КПП',
- 'OGRN' => 'ОГРН',
- 'okpo' => 'ОКПО',
- 'raiting' => 'Рейтинг',
- 'ground' => 'Тип местности в котором расположена поставщик',
- 'username' => 'Логин',
- 'about' => 'Почему выбирают нас',
- 'mun' => 'Муниципальный район',
- 'last' => 'Количество обучающихся в прошлом учебном году (если ребенок обучался на нескольких программах, считаем его несколько раз)',
- 'cratedate' => 'Дата добавления поставщика',
- 'email' => 'E-mail',
- 'site' => 'Сайт',
- 'phone' => 'Телефон',
- 'extra_phone' => 'Комментарии к телефону',
- 'refuse_reason' => 'Причина отказа',
- 'certprogram' => 'Число программ',
- 'licenseDocument' => 'Лицензия',
- 'charterDocument' => 'Устав',
- 'statementDocument' => 'Выписка из ЕГРЮЛ/ЕГРИП',
- 'commonDocuments' => 'Иные документы (не более трёх)',
- 'verifyCode' => 'Проверочный код',
- 'children' => 'Число обучающихся',
- 'programs' => 'Количество программ',
- 'certificate_accounting_limit' => 'Лимит зачисления',
- 'receiver' => 'Получатель (необязательно)',
- 'departament_id' => 'Ведомственная принадлежность',
- 'level_id' => 'Уровень подчиненности',
- 'director_name' => 'Руководитель',
- 'additional_provider_type_id' => 'Тип образовательной организации',
- ];
- }
- /**
- * @return array
- */
- /*
- public function behaviors()
- {
- $defaultAttributes = [
- 'class' => UploadBehavior::class,
- 'multiple' => true,
- 'pathAttribute' => 'path',
- 'baseUrlAttribute' => 'base_url',
- 'nameAttribute' => 'filename',
- 'documentType' => 'type',
- ];
- return [
- array_merge($defaultAttributes, [
- 'attribute' => 'licenseDocument',
- 'uploadRelation' => 'license',
- ]),
- array_merge($defaultAttributes, [
- 'attribute' => 'charterDocument',
- 'uploadRelation' => 'charter',
- ]),
- array_merge($defaultAttributes, [
- 'attribute' => 'statementDocument',
- 'uploadRelation' => 'statement',
- ]),
- array_merge($defaultAttributes, [
- 'attribute' => 'commonDocuments',
- 'uploadRelation' => 'documents',
- ]),
- ];
- }
- */
- /**
- * @inheritdoc
- */
- public function beforeValidate()
- {
- if (!empty($this->commonDocuments) && is_array($this->commonDocuments)) {
- foreach ($this->commonDocuments as $key => $document) {
- $this->commonDocuments[$key]['document_type'] = OrganizationDocument::TYPE_COMMON;
- }
- }
- if (!empty($this->licenseDocument) && is_array($this->licenseDocument)) {
- $this->licenseDocument[0]['document_type'] = OrganizationDocument::TYPE_LICENSE;
- }
- if (!empty($this->charterDocument) && is_array($this->charterDocument)) {
- $this->charterDocument[0]['document_type'] = OrganizationDocument::TYPE_CHARTER;
- }
- if (!empty($this->statementDocument) && is_array($this->statementDocument)) {
- $this->statementDocument[0]['document_type'] = OrganizationDocument::TYPE_STATEMENT;
- }
- if ($this->correspondent_invoice == '') {
- $this->correspondent_invoice = null;
- }
- return parent::beforeValidate();
- }
- /**
- * @param bool $insert
- * @return bool
- */
- public function beforeSave($insert)
- {
- if(parent::beforeSave($insert)){
- $this->phone = PhoneHelper::cleanPhone($this->phone);
- return true;
- }
- return false;
- }
- /**
- * @return \yii\db\ActiveQuery
- */
- public function getContractSettings()
- {
- return $this->hasOne(OrganizationContractSettings::class, ['organization_id' => 'id']);
- }
- /**
- * @return \yii\db\ActiveQuery
- */
- public function getDirectoryDepartament()
- {
- return $this->hasOne(DirectoryDepartment::className(), ['id' => 'departament_id']);
- }
- /**
- * @return \yii\db\ActiveQuery
- */
- public function getDirectorySubordinationLevel()
- {
- return $this->hasOne(DirectorySubordinationLevel::className(), ['id' => 'level_id']);
- }
- /**
- * @return \yii\db\ActiveQuery
- */
- public function getAddresses()
- {
- return $this->hasMany(OrganizationAddress::class, ['organization_id' => 'id']);
- }
- /**
- * @return \yii\db\ActiveQuery
- */
- public function getLicense()
- {
- return $this->hasMany(OrganizationDocument::class, ['organization_id' => 'id'])
- ->andWhere(['type' => OrganizationDocument::TYPE_LICENSE]);
- }
- /**
- * @return \yii\db\ActiveQuery
- */
- public function getChildren()
- {
- return $this->hasMany(Contracts::class, ['organization_id' => 'id']);
- }
- /**
- * @return \yii\db\ActiveQuery
- */
- public function getMunicipalContracts()
- {
- return $this->hasMany(MunicipalTaskContract::class, ['organization_id' => 'id']);
- }
- /**
- * @return \yii\db\ActiveQuery
- */
- public function getCharter()
- {
- return $this->hasMany(OrganizationDocument::class, ['organization_id' => 'id'])
- ->andWhere(['type' => OrganizationDocument::TYPE_CHARTER]);
- }
- /**
- * @return \yii\db\ActiveQuery
- */
- public function getStatement()
- {
- return $this->hasMany(OrganizationDocument::className(), ['organization_id' => 'id'])
- ->andWhere(['type' => OrganizationDocument::TYPE_STATEMENT]);
- }
- /**
- * @return \yii\db\ActiveQuery
- */
- public function getDocuments()
- {
- return $this->hasMany(OrganizationDocument::className(), ['organization_id' => 'id'])
- ->andWhere(['type' => OrganizationDocument::TYPE_COMMON]);
- }
- /**
- * получить общее кол-во программ-черновиков
- *
- * @return integer
- */
- public function getDraftProgramsCount()
- {
- return $this->getPrograms()->where(['programs.status' => ProgramStatus::DRAFT])->count();
- }
- /**
- * получить общее кол-во программ
- *
- * @return integer
- */
- public function getAllProgramsCount()
- {
- $searchCertificatedPrograms = new ProgramsSearch([
- 'organization_id' => $this->id,
- 'verificationStatus' => ProgramVerificationStatus::DONE,
- ]);
- $certificatedProgramsProvider = $searchCertificatedPrograms->search(Yii::$app->request->queryParams);
- return $certificatedProgramsProvider->totalCount;
- }
- /**
- * получить общее кол-во сертифицированных программ
- *
- * @return integer
- */
- public function getCertificatedProgramsCount()
- {
- $searchCertificatedPrograms = new ProgramsSearch([
- 'organization_id' => $this->id,
- 'status' => ProgramStatus::ACTIVE,
- 'verificationStatus' => [ProgramVerificationStatus::DONE, ProgramVerificationStatus::UNDEFINED, ProgramVerificationStatus::WAIT, ProgramVerificationStatus::DENIED],
- ]);
- $certificatedProgramsProvider = $searchCertificatedPrograms->search(Yii::$app->request->queryParams);
- return $certificatedProgramsProvider->totalCount;
- }
- /**
- * получить общее кол-во программ по МЗ
- */
- public function getMunicipalTaskProgramsCount()
- {
- $searchMunicipalTaskPrograms = new ProgramsSearch([
- 'organization_id' => $this->id,
- 'fundType' => ProgramFundType::MUNICIPAL_TASK,
- 'verificationStatus' => [ProgramVerificationStatus::UNDEFINED, ProgramVerificationStatus::WAIT, ProgramVerificationStatus::DONE, ProgramVerificationStatus::DENIED],
- ]);
- $municipalTaskProgramsProvider = $searchMunicipalTaskPrograms->search(Yii::$app->request->queryParams);
- return $municipalTaskProgramsProvider->totalCount;
- }
- /**
- * получить общее кол-во архивных программ
- */
- public function getArchiveProgramsCount()
- {
- $searchArchivePrograms = new ProgramsSearch([
- 'organization_id' => $this->id,
- 'status' => [ProgramStatus::IN_ARCHIVE],
- ]);
- $archiveProgramsProvider = $searchArchivePrograms->search(Yii::$app->request->queryParams);
- return $archiveProgramsProvider->totalCount;
- }
- /**
- * получить кол-во обучающихся
- *
- * @param null $payerId - идентификатор плательщика
- *
- * @return int
- */
- public function getChildrenCount($payerId = null)
- {
- return $this->getChildren()
- ->select('certificates.id')
- ->distinct()
- ->leftJoin(Certificates::tableName(), 'certificates.id = contracts.certificate_id')
- ->andWhere(['contracts.status' => Contracts::STATUS_ACTIVE])
- ->andFilterWhere(['contracts.payer_id' => $payerId])
- ->count();
- }
- public function getChildrenCountMunicipalTask($payerId = null)
- {
- return $this->getMunicipalContracts()
- ->select('certificates.id')
- ->distinct()
- ->leftJoin(Certificates::tableName(), 'certificates.id = municipal_task_contract.certificate_id')
- ->andWhere(['municipal_task_contract.status' => MunicipalTaskContract::STATUS_ACTIVE])
- ->andFilterWhere(['municipal_task_contract.payer_id' => $payerId])
- ->count();
- }
- /**
- * получить кол-во договоров
- *
- * @param null $payerId - идентификатор плательщика
- *
- * @return integer
- */
- public function getContractsCount($payerId = null)
- {
- return $this->getChildren()
- ->andWhere(['contracts.status' => 1])
- ->andFilterWhere(['contracts.payer_id' => $payerId])
- ->count();
- }
- public function getStatusName()
- {
- $title = '';
- switch ($this->status) {
- case self::STATUS_ACTIVE:
- $title = 'Ваша заявка на включение в реестр поставщиков образовательных услуг одобрена, организация внесена в Реестр, и Вы уже даже должны были получить на указанную Вами при формировании заявки электронную почту логин и пароль для входа в личный кабинет. Если логин и пароль Вами не получен – посмотрите в папке «спам» почты, если и там нет письма – обратитесь к оператору.';
- break;
- case self::STATUS_NEW:
- $title = 'Ваша заявка на включение в реестр поставщиков образовательных услуг пока проходит рассмотрение оператором персонифицированного финансирования. Вы получите уведомление о результатах рассмотрения заявки на электронную почту, указанную для организации.';
- break;
- case self::STATUS_REFUSED:
- $title = 'Отказано. Вы можете исправить информацию и отправить заявку повторно.';
- break;
- case self::STATUS_BANNED:
- $title = 'Забанена.';
- break;
- }
- return $title;
- }
- /**
- * @param $status
- * @param $period
- *
- * @return Cooperate
- */
- public function getCooperation($status = null, $period = null)
- {
- return $this->hasOne(Cooperate::class, ['organization_id' => 'id'])
- ->andWhere(['cooperate.payer_id' => Yii::$app->user->getIdentity()->payer->id])
- ->andFilterWhere(['cooperate.status' => $status])
- ->andFilterWhere(['cooperate.period' => $period])
- ->one();
- }
- /**
- * @return \yii\db\ActiveQuery
- */
- public function getContracts()
- {
- return $this->hasMany(Contracts::className(), ['organization_id' => 'id'])->inverseOf('organization');
- }
- public function getActiveContracts()
- {
- return $this->getContracts()->where([Contracts::tableName() . '.status' => [
- Contracts::STATUS_REQUESTED,
- Contracts::STATUS_ACTIVE,
- Contracts::STATUS_ACCEPTED
- ]]);
- }
- /**
- * @return \yii\db\ActiveQuery
- */
- public function getCooperates()
- {
- return $this->hasMany(Cooperate::className(), ['organization_id' => 'id'])->inverseOf('organization');
- }
- public function getCooperatesByPayerId($payerId, $status = null)
- {
- return array_filter($this->cooperates, function ($val) use ($payerId, $status)
- {
- /** @var $val Cooperate */
- return (is_null($status) || $val->status === $status) && $val->payer_id === $payerId;
- });
- }
- /**
- * @return \yii\db\ActiveQuery
- */
- public function getFavorites()
- {
- return $this->hasMany(Favorites::className(), ['organization_id' => 'id']);
- }
- /**
- * @return \yii\db\ActiveQuery
- */
- public function getGroups()
- {
- return $this->hasMany(Groups::className(), ['organization_id' => 'id']);
- }
- /**
- * @return \yii\db\ActiveQuery
- */
- public function getInvoices()
- {
- return $this->hasMany(Invoices::className(), ['organization_id' => 'id']);
- }
- /**
- * @return \yii\db\ActiveQuery
- */
- public function getUser()
- {
- return $this->hasOne(User::className(), ['id' => 'user_id']);
- }
- /**
- * @return \yii\db\ActiveQuery
- */
- public function getMunicipality()
- {
- return $this->hasOne(Mun::className(), ['id' => 'mun'])->inverseOf('organization');
- }
- /**
- * @return string
- */
- public function getUserName()
- {
- return $this->user->username;
- }
- /**
- * @return \yii\db\ActiveQuery
- */
- public function getPrograms()
- {
- return $this->hasMany(Programs::class, ['organization_id' => 'id']);
- }
- /**
- * @return \yii\db\ActiveQuery
- */
- public function getOperators()
- {
- return $this->hasMany(Operators::className(), ['id' => 'operator_id'])
- ->viaTable('organization_operator_assignment', ['organization_id' => 'id']);
- }
- /**
- * @return \yii\db\ActiveQuery
- */
- public function getOperator()
- {
- return $this->hasOne(Operators::className(), ['id' => 'operator_id'])
- ->viaTable('organization_operator_assignment', ['organization_id' => 'id']);
- }
- /**
- * @return \yii\db\ActiveQuery
- */
- public function getOrganizationPayerAssignment()
- {
- return $this->hasOne(OrganizationPayerAssignment::className(), ['organization_id' => 'id']);
- }
- /**
- * @return \yii\db\ActiveQuery
- */
- public function getOrganizationOperatorAssignment()
- {
- return $this->hasOne(OrganizationOperatorAssignment::className(), ['organization_id' => 'id']);
- }
- /**
- * @return \yii\db\ActiveQuery
- */
- public function getAdditionalProviderType()
- {
- return $this->hasOne(AdditionalProviderType::class, ['id' => 'additional_provider_type_id']);
- }
- /**
- * @return \yii\db\ActiveQuery
- */
- public function getSuborderPayer()
- {
- return $this->hasOne(Payers::className(), ['id' => 'payer_id'])->viaTable('organization_payer_assignment', ['organization_id' => 'id']);
- }
- public function hasEmptyInfo()
- {
- if (((empty($this->contractSettings->organization_first_ending) || empty($this->contractSettings->organization_second_ending) || empty($this->contractSettings->director_name_ending)) && $this->type != self::TYPE_IP_WITHOUT_WORKERS && $this->type != self::TYPE_IP_WITH_WORKERS) || (empty($this->contractSettings->organization_second_ending) && $this->type == self::TYPE_IP_WITHOUT_WORKERS) || (empty($this->contractSettings->organization_first_ending) && empty($this->contractSettings->organization_second_ending) && $this->type == self::TYPE_IP_WITH_WORKERS)) {
- return true;
- }
- return false;
- }
- /**
- * получить кол-во организаций со статусом активный
- *
- * @return int|string
- */
- public static function getActiveCount()
- {
- $query = static::find()
- ->joinWith(['municipality'])
- ->where([
- 'status' => self::STATUS_ACTIVE,
- '`mun`.operator_id' => Yii::$app->operator->identity->id,
- ]);
- return $query->count();
- }
- /**
- * получить список идентификаторов активных организаций
- *
- * @return array
- */
- public static function getActiveOrganizationIdList()
- {
- return self::find()->where(['status' => self::STATUS_ACTIVE])->column();
- }
- public static function types()
- {
- return [
- self::TYPE_EDUCATION => 'Образовательная организация',
- self::TYPE_TRAINING => 'Организация, осуществляющая обучение',
- self::TYPE_IP_WITH_WORKERS => 'Индивидуальный предприниматель, оказывающий услуги с наймом работников',
- self::TYPE_IP_WITHOUT_WORKERS => 'Индивидуальный предприниматель, оказывающий услуги без найма работников',
- ];
- }
- /**
- * @return int|string
- */
- public function getCertprogram()
- {
- $count = Programs::find()
- ->joinWith('programVerifications')
- ->where(['organization_id' => $this->id])
- ->andWhere(['program_verification.status' => ProgramVerificationStatus::DONE])
- ->count();
- return $count;
- }
- public function invoiceCount($data, $id)
- {
- $rows = (new \yii\db\Query())
- ->select(['id'])
- ->from('invoices')
- ->where(['organization_id' => $data])
- ->where(['payers_id' => $id])
- ->count();
- return $rows;
- }
- public static function findWithoutOperator($operatorId)
- {
- $query = static::find()
- ->leftJoin('organization_operator_assignment', 'organization.id = organization_operator_assignment.organization_id')
- ->where(['organization_operator_assignment.operator_id' => null]);
- return $query->all();
- }
- public function setNew()
- {
- $this->status = self::STATUS_NEW;
- }
- public function setActive()
- {
- $this->status = self::STATUS_ACTIVE;
- $this->accepted_date = time();
- }
- /**
- * организация со статусом новая
- *
- * @return bool
- */
- public function isNew()
- {
- return self::STATUS_NEW == $this->status;
- }
- /**
- * активна ли организация
- *
- * @return bool
- */
- public function isActive()
- {
- return self::STATUS_ACTIVE == $this->status;
- }
- /**
- * заблокирована ли организация
- *
- * @return bool
- */
- public function isBanned()
- {
- return self::STATUS_BANNED == $this->status;
- }
- public function setRefused()
- {
- $this->status = self::STATUS_REFUSED;
- }
- /** @return bool */
- public function existsFreePlace()
- {
- return $this->max_child > $this->getActiveContracts()->count();
- }
- public function sendRequestEmail()
- {
- $mail = Yii::$app->mailer
- ->compose(
- ['html' => 'organizationRequestNew-html', 'text' => 'organizationRequestNew-text'],
- ['model' => $this]
- )
- ->setTo($this->email)
- ->setFrom([Yii::$app->params['sendEmail'] => 'PFDO'])
- ->setSubject('Заявка на включение в реестр поставщиков зарегистрирована');
- if ($mail->send()) {
- return true;
- }
- return false;
- }
- public function sendModerateEmail($password = null)
- {
- $mail = Yii::$app->mailer
- ->compose(
- ['html' => $this->isRefused ? 'organizationRequestRefused-html' : 'organizationRequestAccepted-html', 'text' => $this->isRefused ? 'organizationRequestRefused-text' : 'organizationRequestAccepted-text'],
- [
- 'model' => $this,
- 'password' => $password,
- ]
- )
- ->setTo($this->email)
- ->setFrom([Yii::$app->params['sendEmail'] => 'PFDO'])
- ->setSubject($this->isRefused ? 'Заявка на включение в реестр поставщиков отклонена' : 'Заявка на включение в реестр поставщиков одобрена');
- try {
- if ($mail->send()) {
- return true;
- }
- } catch (\Exception $e) {
- return false;
- }
- return false;
- }
- public function getIsModerating()
- {
- return $this->scenario == self::SCENARIO_MODERATOR ? true : false;
- }
- public function getRequestCanBeUpdated()
- {
- return $this->scenario != self::SCENARIO_GUEST || $this->status == self::STATUS_REFUSED;
- }
- public function getIsRefused()
- {
- return $this->status == self::STATUS_REFUSED;
- }
- public static function docTypes()
- {
- return [
- self::DOC_TYPE_PROXY => 'доверенности',
- self::DOC_TYPE_CHARTER => 'Устава'
- ];
- }
- /**
- * существуют ли программы для автопролонгации у организации
- *
- * @return boolean
- */
- public function programsForAutoProlongationExists()
- {
- $autoProlongation = AutoProlongation::make($this->id);
- return $autoProlongation->getProgramIdList() ? true : false;
- }
- /**
- * может ли организация зарегистрировать автопролонгированный договор
- *
- * @param $contractId
- *
- * @return bool
- */
- public function canRegisterAutoProlongedContract($contractId)
- {
- if (!$contract = Contracts::findOne($contractId)) {
- return false;
- }
- return $contract->start_edu_contract <= date('Y-m-d');
- }
- /**
- * получить номер договора, которого нет в БД
- *
- * @param $exceptContractNumberList - список номеров, которые необходимо исключить при генерации
- *
- * @return string
- */
- public function getContractNumber($exceptContractNumberList = [])
- {
- $contractNumber = 1;
- $existsContractNumberList = $this->getContracts()->select('contracts.number')->where(['not', ['contracts.number' => null]])->column();
- do {
- $number = (count($existsContractNumberList) + $contractNumber++) . ' - ПФ';
- } while (in_array($number, $existsContractNumberList) || in_array($number, $exceptContractNumberList));
- return $number;
- }
- /**
- * существуют активные контракты
- *
- * @return bool
- */
- public function activeContractsExists()
- {
- return $this->getContracts()->where(['contracts.status' => Contracts::STATUS_ACTIVE])->exists();
- }
- /**
- * посчитать рейтинг организации
- */
- public function countRating()
- {
- $programs = Programs::find()
- ->select(['id'])
- ->where(['organization_id' => $this->id])
- ->andWhere(['not', ['programs.status' => [ProgramStatus::IN_ARCHIVE, ProgramStatus::DRAFT]]])
- ->andWhere(['>', 'rating', 0])
- ->column();
- $count = 0;
- $count2 = 0;
- foreach ($programs as $program) {
- $model_program = Programs::findOne($program);
- $contractCount = $model_program->getContracts()->where([
- 'contracts.status' => [
- Contracts::STATUS_ACTIVE,
- Contracts::STATUS_CLOSED
- ]
- ])->count();
- $count += $model_program->rating * $contractCount;
- $count2 += $contractCount;
- }
- if ($count2 != 0) {
- $this->raiting = round($count / $count2);
- } else {
- $this->raiting = null;
- }
- }
- /**
- * разрешено ли организации просматривать программы, договоры по МЗ
- */
- public function canViewMunicipalTask()
- {
- return $this->directorySubordinationLevel && in_array($this->level_id, [DirectorySubordinationLevel::MUNICIPAL, DirectorySubordinationLevel::FEDERAL, DirectorySubordinationLevel::RF_SUBJECT]);
- }
- /**
- * разрешено ли организации просматривать подведомственные организации
- */
- public function canViewSuborders()
- {
- return $this->directorySubordinationLevel && $this->level_id == DirectorySubordinationLevel::MUNICIPAL;
- }
- /**
- * может ли организация сама выбрать реестр программ по МЗ при подаче заявки
- */
- public function canChooseMunicipalTaskRegistry()
- {
- return $this->directorySubordinationLevel && in_array($this->level_id, [DirectorySubordinationLevel::RF_SUBJECT, DirectorySubordinationLevel::FEDERAL]);
- }
- /**
- * может ли организация создавать программы по МЗ
- */
- public function canCreateMunicipalTaskProgram()
- {
- return in_array($this->level_id, [DirectorySubordinationLevel::RF_SUBJECT, DirectorySubordinationLevel::FEDERAL]) || (DirectorySubordinationLevel::MUNICIPAL == $this->level_id && $this->getSuborderPayer()->exists());
- }
- /**
- * Возвращает js функцию для клиентской валидации, является ли поле additional_provider_type_id обязательным
- *
- * @return string
- */
- public static function getIsAdditionalTypeRequiredClient()
- {
- $type = self::ORGANIZATION_TYPE_EDUCATIONAL;
- return "function (attribute, value) { return $('#organization-type').val() === '{$type}'; }";
- }
- /**
- * Список типов организаций для поля select
- *
- * @return array
- */
- public static function organizationTypeList()
- {
- return [
- self::ORGANIZATION_TYPE_EDUCATIONAL => 'Образовательная организация',
- self::ORGANIZATION_TYPE_TRAINING => 'Организация, осуществляющая обучение',
- self::ORGANIZATION_TYPE_IE_WITH_EMPLOYEES => 'Индивидуальный предприниматель, оказывающий услуги с наймом работников',
- self::ORGANIZATION_TYPE_IE_WITHOUT_EMPLOYEES => 'Индивидуальный предприниматель, оказывающий услуги без найма работников'
- ];
- }
- /**
- * @inheritdoc
- */
- public function afterValidate()
- {
- parent::afterValidate();
- // Принудительно сбрасываем значение additional_provider_type_id если тип не "Образовательная организация"
- if ($this->type != self::ORGANIZATION_TYPE_EDUCATIONAL) {
- $this->additional_provider_type_id = null;
- }
- }
- /**
- * @inheritdoc
- */
- public function attributeHints()
- {
- return array_merge(parent::attributeHints(), [
- 'additional_provider_type_id' => 'Заполняется если тип поставщика "' . ArrayHelper::getValue(self::organizationTypeList(),
- self::ORGANIZATION_TYPE_EDUCATIONAL) . '"'
- ]);
- }
- /**
- * получить список программ указанного реестра в которые можно записаться
- *
- * @param $fund_type - тип фонда программы
- *
- * @see ProgramFundType
- *
- * @return Programs[]|null[]
- */
- public function getAvailableProgramsByFundType($fund_type)
- {
- return $this->getPrograms()
- ->joinWith(['programVerifications'])
- ->where(['program_verification.status' => ProgramVerificationStatus::DONE])
- ->andWhere(['program_verification.fund_type' => $fund_type])
- ->all();
- }
- }
Add Comment
Please, Sign In to add comment