Guest User

Untitled

a guest
May 29th, 2018
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 46.31 KB | None | 0 0
  1. <?php
  2.  
  3. namespace app\models;
  4.  
  5. use app\behaviors\UploadBehavior;
  6. use app\components\validators\OgrnValidator;
  7. use app\helpers\ArrayHelper;
  8. use app\models\directorySubordinationLevel\DirectorySubordinationLevel;
  9. use app\models\programs\ProgramFundType;
  10. use app\models\programs\ProgramStatus;
  11. use app\models\programs\ProgramVerificationStatus;
  12. use app\models\search\ProgramsSearch;
  13. use app\modules\municipalTask\models\MunicipalTaskContract;
  14. use Yii;
  15. use app\components\validators\InnValidator;
  16. use app\components\validators\BikValidator;
  17. use app\components\validators\RassValidator;
  18. use app\helpers\PhoneHelper;
  19. use yii\db\ActiveRecord;
  20.  
  21. /**
  22. * This is the model class for table "organization".
  23. *
  24. * @property integer $id
  25. * @property integer $status
  26. * @property integer $user_id
  27. * @property integer $type
  28. * @property string $name
  29. * @property string $license_date
  30. * @property integer $license_number
  31. * @property string $license_issued
  32. * @property string $bank_name
  33. * @property integer $bank_bik
  34. * @property string $bank_sity
  35. * @property integer $korr_invoice
  36. * @property int $correspondent_invoice
  37. * @property integer $mun
  38. * @property string $rass_invoice
  39. * @property string $fio
  40. * @property string $position
  41. * @property integer $doc_type
  42. * @property string $date_proxy
  43. * @property string $address_legal
  44. * @property string $address_actual
  45. * @property string $geocode
  46. * @property integer $max_child
  47. * @property integer $amount_child
  48. * @property integer $inn
  49. * @property integer $KPP
  50. * @property integer $OGRN
  51. * @property integer $okpo
  52. * @property string $raiting
  53. * @property string $ground
  54. * @property string $about
  55. * @property string $fio_contact
  56. * @property string $email
  57. * @property string $full_name
  58. * @property string $number_proxy
  59. * @property string $license_issued_dat
  60. * @property string $refuse_reason
  61. * @property integer $contracts_count
  62. * @property string $cratedate
  63. * @property string $anonymous_update_token
  64. * @property integer $departament_id
  65. * @property integer $level_id
  66. * @property string $svidet
  67. * @property string $position_min
  68. * @property int $last
  69. * @property int $last_year_contract
  70. * @property string $site
  71. * @property string $phone
  72. * @property string $extra_phone
  73. * @property int $organizational_form
  74. * @property int $accepted_date
  75. * @property int $certificate_accounting_limit
  76. * @property string $receiver
  77. * @property string $director_name
  78. * @property int $additional_provider_type_id
  79. *
  80. * @property Contracts[] $contracts
  81. * @property Cooperate[] $cooperates
  82. * @property Invoices[] $invoices
  83. * @property Payers $payer
  84. * @property User $user
  85. * @property mixed $certprogram
  86. * @property \yii\db\ActiveQuery $statement
  87. * @property string $statusName
  88. * @property bool $isModerating
  89. * @property \yii\db\ActiveQuery $children
  90. * @property \yii\db\ActiveQuery $operators
  91. * @property \yii\db\ActiveQuery $license
  92. * @property Operators $operator
  93. * @property string $userName
  94. * @property \yii\db\ActiveQuery $groups
  95. * @property Mun $municipality
  96. * @property \yii\db\ActiveQuery $charter
  97. * @property \yii\db\ActiveQuery $documents
  98. * @property bool $requestCanBeUpdated
  99. * @property bool $isRefused
  100. * @property \yii\db\ActiveQuery $favorites
  101. * @property Programs[] $programs
  102. * @property OrganizationAddress[] $addresses
  103. * @property OrganizationContractSettings $contractSettings
  104. * @property string $contractNumber
  105. * @property DirectoryDepartment $directoryDepartament
  106. * @property DirectorySubordinationLevel $directorySubordinationLevel
  107. * @property Payers $suborderPayer
  108. * @property OrganizationPayerAssignment $organizationPayerAssignment
  109. * @property AdditionalProviderType $additionalProviderType
  110. */
  111. class Organization extends ActiveRecord
  112. {
  113. const SCENARIO_GUEST = 'guest';
  114. const SCENARIO_REFUSING = 'refusing';
  115. const SCENARIO_MODERATOR = 'moderator';
  116. const SCENARIO_PAYER = 'payer';
  117. const SCENARIO_ORGANIZATION = 'organization';
  118. const SCENARIO_REST_CREATE = 'scenario_rest_create';
  119. const SCENARIO_REST_UPDATE = 'scenario_rest_update';
  120.  
  121. const TYPE_EDUCATION = 1;
  122. const TYPE_TRAINING = 2;
  123. const TYPE_IP_WITH_WORKERS = 3;
  124. const TYPE_IP_WITHOUT_WORKERS = 4;
  125.  
  126. const DOC_TYPE_CHARTER = 2;
  127. const DOC_TYPE_PROXY = 1;
  128.  
  129. // Образовательная организация
  130. const ORGANIZATION_TYPE_EDUCATIONAL = 1;
  131.  
  132. // Организация, осуществляющая обучение
  133. const ORGANIZATION_TYPE_TRAINING = 2;
  134.  
  135. // Индивидуальный предприниматель, оказывающий услуги с наймом работников
  136. const ORGANIZATION_TYPE_IE_WITH_EMPLOYEES = 3;
  137.  
  138. // Индивидуальный предприниматель, оказывающий услуги без найма работников
  139. const ORGANIZATION_TYPE_IE_WITHOUT_EMPLOYEES = 4;
  140.  
  141. // Новая организация (не промодерированная)
  142. const STATUS_NEW = 10;
  143.  
  144. // Активная организация
  145. const STATUS_ACTIVE = 20;
  146.  
  147. // Отклоненная организация (можно редактировать заявителю)
  148. const STATUS_REFUSED = 30;
  149.  
  150. // Забаненная организация
  151. const STATUS_BANNED = 40;
  152.  
  153. // Организация без пользователя
  154. const STATUS_DELETED = 50;
  155.  
  156. public $cooperate;
  157.  
  158. // Лицензия (документ)
  159. public $licenseDocument;
  160.  
  161. // Устав
  162. public $charterDocument;
  163.  
  164. // Выписка
  165. public $statementDocument;
  166.  
  167. // Иные документы
  168. public $commonDocuments = [];
  169.  
  170. // Капча
  171. public $verifyCode;
  172.  
  173. /**
  174. * @inheritdoc
  175. */
  176. public static function tableName()
  177. {
  178. return 'organization';
  179. }
  180.  
  181. public function scenarios()
  182. {
  183. $scenarios = parent::scenarios();
  184. $scenarios[self::SCENARIO_MODERATOR] = $scenarios[self::SCENARIO_DEFAULT];
  185. $scenarios[self::SCENARIO_GUEST] = [
  186. 'charterDocument',
  187. 'statementDocument',
  188. 'name',
  189. 'full_name',
  190. 'organizational_form',
  191. 'type',
  192. 'license_date',
  193. 'license_number',
  194. 'license_issued',
  195. 'svidet',
  196. 'bank_name',
  197. 'bank_sity',
  198. 'bank_bik',
  199. 'korr_invoice',
  200. 'rass_invoice',
  201. 'phone',
  202. 'email',
  203. 'site',
  204. 'fio_contact',
  205. 'address_actual',
  206. 'address_legal',
  207. 'inn',
  208. 'KPP',
  209. 'OGRN',
  210. 'last',
  211. 'mun',
  212. 'licenseDocument',
  213. 'commonDocuments',
  214. 'anonymous_update_token',
  215. 'departament_id',
  216. 'level_id',
  217. 'verifyCode',
  218. 'additional_provider_type_id'
  219. ];
  220. $scenarios[self::SCENARIO_PAYER] = ['certificate_accounting_limit'];
  221. $scenarios[self::SCENARIO_ORGANIZATION] = [
  222. 'license_issued_dat',
  223. 'fio',
  224. 'position_min',
  225. 'position',
  226. 'doc_type',
  227. 'date_proxy',
  228. 'number_proxy',
  229. 'about'
  230. ];
  231. $scenarios[self::SCENARIO_REFUSING] = ['refuse_reason'];
  232. $scenarios[self::SCENARIO_REFUSING] = [];
  233. $scenarios[self::SCENARIO_REST_CREATE] = [
  234. 'type',
  235. 'name',
  236. 'full_name',
  237. 'license_date',
  238. 'license_number',
  239. 'license_issued',
  240. 'svidet',
  241. 'bank_name',
  242. 'bank_bik',
  243. 'bank_sity',
  244. 'korr_invoice',
  245. 'correspondent_invoice',
  246. 'rass_invoice',
  247. 'fio_contact',
  248. 'address_legal',
  249. 'address_actual',
  250. 'inn',
  251. 'KPP',
  252. 'OGRN',
  253. 'okpo',
  254. 'mun',
  255. 'email',
  256. 'site',
  257. 'phone',
  258. 'organizational_form',
  259. 'receiver',
  260. 'departament_id',
  261. 'level_id',
  262. 'director_name',
  263. 'additional_provider_type_id'
  264. ];
  265. $scenarios[self::SCENARIO_REST_UPDATE] = [
  266. 'type',
  267. 'name',
  268. 'full_name',
  269. 'license_date',
  270. 'license_number',
  271. 'license_issued',
  272. 'svidet',
  273. 'bank_name',
  274. 'bank_bik',
  275. 'bank_sity',
  276. 'korr_invoice',
  277. 'correspondent_invoice',
  278. 'rass_invoice',
  279. 'fio_contact',
  280. 'address_legal',
  281. 'address_actual',
  282. 'KPP',
  283. 'OGRN',
  284. 'okpo',
  285. 'mun',
  286. 'email',
  287. 'site',
  288. 'phone',
  289. 'organizational_form',
  290. 'receiver',
  291. 'departament_id',
  292. 'level_id',
  293. 'director_name',
  294. 'additional_provider_type_id'
  295. ];
  296.  
  297. return $scenarios;
  298. }
  299.  
  300. /**
  301. * @inheritdoc
  302. */
  303. public function rules()
  304. {
  305. return [
  306. [
  307. [
  308. 'name',
  309. 'bank_name',
  310. 'bank_bik',
  311. 'korr_invoice',
  312. 'rass_invoice',
  313. 'fio_contact',
  314. 'address_actual',
  315. 'email',
  316. 'full_name',
  317. 'type',
  318. 'phone',
  319. 'address_legal',
  320. 'mun',
  321. ],
  322. 'required',
  323. 'except' => [self::SCENARIO_REST_CREATE, self::SCENARIO_REST_UPDATE]
  324. ],
  325. [['inn', 'name', 'email', 'full_name'], 'required', 'on' => self::SCENARIO_REST_CREATE],
  326. [['inn'], 'unique', 'on' => self::SCENARIO_REST_CREATE],
  327. [['organizational_form', 'last', 'bank_sity', 'inn', 'OGRN'], 'required',
  328. 'except' => [self::SCENARIO_REST_CREATE, self::SCENARIO_REST_UPDATE]],
  329. [['svidet'], 'required', 'except' => [self::SCENARIO_REST_CREATE, self::SCENARIO_REST_UPDATE],
  330. 'when' => function($model) {
  331. return $model->type == self::TYPE_IP_WITH_WORKERS;
  332. },
  333. 'whenClient' => "function (attribute, value) {
  334. return $('#organization-type').val() == 3;
  335. }"],
  336. [['license_date', 'license_number', 'license_issued'], 'required', 'except' => [self::SCENARIO_REST_CREATE, self::SCENARIO_REST_UPDATE],
  337. 'when' => function($model) {
  338. return $model->type != self::TYPE_IP_WITHOUT_WORKERS;
  339. },
  340. 'whenClient' => "function (attribute, value) {
  341. return $('#organization-type').val() != 4;
  342. }"],
  343. [['user_id', 'type', 'doc_type', 'max_child', 'amount_child', 'mun', 'last', 'last_year_contract', 'certprogram', 'status', 'organizational_form', 'certificate_accounting_limit', 'contracts_count'], 'integer'],
  344. [['license_date', 'date_proxy', 'cratedate', 'accepted_date'], 'safe'],
  345. [['raiting'], 'number'],
  346. [['about', 'site', 'refuse_reason', 'anonymous_update_token', 'receiver', 'korr_invoice', 'extra_phone', 'site'], 'string'],
  347. ['correspondent_invoice', 'integer', 'integerPattern' => '/^[0-9]{20}$/', 'message' => 'Значение должно состоять из 20 цифр'],
  348. [['email', 'fio', 'bank_sity'], 'string', 'max' => 100],
  349. [['email'], 'email'],
  350. [['name', 'license_number', 'license_issued', 'license_issued_dat', 'address_legal', 'address_actual', 'geocode', 'full_name', 'director_name'], 'string', 'max' => 255],
  351. [[ 'KPP', 'bank_bik'], 'string', 'min' => 9, 'max' => 9],
  352. [['fio_contact', 'position', 'position_min'], 'string', 'max' => 200],
  353. [['bank_name',], 'string', 'max' => 150],
  354. [['ground', 'number_proxy'], 'string', 'max' => 45],
  355. [['rass_invoice'], 'string', 'max' => 20],
  356. [['okpo'], 'string', 'min' => 8, 'max' => 10],
  357. ['rass_invoice', RassValidator::className()],
  358. [['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'id']],
  359. [
  360. ['licenseDocument', 'charterDocument', 'statementDocument', 'commonDocuments'],
  361. 'safe', 'on' => self::SCENARIO_GUEST
  362. ],
  363. ['verifyCode', 'captcha', 'on' => self::SCENARIO_GUEST],
  364. ['verifyCode', 'required', 'on' => self::SCENARIO_GUEST],
  365. [['inn'], 'string', 'min' => 10, 'max' => 12],
  366. [
  367. ['inn', 'bank_bik', 'rass_invoice', 'OGRN', 'okpo',],
  368. 'match',
  369. 'pattern' => '/^\s*[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?\s*$/',
  370. 'message' => 'Только цифры'
  371. ],
  372. [['inn', 'rass_invoice', 'bank_bik'], 'trim'],
  373. ['inn', InnValidator::className()],
  374. ['bank_bik', BikValidator::className()],
  375. [['OGRN'], 'string', 'min' => 13, 'max' => 15],
  376. ['OGRN', OgrnValidator::className()],
  377. [['departament_id'], 'exist', 'targetClass' => DirectoryDepartment::className(), 'targetAttribute' => 'id'],
  378. [['level_id'], 'exist', 'targetClass' => DirectorySubordinationLevel::className(), 'targetAttribute' => 'id'],
  379. [['additional_provider_type_id'],
  380. 'required',
  381. 'whenClient' => self::getIsAdditionalTypeRequiredClient(),
  382. 'when' => function(Organization $model) {
  383. return intval($model->type) === self::ORGANIZATION_TYPE_EDUCATIONAL;
  384. }],
  385. [['additional_provider_type_id'], 'exist', 'targetClass' => AdditionalProviderType::class, 'targetAttribute' => 'id'],
  386. ];
  387. }
  388.  
  389. /**
  390. * @inheritdoc
  391. */
  392. public function attributeLabels()
  393. {
  394. return [
  395. 'id' => 'ID',
  396. 'user_id' => 'User ID',
  397. 'status' => 'Статус',
  398. 'organizational_form' => 'Организационно-правовая форма',
  399. 'type' => 'Тип поставщика',
  400. 'typeLabel' => 'Тип поставщика',
  401. 'name' => 'Сокращенное наименование поставщика',
  402. 'full_name' => 'Полное наименование поставщика',
  403. 'license_date' => 'Лицензия от',
  404. 'license_number' => 'Номер лицензии',
  405. 'license_issued' => 'Кем выдана лицензия',
  406. 'license_issued_dat' => 'Кем выдана лицензия (в дательном падеже)',
  407. 'svidet' => 'Cвидетельство о государственной регистрации',
  408. 'bank_name' => 'Наименование банка',
  409. 'bank_bik' => 'БИК Банка',
  410. 'bank_sity' => 'Город банка',
  411. 'korr_invoice' => 'Лицевой счёт (л/с)',
  412. 'correspondent_invoice' => 'Корреспондентский счёт (к/с)',
  413. 'rass_invoice' => 'Расчетный счет',
  414. 'fio_contact' => 'Контактное лицо',
  415. 'fio' => 'ФИО представителя поставщика',
  416. 'position' => 'Должность представителя поставщика',
  417. 'position_min' => 'Должность представителя поставщика (кратко)',
  418. 'doc_type' => 'Действующего на основании',
  419. 'date_proxy' => 'Дата доверенности',
  420. 'number_proxy' => 'Номер доверенности',
  421. 'address_legal' => 'Юридический адрес',
  422. 'address_actual' => 'Фактический адрес',
  423. 'geocode' => 'Геокод',
  424. 'max_child' => 'Лимит обучения',
  425. 'amount_child' => 'Число договоров',
  426. 'last_year_contract' => 'Число обучающихся за прошлый год',
  427. 'inn' => 'ИНН',
  428. 'KPP' => 'КПП',
  429. 'OGRN' => 'ОГРН',
  430. 'okpo' => 'ОКПО',
  431. 'raiting' => 'Рейтинг',
  432. 'ground' => 'Тип местности в котором расположена поставщик',
  433. 'username' => 'Логин',
  434. 'about' => 'Почему выбирают нас',
  435. 'mun' => 'Муниципальный район',
  436. 'last' => 'Количество обучающихся в прошлом учебном году (если ребенок обучался на нескольких программах, считаем его несколько раз)',
  437. 'cratedate' => 'Дата добавления поставщика',
  438. 'email' => 'E-mail',
  439. 'site' => 'Сайт',
  440. 'phone' => 'Телефон',
  441. 'extra_phone' => 'Комментарии к телефону',
  442. 'refuse_reason' => 'Причина отказа',
  443. 'certprogram' => 'Число программ',
  444. 'licenseDocument' => 'Лицензия',
  445. 'charterDocument' => 'Устав',
  446. 'statementDocument' => 'Выписка из ЕГРЮЛ/ЕГРИП',
  447. 'commonDocuments' => 'Иные документы (не более трёх)',
  448. 'verifyCode' => 'Проверочный код',
  449. 'children' => 'Число обучающихся',
  450. 'programs' => 'Количество программ',
  451. 'certificate_accounting_limit' => 'Лимит зачисления',
  452. 'receiver' => 'Получатель (необязательно)',
  453. 'departament_id' => 'Ведомственная принадлежность',
  454. 'level_id' => 'Уровень подчиненности',
  455. 'director_name' => 'Руководитель',
  456. 'additional_provider_type_id' => 'Тип образовательной организации',
  457. ];
  458. }
  459.  
  460. /**
  461. * @return array
  462. */
  463. /*
  464. public function behaviors()
  465. {
  466. $defaultAttributes = [
  467. 'class' => UploadBehavior::class,
  468. 'multiple' => true,
  469. 'pathAttribute' => 'path',
  470. 'baseUrlAttribute' => 'base_url',
  471. 'nameAttribute' => 'filename',
  472. 'documentType' => 'type',
  473. ];
  474. return [
  475. array_merge($defaultAttributes, [
  476. 'attribute' => 'licenseDocument',
  477. 'uploadRelation' => 'license',
  478. ]),
  479. array_merge($defaultAttributes, [
  480. 'attribute' => 'charterDocument',
  481. 'uploadRelation' => 'charter',
  482. ]),
  483. array_merge($defaultAttributes, [
  484. 'attribute' => 'statementDocument',
  485. 'uploadRelation' => 'statement',
  486. ]),
  487. array_merge($defaultAttributes, [
  488. 'attribute' => 'commonDocuments',
  489. 'uploadRelation' => 'documents',
  490. ]),
  491. ];
  492. }
  493. */
  494.  
  495. /**
  496. * @inheritdoc
  497. */
  498. public function beforeValidate()
  499. {
  500. if (!empty($this->commonDocuments) && is_array($this->commonDocuments)) {
  501. foreach ($this->commonDocuments as $key => $document) {
  502. $this->commonDocuments[$key]['document_type'] = OrganizationDocument::TYPE_COMMON;
  503. }
  504. }
  505. if (!empty($this->licenseDocument) && is_array($this->licenseDocument)) {
  506. $this->licenseDocument[0]['document_type'] = OrganizationDocument::TYPE_LICENSE;
  507. }
  508. if (!empty($this->charterDocument) && is_array($this->charterDocument)) {
  509. $this->charterDocument[0]['document_type'] = OrganizationDocument::TYPE_CHARTER;
  510. }
  511. if (!empty($this->statementDocument) && is_array($this->statementDocument)) {
  512. $this->statementDocument[0]['document_type'] = OrganizationDocument::TYPE_STATEMENT;
  513. }
  514.  
  515. if ($this->correspondent_invoice == '') {
  516. $this->correspondent_invoice = null;
  517. }
  518.  
  519. return parent::beforeValidate();
  520. }
  521.  
  522. /**
  523. * @param bool $insert
  524. * @return bool
  525. */
  526. public function beforeSave($insert)
  527. {
  528. if(parent::beforeSave($insert)){
  529. $this->phone = PhoneHelper::cleanPhone($this->phone);
  530. return true;
  531. }
  532. return false;
  533. }
  534.  
  535. /**
  536. * @return \yii\db\ActiveQuery
  537. */
  538. public function getContractSettings()
  539. {
  540. return $this->hasOne(OrganizationContractSettings::class, ['organization_id' => 'id']);
  541. }
  542.  
  543. /**
  544. * @return \yii\db\ActiveQuery
  545. */
  546. public function getDirectoryDepartament()
  547. {
  548. return $this->hasOne(DirectoryDepartment::className(), ['id' => 'departament_id']);
  549. }
  550.  
  551. /**
  552. * @return \yii\db\ActiveQuery
  553. */
  554. public function getDirectorySubordinationLevel()
  555. {
  556. return $this->hasOne(DirectorySubordinationLevel::className(), ['id' => 'level_id']);
  557. }
  558.  
  559. /**
  560. * @return \yii\db\ActiveQuery
  561. */
  562. public function getAddresses()
  563. {
  564. return $this->hasMany(OrganizationAddress::class, ['organization_id' => 'id']);
  565. }
  566.  
  567. /**
  568. * @return \yii\db\ActiveQuery
  569. */
  570. public function getLicense()
  571. {
  572. return $this->hasMany(OrganizationDocument::class, ['organization_id' => 'id'])
  573. ->andWhere(['type' => OrganizationDocument::TYPE_LICENSE]);
  574. }
  575.  
  576. /**
  577. * @return \yii\db\ActiveQuery
  578. */
  579. public function getChildren()
  580. {
  581. return $this->hasMany(Contracts::class, ['organization_id' => 'id']);
  582. }
  583.  
  584. /**
  585. * @return \yii\db\ActiveQuery
  586. */
  587. public function getMunicipalContracts()
  588. {
  589. return $this->hasMany(MunicipalTaskContract::class, ['organization_id' => 'id']);
  590. }
  591.  
  592. /**
  593. * @return \yii\db\ActiveQuery
  594. */
  595. public function getCharter()
  596. {
  597. return $this->hasMany(OrganizationDocument::class, ['organization_id' => 'id'])
  598. ->andWhere(['type' => OrganizationDocument::TYPE_CHARTER]);
  599. }
  600.  
  601. /**
  602. * @return \yii\db\ActiveQuery
  603. */
  604. public function getStatement()
  605. {
  606. return $this->hasMany(OrganizationDocument::className(), ['organization_id' => 'id'])
  607. ->andWhere(['type' => OrganizationDocument::TYPE_STATEMENT]);
  608. }
  609.  
  610. /**
  611. * @return \yii\db\ActiveQuery
  612. */
  613. public function getDocuments()
  614. {
  615. return $this->hasMany(OrganizationDocument::className(), ['organization_id' => 'id'])
  616. ->andWhere(['type' => OrganizationDocument::TYPE_COMMON]);
  617. }
  618.  
  619. /**
  620. * получить общее кол-во программ-черновиков
  621. *
  622. * @return integer
  623. */
  624. public function getDraftProgramsCount()
  625. {
  626. return $this->getPrograms()->where(['programs.status' => ProgramStatus::DRAFT])->count();
  627. }
  628.  
  629. /**
  630. * получить общее кол-во программ
  631. *
  632. * @return integer
  633. */
  634. public function getAllProgramsCount()
  635. {
  636. $searchCertificatedPrograms = new ProgramsSearch([
  637. 'organization_id' => $this->id,
  638. 'verificationStatus' => ProgramVerificationStatus::DONE,
  639. ]);
  640. $certificatedProgramsProvider = $searchCertificatedPrograms->search(Yii::$app->request->queryParams);
  641.  
  642. return $certificatedProgramsProvider->totalCount;
  643. }
  644.  
  645. /**
  646. * получить общее кол-во сертифицированных программ
  647. *
  648. * @return integer
  649. */
  650. public function getCertificatedProgramsCount()
  651. {
  652. $searchCertificatedPrograms = new ProgramsSearch([
  653. 'organization_id' => $this->id,
  654. 'status' => ProgramStatus::ACTIVE,
  655. 'verificationStatus' => [ProgramVerificationStatus::DONE, ProgramVerificationStatus::UNDEFINED, ProgramVerificationStatus::WAIT, ProgramVerificationStatus::DENIED],
  656. ]);
  657. $certificatedProgramsProvider = $searchCertificatedPrograms->search(Yii::$app->request->queryParams);
  658.  
  659. return $certificatedProgramsProvider->totalCount;
  660. }
  661.  
  662. /**
  663. * получить общее кол-во программ по МЗ
  664. */
  665. public function getMunicipalTaskProgramsCount()
  666. {
  667. $searchMunicipalTaskPrograms = new ProgramsSearch([
  668. 'organization_id' => $this->id,
  669. 'fundType' => ProgramFundType::MUNICIPAL_TASK,
  670. 'verificationStatus' => [ProgramVerificationStatus::UNDEFINED, ProgramVerificationStatus::WAIT, ProgramVerificationStatus::DONE, ProgramVerificationStatus::DENIED],
  671. ]);
  672. $municipalTaskProgramsProvider = $searchMunicipalTaskPrograms->search(Yii::$app->request->queryParams);
  673.  
  674. return $municipalTaskProgramsProvider->totalCount;
  675. }
  676.  
  677. /**
  678. * получить общее кол-во архивных программ
  679. */
  680. public function getArchiveProgramsCount()
  681. {
  682. $searchArchivePrograms = new ProgramsSearch([
  683. 'organization_id' => $this->id,
  684. 'status' => [ProgramStatus::IN_ARCHIVE],
  685. ]);
  686. $archiveProgramsProvider = $searchArchivePrograms->search(Yii::$app->request->queryParams);
  687.  
  688. return $archiveProgramsProvider->totalCount;
  689. }
  690.  
  691. /**
  692. * получить кол-во обучающихся
  693. *
  694. * @param null $payerId - идентификатор плательщика
  695. *
  696. * @return int
  697. */
  698. public function getChildrenCount($payerId = null)
  699. {
  700. return $this->getChildren()
  701. ->select('certificates.id')
  702. ->distinct()
  703. ->leftJoin(Certificates::tableName(), 'certificates.id = contracts.certificate_id')
  704. ->andWhere(['contracts.status' => Contracts::STATUS_ACTIVE])
  705. ->andFilterWhere(['contracts.payer_id' => $payerId])
  706. ->count();
  707. }
  708.  
  709. public function getChildrenCountMunicipalTask($payerId = null)
  710. {
  711. return $this->getMunicipalContracts()
  712. ->select('certificates.id')
  713. ->distinct()
  714. ->leftJoin(Certificates::tableName(), 'certificates.id = municipal_task_contract.certificate_id')
  715. ->andWhere(['municipal_task_contract.status' => MunicipalTaskContract::STATUS_ACTIVE])
  716. ->andFilterWhere(['municipal_task_contract.payer_id' => $payerId])
  717. ->count();
  718. }
  719.  
  720. /**
  721. * получить кол-во договоров
  722. *
  723. * @param null $payerId - идентификатор плательщика
  724. *
  725. * @return integer
  726. */
  727. public function getContractsCount($payerId = null)
  728. {
  729. return $this->getChildren()
  730. ->andWhere(['contracts.status' => 1])
  731. ->andFilterWhere(['contracts.payer_id' => $payerId])
  732. ->count();
  733. }
  734.  
  735. public function getStatusName()
  736. {
  737. $title = '';
  738. switch ($this->status) {
  739. case self::STATUS_ACTIVE:
  740. $title = 'Ваша заявка на включение в реестр поставщиков образовательных услуг одобрена, организация внесена в Реестр, и Вы уже даже должны были получить на указанную Вами при формировании заявки электронную почту логин и пароль для входа в личный кабинет. Если логин и пароль Вами не получен – посмотрите в папке «спам» почты, если и там нет письма – обратитесь к оператору.';
  741. break;
  742. case self::STATUS_NEW:
  743. $title = 'Ваша заявка на включение в реестр поставщиков образовательных услуг пока проходит рассмотрение оператором персонифицированного финансирования. Вы получите уведомление о результатах рассмотрения заявки на электронную почту, указанную для организации.';
  744. break;
  745. case self::STATUS_REFUSED:
  746. $title = 'Отказано. Вы можете исправить информацию и отправить заявку повторно.';
  747. break;
  748. case self::STATUS_BANNED:
  749. $title = 'Забанена.';
  750. break;
  751. }
  752.  
  753. return $title;
  754. }
  755.  
  756. /**
  757. * @param $status
  758. * @param $period
  759. *
  760. * @return Cooperate
  761. */
  762. public function getCooperation($status = null, $period = null)
  763. {
  764. return $this->hasOne(Cooperate::class, ['organization_id' => 'id'])
  765. ->andWhere(['cooperate.payer_id' => Yii::$app->user->getIdentity()->payer->id])
  766. ->andFilterWhere(['cooperate.status' => $status])
  767. ->andFilterWhere(['cooperate.period' => $period])
  768. ->one();
  769. }
  770.  
  771. /**
  772. * @return \yii\db\ActiveQuery
  773. */
  774. public function getContracts()
  775. {
  776. return $this->hasMany(Contracts::className(), ['organization_id' => 'id'])->inverseOf('organization');
  777. }
  778.  
  779. public function getActiveContracts()
  780. {
  781. return $this->getContracts()->where([Contracts::tableName() . '.status' => [
  782. Contracts::STATUS_REQUESTED,
  783. Contracts::STATUS_ACTIVE,
  784. Contracts::STATUS_ACCEPTED
  785. ]]);
  786. }
  787.  
  788. /**
  789. * @return \yii\db\ActiveQuery
  790. */
  791. public function getCooperates()
  792. {
  793. return $this->hasMany(Cooperate::className(), ['organization_id' => 'id'])->inverseOf('organization');
  794. }
  795.  
  796. public function getCooperatesByPayerId($payerId, $status = null)
  797. {
  798. return array_filter($this->cooperates, function ($val) use ($payerId, $status)
  799. {
  800. /** @var $val Cooperate */
  801. return (is_null($status) || $val->status === $status) && $val->payer_id === $payerId;
  802. });
  803. }
  804.  
  805. /**
  806. * @return \yii\db\ActiveQuery
  807. */
  808. public function getFavorites()
  809. {
  810. return $this->hasMany(Favorites::className(), ['organization_id' => 'id']);
  811. }
  812.  
  813. /**
  814. * @return \yii\db\ActiveQuery
  815. */
  816. public function getGroups()
  817. {
  818. return $this->hasMany(Groups::className(), ['organization_id' => 'id']);
  819. }
  820.  
  821. /**
  822. * @return \yii\db\ActiveQuery
  823. */
  824. public function getInvoices()
  825. {
  826. return $this->hasMany(Invoices::className(), ['organization_id' => 'id']);
  827. }
  828.  
  829. /**
  830. * @return \yii\db\ActiveQuery
  831. */
  832. public function getUser()
  833. {
  834. return $this->hasOne(User::className(), ['id' => 'user_id']);
  835. }
  836.  
  837. /**
  838. * @return \yii\db\ActiveQuery
  839. */
  840. public function getMunicipality()
  841. {
  842. return $this->hasOne(Mun::className(), ['id' => 'mun'])->inverseOf('organization');
  843. }
  844.  
  845. /**
  846. * @return string
  847. */
  848. public function getUserName()
  849. {
  850. return $this->user->username;
  851. }
  852.  
  853. /**
  854. * @return \yii\db\ActiveQuery
  855. */
  856. public function getPrograms()
  857. {
  858. return $this->hasMany(Programs::class, ['organization_id' => 'id']);
  859. }
  860.  
  861. /**
  862. * @return \yii\db\ActiveQuery
  863. */
  864. public function getOperators()
  865. {
  866. return $this->hasMany(Operators::className(), ['id' => 'operator_id'])
  867. ->viaTable('organization_operator_assignment', ['organization_id' => 'id']);
  868. }
  869.  
  870. /**
  871. * @return \yii\db\ActiveQuery
  872. */
  873. public function getOperator()
  874. {
  875. return $this->hasOne(Operators::className(), ['id' => 'operator_id'])
  876. ->viaTable('organization_operator_assignment', ['organization_id' => 'id']);
  877. }
  878.  
  879. /**
  880. * @return \yii\db\ActiveQuery
  881. */
  882. public function getOrganizationPayerAssignment()
  883. {
  884. return $this->hasOne(OrganizationPayerAssignment::className(), ['organization_id' => 'id']);
  885. }
  886.  
  887. /**
  888. * @return \yii\db\ActiveQuery
  889. */
  890. public function getOrganizationOperatorAssignment()
  891. {
  892. return $this->hasOne(OrganizationOperatorAssignment::className(), ['organization_id' => 'id']);
  893. }
  894.  
  895. /**
  896. * @return \yii\db\ActiveQuery
  897. */
  898. public function getAdditionalProviderType()
  899. {
  900. return $this->hasOne(AdditionalProviderType::class, ['id' => 'additional_provider_type_id']);
  901. }
  902.  
  903. /**
  904. * @return \yii\db\ActiveQuery
  905. */
  906. public function getSuborderPayer()
  907. {
  908. return $this->hasOne(Payers::className(), ['id' => 'payer_id'])->viaTable('organization_payer_assignment', ['organization_id' => 'id']);
  909. }
  910.  
  911. public function hasEmptyInfo()
  912. {
  913. 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)) {
  914. return true;
  915. }
  916.  
  917. return false;
  918. }
  919.  
  920. /**
  921. * получить кол-во организаций со статусом активный
  922. *
  923. * @return int|string
  924. */
  925. public static function getActiveCount()
  926. {
  927. $query = static::find()
  928. ->joinWith(['municipality'])
  929. ->where([
  930. 'status' => self::STATUS_ACTIVE,
  931. '`mun`.operator_id' => Yii::$app->operator->identity->id,
  932. ]);
  933.  
  934. return $query->count();
  935. }
  936.  
  937. /**
  938. * получить список идентификаторов активных организаций
  939. *
  940. * @return array
  941. */
  942. public static function getActiveOrganizationIdList()
  943. {
  944. return self::find()->where(['status' => self::STATUS_ACTIVE])->column();
  945. }
  946.  
  947. public static function types()
  948. {
  949. return [
  950. self::TYPE_EDUCATION => 'Образовательная организация',
  951. self::TYPE_TRAINING => 'Организация, осуществляющая обучение',
  952. self::TYPE_IP_WITH_WORKERS => 'Индивидуальный предприниматель, оказывающий услуги с наймом работников',
  953. self::TYPE_IP_WITHOUT_WORKERS => 'Индивидуальный предприниматель, оказывающий услуги без найма работников',
  954. ];
  955. }
  956.  
  957. /**
  958. * @return int|string
  959. */
  960. public function getCertprogram()
  961. {
  962. $count = Programs::find()
  963. ->joinWith('programVerifications')
  964. ->where(['organization_id' => $this->id])
  965. ->andWhere(['program_verification.status' => ProgramVerificationStatus::DONE])
  966. ->count();
  967.  
  968. return $count;
  969. }
  970.  
  971. public function invoiceCount($data, $id)
  972. {
  973. $rows = (new \yii\db\Query())
  974. ->select(['id'])
  975. ->from('invoices')
  976. ->where(['organization_id' => $data])
  977. ->where(['payers_id' => $id])
  978. ->count();
  979.  
  980. return $rows;
  981. }
  982.  
  983. public static function findWithoutOperator($operatorId)
  984. {
  985. $query = static::find()
  986. ->leftJoin('organization_operator_assignment', 'organization.id = organization_operator_assignment.organization_id')
  987. ->where(['organization_operator_assignment.operator_id' => null]);
  988.  
  989. return $query->all();
  990. }
  991.  
  992. public function setNew()
  993. {
  994. $this->status = self::STATUS_NEW;
  995. }
  996.  
  997. public function setActive()
  998. {
  999. $this->status = self::STATUS_ACTIVE;
  1000. $this->accepted_date = time();
  1001. }
  1002.  
  1003. /**
  1004. * организация со статусом новая
  1005. *
  1006. * @return bool
  1007. */
  1008. public function isNew()
  1009. {
  1010. return self::STATUS_NEW == $this->status;
  1011. }
  1012.  
  1013. /**
  1014. * активна ли организация
  1015. *
  1016. * @return bool
  1017. */
  1018. public function isActive()
  1019. {
  1020. return self::STATUS_ACTIVE == $this->status;
  1021. }
  1022.  
  1023. /**
  1024. * заблокирована ли организация
  1025. *
  1026. * @return bool
  1027. */
  1028. public function isBanned()
  1029. {
  1030. return self::STATUS_BANNED == $this->status;
  1031. }
  1032.  
  1033. public function setRefused()
  1034. {
  1035. $this->status = self::STATUS_REFUSED;
  1036. }
  1037.  
  1038. /** @return bool */
  1039. public function existsFreePlace()
  1040. {
  1041. return $this->max_child > $this->getActiveContracts()->count();
  1042. }
  1043.  
  1044. public function sendRequestEmail()
  1045. {
  1046. $mail = Yii::$app->mailer
  1047. ->compose(
  1048. ['html' => 'organizationRequestNew-html', 'text' => 'organizationRequestNew-text'],
  1049. ['model' => $this]
  1050. )
  1051. ->setTo($this->email)
  1052. ->setFrom([Yii::$app->params['sendEmail'] => 'PFDO'])
  1053. ->setSubject('Заявка на включение в реестр поставщиков зарегистрирована');
  1054.  
  1055. if ($mail->send()) {
  1056. return true;
  1057. }
  1058.  
  1059. return false;
  1060. }
  1061.  
  1062. public function sendModerateEmail($password = null)
  1063. {
  1064. $mail = Yii::$app->mailer
  1065. ->compose(
  1066. ['html' => $this->isRefused ? 'organizationRequestRefused-html' : 'organizationRequestAccepted-html', 'text' => $this->isRefused ? 'organizationRequestRefused-text' : 'organizationRequestAccepted-text'],
  1067. [
  1068. 'model' => $this,
  1069. 'password' => $password,
  1070. ]
  1071. )
  1072. ->setTo($this->email)
  1073. ->setFrom([Yii::$app->params['sendEmail'] => 'PFDO'])
  1074. ->setSubject($this->isRefused ? 'Заявка на включение в реестр поставщиков отклонена' : 'Заявка на включение в реестр поставщиков одобрена');
  1075.  
  1076. try {
  1077. if ($mail->send()) {
  1078. return true;
  1079. }
  1080. } catch (\Exception $e) {
  1081. return false;
  1082. }
  1083.  
  1084. return false;
  1085. }
  1086.  
  1087. public function getIsModerating()
  1088. {
  1089. return $this->scenario == self::SCENARIO_MODERATOR ? true : false;
  1090. }
  1091.  
  1092. public function getRequestCanBeUpdated()
  1093. {
  1094. return $this->scenario != self::SCENARIO_GUEST || $this->status == self::STATUS_REFUSED;
  1095. }
  1096.  
  1097. public function getIsRefused()
  1098. {
  1099. return $this->status == self::STATUS_REFUSED;
  1100. }
  1101.  
  1102. public static function docTypes()
  1103. {
  1104. return [
  1105. self::DOC_TYPE_PROXY => 'доверенности',
  1106. self::DOC_TYPE_CHARTER => 'Устава'
  1107. ];
  1108. }
  1109.  
  1110. /**
  1111. * существуют ли программы для автопролонгации у организации
  1112. *
  1113. * @return boolean
  1114. */
  1115. public function programsForAutoProlongationExists()
  1116. {
  1117. $autoProlongation = AutoProlongation::make($this->id);
  1118.  
  1119. return $autoProlongation->getProgramIdList() ? true : false;
  1120. }
  1121.  
  1122. /**
  1123. * может ли организация зарегистрировать автопролонгированный договор
  1124. *
  1125. * @param $contractId
  1126. *
  1127. * @return bool
  1128. */
  1129. public function canRegisterAutoProlongedContract($contractId)
  1130. {
  1131. if (!$contract = Contracts::findOne($contractId)) {
  1132. return false;
  1133. }
  1134.  
  1135. return $contract->start_edu_contract <= date('Y-m-d');
  1136. }
  1137.  
  1138. /**
  1139. * получить номер договора, которого нет в БД
  1140. *
  1141. * @param $exceptContractNumberList - список номеров, которые необходимо исключить при генерации
  1142. *
  1143. * @return string
  1144. */
  1145. public function getContractNumber($exceptContractNumberList = [])
  1146. {
  1147. $contractNumber = 1;
  1148. $existsContractNumberList = $this->getContracts()->select('contracts.number')->where(['not', ['contracts.number' => null]])->column();
  1149.  
  1150. do {
  1151. $number = (count($existsContractNumberList) + $contractNumber++) . ' - ПФ';
  1152. } while (in_array($number, $existsContractNumberList) || in_array($number, $exceptContractNumberList));
  1153.  
  1154. return $number;
  1155. }
  1156.  
  1157. /**
  1158. * существуют активные контракты
  1159. *
  1160. * @return bool
  1161. */
  1162. public function activeContractsExists()
  1163. {
  1164. return $this->getContracts()->where(['contracts.status' => Contracts::STATUS_ACTIVE])->exists();
  1165. }
  1166.  
  1167. /**
  1168. * посчитать рейтинг организации
  1169. */
  1170. public function countRating()
  1171. {
  1172. $programs = Programs::find()
  1173. ->select(['id'])
  1174. ->where(['organization_id' => $this->id])
  1175. ->andWhere(['not', ['programs.status' => [ProgramStatus::IN_ARCHIVE, ProgramStatus::DRAFT]]])
  1176. ->andWhere(['>', 'rating', 0])
  1177. ->column();
  1178.  
  1179. $count = 0;
  1180. $count2 = 0;
  1181. foreach ($programs as $program) {
  1182. $model_program = Programs::findOne($program);
  1183.  
  1184. $contractCount = $model_program->getContracts()->where([
  1185. 'contracts.status' => [
  1186. Contracts::STATUS_ACTIVE,
  1187. Contracts::STATUS_CLOSED
  1188. ]
  1189. ])->count();
  1190.  
  1191. $count += $model_program->rating * $contractCount;
  1192. $count2 += $contractCount;
  1193. }
  1194.  
  1195. if ($count2 != 0) {
  1196. $this->raiting = round($count / $count2);
  1197. } else {
  1198. $this->raiting = null;
  1199. }
  1200. }
  1201.  
  1202. /**
  1203. * разрешено ли организации просматривать программы, договоры по МЗ
  1204. */
  1205. public function canViewMunicipalTask()
  1206. {
  1207. return $this->directorySubordinationLevel && in_array($this->level_id, [DirectorySubordinationLevel::MUNICIPAL, DirectorySubordinationLevel::FEDERAL, DirectorySubordinationLevel::RF_SUBJECT]);
  1208. }
  1209.  
  1210. /**
  1211. * разрешено ли организации просматривать подведомственные организации
  1212. */
  1213. public function canViewSuborders()
  1214. {
  1215. return $this->directorySubordinationLevel && $this->level_id == DirectorySubordinationLevel::MUNICIPAL;
  1216. }
  1217.  
  1218. /**
  1219. * может ли организация сама выбрать реестр программ по МЗ при подаче заявки
  1220. */
  1221. public function canChooseMunicipalTaskRegistry()
  1222. {
  1223. return $this->directorySubordinationLevel && in_array($this->level_id, [DirectorySubordinationLevel::RF_SUBJECT, DirectorySubordinationLevel::FEDERAL]);
  1224. }
  1225.  
  1226. /**
  1227. * может ли организация создавать программы по МЗ
  1228. */
  1229. public function canCreateMunicipalTaskProgram()
  1230. {
  1231. return in_array($this->level_id, [DirectorySubordinationLevel::RF_SUBJECT, DirectorySubordinationLevel::FEDERAL]) || (DirectorySubordinationLevel::MUNICIPAL == $this->level_id && $this->getSuborderPayer()->exists());
  1232. }
  1233.  
  1234. /**
  1235. * Возвращает js функцию для клиентской валидации, является ли поле additional_provider_type_id обязательным
  1236. *
  1237. * @return string
  1238. */
  1239. public static function getIsAdditionalTypeRequiredClient()
  1240. {
  1241. $type = self::ORGANIZATION_TYPE_EDUCATIONAL;
  1242. return "function (attribute, value) { return $('#organization-type').val() === '{$type}'; }";
  1243. }
  1244.  
  1245. /**
  1246. * Список типов организаций для поля select
  1247. *
  1248. * @return array
  1249. */
  1250. public static function organizationTypeList()
  1251. {
  1252. return [
  1253. self::ORGANIZATION_TYPE_EDUCATIONAL => 'Образовательная организация',
  1254. self::ORGANIZATION_TYPE_TRAINING => 'Организация, осуществляющая обучение',
  1255. self::ORGANIZATION_TYPE_IE_WITH_EMPLOYEES => 'Индивидуальный предприниматель, оказывающий услуги с наймом работников',
  1256. self::ORGANIZATION_TYPE_IE_WITHOUT_EMPLOYEES => 'Индивидуальный предприниматель, оказывающий услуги без найма работников'
  1257. ];
  1258. }
  1259.  
  1260. /**
  1261. * @inheritdoc
  1262. */
  1263. public function afterValidate()
  1264. {
  1265. parent::afterValidate();
  1266.  
  1267. // Принудительно сбрасываем значение additional_provider_type_id если тип не "Образовательная организация"
  1268. if ($this->type != self::ORGANIZATION_TYPE_EDUCATIONAL) {
  1269. $this->additional_provider_type_id = null;
  1270. }
  1271. }
  1272.  
  1273. /**
  1274. * @inheritdoc
  1275. */
  1276. public function attributeHints()
  1277. {
  1278. return array_merge(parent::attributeHints(), [
  1279. 'additional_provider_type_id' => 'Заполняется если тип поставщика "' . ArrayHelper::getValue(self::organizationTypeList(),
  1280. self::ORGANIZATION_TYPE_EDUCATIONAL) . '"'
  1281. ]);
  1282. }
  1283.  
  1284. /**
  1285. * получить список программ указанного реестра в которые можно записаться
  1286. *
  1287. * @param $fund_type - тип фонда программы
  1288. *
  1289. * @see ProgramFundType
  1290. *
  1291. * @return Programs[]|null[]
  1292. */
  1293. public function getAvailableProgramsByFundType($fund_type)
  1294. {
  1295. return $this->getPrograms()
  1296. ->joinWith(['programVerifications'])
  1297. ->where(['program_verification.status' => ProgramVerificationStatus::DONE])
  1298. ->andWhere(['program_verification.fund_type' => $fund_type])
  1299. ->all();
  1300. }
  1301. }
Add Comment
Please, Sign In to add comment