File: //home/aliazzsr/api.crm.vqode.com/models/core/Company.php
<?php
namespace app\models\core;
use app\components\BaseModel;
use app\components\formatters\DateFormatter;
use app\components\validators\WebsiteValidator;
use yii\behaviors\AttributeTypecastBehavior;
use yii\db\Expression;
use yii\db\Query;
/**
* Class Company
* @package app\models\core
* @property integer $id
*/
class Company extends BaseModel
{
protected static $actionPermissionMap = [
'first-letter' => 'read',
'index' => 'read',
'view' => 'read',
'validate' => 'read',
'options' => 'read',
'create' => 'create',
'update' => 'update',
'delete' => 'delete',
];
public $countContacts;
public $countClosedProjects;
public $countOpenProjects;
public static $extraFields = [
'companyType',
'owner',
'companyContacts',
'projects',
'companyProjects',
];
/**
* @inheritdoc
*/
public static function tableName()
{
return 'company';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['name', 'company_type_id', 'owner_id'], 'required'],
[
[
'name', 'phone', 'website',
'address_1', 'address_2', 'address_3', 'postal_town', 'post_code',
'notes',
],
'string',
'max' => 255
],
[['next_action_at',], 'date', 'format' => 'php:d/m/Y', 'message' => 'Date should be in format DD/MM/YYYY',],
[['website'], WebsiteValidator::className()],
[['company_type_id', 'owner_id'], 'integer'],
[['company_type_id'], 'exist', 'targetClass' => CompanyType::className(), 'targetAttribute' => 'id'],
[['owner_id'], 'exist', 'targetClass' => User::className(), 'targetAttribute' => 'id'],
[
[
'name', 'phone', 'website', 'company_type_id',
'address_1', 'address_2', 'address_3', 'postal_town', 'post_code',
'notes', 'location', 'longitude', 'latitude',
],
'safe',
],
[
'name',
'unique',
'message' => 'A duplicate company with the same name has been found',
'on' => self::SCENARIO_STRICT_VALIDATE,
],
];
}
public function getProjects()
{
return $this->hasMany(Project::className(), ['id' => 'project_id'])
->viaTable(CompanyProject::tableName(), ['company_id' => 'id']);
}
public function delete()
{
$tran = $this->getDb()->beginTransaction();
try {
foreach ($this->getCompanyContacts()->all() as $contact) {
$contact->delete();
}
foreach ($this->getCompanyProjects()->all() as $project) {
$project->delete();
}
if (!parent::delete()) {
throw new \Exception('Internal server error');
}
$tran->commit();
} catch (\Throwable $e) {
$tran->rollBack();
throw $e;
}
return true;
}
public static function findWithJoin()
{
return parent::find()
->joinWith([
'companyType as companyType',
'owner as owner',
]);
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'company_type_id' => 'Company Type',
'owner_id' => 'Owner',
];
}
public static function getAdditionalFields()
{
return [
'countContacts' => self::getCountContacts(),
'countClosedProjects' => self::getCountClosedProjects(),
'countOpenProjects' => self::getCountOpenProjects(),
];
}
protected static function getCountContacts()
{
$subQuery = new Query();
$subQuery->select('count(*)')
->from(['countContacts' => CompanyContact::tableName()])
->where(['countContacts.company_id' => new Expression(self::tableName() . '.id')]);
return $subQuery;
}
protected static function getCountClosedProjects()
{
$subQuery = new Query();
$subQuery->select('count(*)')
->from(['cp' => CompanyProject::tableName()])
->innerJoin(Project::tableName() . ' as p', 'p.id = cp.project_id')
->innerJoin(Stage::tableName() . ' as s', 's.id = p.stage_id')
->where(['cp.company_id' => new Expression(self::tableName() . '.id')])
->andWhere(['s.active' => false]);
return $subQuery;
}
protected static function getCountOpenProjects()
{
$subQuery = new Query();
$subQuery->select('count(*)')
->from(['cp' => CompanyProject::tableName()])
->innerJoin(Project::tableName() . ' as p', 'p.id = cp.project_id')
->innerJoin(Stage::tableName() . ' as s', 's.id = p.stage_id')
->where(['cp.company_id' => new Expression(self::tableName() . '.id')])
->andWhere(['s.active' => true]);
return $subQuery;
}
public function behaviors()
{
$behaviors = [
'typecasts' => [
'class' => AttributeTypecastBehavior::className(),
'attributeTypes' => [
'company_type_id' => AttributeTypecastBehavior::TYPE_INTEGER,
'owner_id' => AttributeTypecastBehavior::TYPE_INTEGER,
'countContacts' => AttributeTypecastBehavior::TYPE_INTEGER,
'countOpenProjects' => AttributeTypecastBehavior::TYPE_INTEGER,
'countClosedProjects' => AttributeTypecastBehavior::TYPE_INTEGER,
],
'typecastAfterValidate' => true,
'typecastBeforeSave' => true,
'typecastAfterFind' => true,
],
];
return array_merge(parent::behaviors(), $behaviors);
}
public function afterFind()
{
$this->next_action_at = $this->next_action_at ? DateFormatter::toString($this->next_action_at) : null;
parent::afterFind();
}
public function beforeSave($insert)
{
$this->next_action_at = $this->next_action_at ? DateFormatter::toMysql($this->next_action_at) : null;
$this->first_letter = strtoupper(substr($this->name, 0, 1));
return parent::beforeSave($insert);
}
public function afterSave($insert, $changedAttributes)
{
$this->next_action_at = $this->next_action_at ? DateFormatter::toString($this->next_action_at) : null;
return parent::afterSave($insert, $changedAttributes);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCompanyType()
{
return $this->hasOne(CompanyType::className(), ['id' => 'company_type_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getOwner()
{
return $this->hasOne(User::className(), ['id' => 'owner_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCompanyContacts()
{
return $this->hasMany(CompanyContact::className(), ['company_id' => 'id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCompanyProjects()
{
return $this->hasMany(CompanyProject::className(), ['company_id' => 'id']);
}
}
/**
* @SWG\Definition(
* definition="Company",
* type="object",
* description="Company model",
* allOf={
* @SWG\Schema(ref="#/definitions/Company"),
* @SWG\Schema(
* required={"name","company_type_id","owner_id"},
* @SWG\Property(property="id", type="integer", example=7, description="Company unique identifier, readonly"),
* @SWG\Property(property="company_type_id", type="integer", example=1, description="Company Type identifier"),
* @SWG\Property(property="owner_id", type="integer", example=3, description="The user of the software who looks after this customer/contact for the client (user identifier)"),
* @SWG\Property(property="name", type="string", example="Barchester Healthcare Ltd", description="Company name"),
* @SWG\Property(property="website", type="string", example="www.barchester.com", description="Company website"),
* @SWG\Property(property="phone", type="string", example="020 7352 2224", description="Company phone"),
* @SWG\Property(property="location", type="string", example="Suite 201, Design Centre East", description="Company location"),
* @SWG\Property(property="longitude", type="double", example=0.12345, description="Company location, longitude"),
* @SWG\Property(property="latitude", type="double", example=-51.5083896, description="Company location, latitude"),
* @SWG\Property(property="address_1", type="string", example="Suite 201, Design Centre East", description="First part of address"),
* @SWG\Property(property="address_2", type="string", example="Chelsea Harbour", description="Second part of address"),
* @SWG\Property(property="address_3", type="string", description="Third part of address"),
* @SWG\Property(property="postal_town", type="string", example="London", description="Company postal town"),
* @SWG\Property(property="post_code", type="string", example="SW10 0XF", description="Company post code"),
* @SWG\Property(property="next_action_at", type="string", example="23/03/2018", description="Next action date in format DD/MM/YYYY."),
* @SWG\Property(property="notes", type="string", example="Sunt provident nostrum totam. Ea repellat et distinctio.", description="Ane notes"),
* @SWG\Property(property="countContacts", type="integer", description="Readonly. The amount of People/Contacts saved within the shown Company"),
* @SWG\Property(property="countClosedProjects", type="integer", description="Readonly. The amount of Closed Projects."),
* @SWG\Property(property="countOpenProjects", type="integer", description="Readonly. The amount of Open Projects.")
* )
* }
* )
*/