Failed Conditions
Pull Request — master (#48)
by Rafael
05:06
created

Companies   A

Complexity

Total Complexity 27

Size/Duplication

Total Lines 431
Duplicated Lines 0 %

Test Coverage

Coverage 84.7%

Importance

Changes 0
Metric Value
eloc 189
dl 0
loc 431
ccs 155
cts 183
cp 0.847
rs 10
c 0
b 0
f 0
wmc 27

9 Methods

Rating   Name   Duplication   Size   Complexity  
B afterCreate() 0 75 10
A afterUpdate() 0 19 5
A userAssociatedToCompany() 0 3 2
A register() 0 11 2
A getSource() 0 3 1
A validation() 0 13 1
A startCompanySubscription() 0 27 2
A getDefaultByUser() 0 24 3
B initialize() 0 117 1
1
<?php
2
declare(strict_types=1);
3
4
namespace Gewaer\Models;
5
6
use Phalcon\Validation;
7
use Phalcon\Validation\Validator\PresenceOf;
8
use Gewaer\Exception\ServerErrorHttpException;
9
use Exception;
10
use Carbon\Carbon;
11
12
/**
13
 * Class Companies
14
 *
15
 * @package Gewaer\Models
16
 *
17
 * @property Users $user
18
 * @property CompaniesBranches $branch
19
 * @property CompaniesBranches $branches
20
 * @property Config $config
21
 * @property UserCompanyApps $app
22
 * @property \Phalcon\Di $di
23
 */
24
class Companies extends \Gewaer\CustomFields\AbstractCustomFieldsModel
25
{
26
    const DEFAULT_COMPANY = 'DefaulCompany';
27
28
    /**
29
     *
30
     * @var integer
31
     */
32
    public $id;
33
34
    /**
35
     *
36
     * @var string
37
     */
38
    public $name;
39
40
    /**
41
     *
42
     * @var string
43
     */
44
    public $profile_image;
45
46
    /**
47
     *
48
     * @var string
49
     */
50
    public $website;
51
52
    /**
53
     *
54
     * @var integer
55
     */
56
    public $users_id;
57
58
    /**
59
     *
60
     * @var integer
61
     */
62
    public $has_activities;
63
64
    /**
65
     *
66
     * @var string
67
     */
68
    public $created_at;
69
70
    /**
71
     *
72
     * @var string
73
     */
74
    public $updated_at;
75
76
    /**
77
     *
78
     * @var integer
79
     */
80
    public $is_deleted;
81
82
    /**
83
     * Provide the app plan id
84
     *
85
     * @var integer
86
     */
87
    public $appPlanId = null;
88
89
    /**
90
     *
91
     * @var integer
92
     */
93
    public $currency_id;
94
95
    /**
96
     * Initialize method for model.
97
     */
98 23
    public function initialize()
99
    {
100 23
        $this->setSource('companies');
101
102 23
        $this->belongsTo('users_id', 'Baka\Auth\Models\Users', 'id', ['alias' => 'user']);
103 23
        $this->hasMany('id', 'Baka\Auth\Models\CompanySettings', 'id', ['alias' => 'settings']);
104
105 23
        $this->belongsTo(
106 23
            'users_id',
107 23
            'Gewaer\Models\Users',
108 23
            'id',
109 23
            ['alias' => 'user']
110
        );
111
112 23
        $this->hasMany(
113 23
            'id',
114 23
            'Gewaer\Models\CompaniesBranches',
115 23
            'companies_id',
116 23
            ['alias' => 'branches']
117
        );
118
119 23
        $this->hasMany(
120 23
            'id',
121 23
            'Gewaer\Models\CompaniesCustomFields',
122 23
            'companies_id',
123 23
            ['alias' => 'fields']
124
        );
125
126 23
        $this->hasMany(
127 23
            'id',
128 23
            'Gewaer\CustomFields\CustomFields',
129 23
            'companies_id',
130 23
            ['alias' => 'custom-fields']
131
        );
132
133 23
        $this->hasMany(
134 23
            'id',
135 23
            'Gewaer\Models\UsersAssociatedCompany',
136 23
            'companies_id',
137 23
            ['alias' => 'UsersAssociatedCompany']
138
        );
139
140 23
        $this->hasOne(
141 23
            'id',
142 23
            'Gewaer\Models\CompaniesBranches',
143 23
            'companies_id',
144
            [
145 23
                'alias' => 'branch',
146
            ]
147
        );
148
149 23
        $this->hasOne(
150 23
            'id',
151 23
            'Gewaer\Models\UserCompanyApps',
152 23
            'companies_id',
153
            [
154 23
                'alias' => 'app',
155
                'params' => [
156 23
                    'conditions' => 'apps_id = ' . $this->di->getApp()->getId()
157
                ]
158
            ]
159
        );
160
161 23
        $this->hasOne(
162 23
            'id',
163 23
            'Gewaer\Models\UserCompanyApps',
164 23
            'companies_id',
165
            [
166 23
                'alias' => 'apps',
167
                'params' => [
168 23
                    'conditions' => 'apps_id = ' . $this->di->getApp()->getId()
169
                ]
170
            ]
171
        );
172
173 23
        $this->hasOne(
174 23
            'id',
175 23
            'Gewaer\Models\Subscription',
176 23
            'companies_id',
177
            [
178 23
                'alias' => 'subscription',
179
                'params' => [
180 23
                    'conditions' => 'apps_id = ' . $this->di->getApp()->getId() . ' AND ends_at is null AND is_deleted = 0 ',
181 23
                    'order' => 'id DESC'
182
                ]
183
            ]
184
        );
185
186 23
        $this->hasMany(
187 23
            'id',
188 23
            'Gewaer\Models\Subscription',
189 23
            'companies_id',
190
            [
191 23
                'alias' => 'subscriptions',
192
                'params' => [
193 23
                    'conditions' => 'apps_id = ' . $this->di->getApp()->getId() . ' AND is_deleted = 0',
194 23
                    'order' => 'id DESC'
195
                ]
196
            ]
197
        );
198
199 23
        $this->hasMany(
200 23
            'id',
201 23
            'Gewaer\Models\UserWebhooks',
202 23
            'companies_id',
203 23
            ['alias' => 'user-webhooks']
204
        );
205
206 23
        $systemModule = SystemModules::getSystemModuleByModelName(self::class);
207 23
        $this->hasMany(
208 23
            'id',
209 23
            'Gewaer\Models\FileSystem',
210 23
            'entity_id',
211
            [
212 23
                'alias' => 'filesystem',
213 23
                'conditions' => 'system_modules_id = ?0',
214 23
                'bind' => [$systemModule->getId()]
215
            ]
216
        );
217 23
    }
218
219
    /**
220
     * Model validation
221
     *
222
     * @return void
223
     */
224 4
    public function validation()
225
    {
226 4
        $validator = new Validation();
227
228 4
        $validator->add(
229 4
            'name',
230 4
            new PresenceOf([
231 4
                'model' => $this,
232
                'required' => true,
233
            ])
234
        );
235
236 4
        return $this->validate($validator);
237
    }
238
239
    /**
240
    * Register a company given a user and name
241
    *
242
    * @param  Users  $user
243
    * @param  string $name
244
    * @return Companies
245
    */
246
    public static function register(Users $user, string $name): Companies
247
    {
248
        $company = new self();
249
        $company->name = $name;
250
        $company->users_id = $user->getId();
251
252
        if (!$company->save()) {
253
            throw new Exception(current($company->getMessages()));
254
        }
255
256
        return $company;
257
    }
258
259
    /**
260
     * Returns table name mapped in the model.
261
     *
262
     * @return string
263
     */
264 15
    public function getSource() : string
265
    {
266 15
        return 'companies';
267
    }
268
269
    /**
270
     * Confirm if a user belongs to this current company
271
     *
272
     * @param Users $user
273
     * @return boolean
274
     */
275
    public function userAssociatedToCompany(Users $user): bool
276
    {
277
        return is_object($this->getUsersAssociatedCompany('users_id =' . $user->getId())) ? true : false;
278
    }
279
280
    /**
281
     * After creating the company
282
     *
283
     * @return void
284
     */
285 3
    public function afterCreate()
286
    {
287 3
        parent::afterCreate();
288
289
        //setup the user notificatoin setting
290 3
        $companySettings = new CompaniesSettings();
291 3
        $companySettings->companies_id = $this->getId();
292 3
        $companySettings->name = 'notifications';
293 3
        $companySettings->value = $this->user->email;
294 3
        if (!$companySettings->save()) {
295
            throw new Exception((string)current($companySettings->getMessages()));
296
        }
297
298
        //multi user asociation
299 3
        $usersAssociatedCompany = new UsersAssociatedCompany();
300 3
        $usersAssociatedCompany->users_id = $this->user->getId();
301 3
        $usersAssociatedCompany->companies_id = $this->getId();
302 3
        $usersAssociatedCompany->identify_id = $this->user->getId();
303 3
        $usersAssociatedCompany->user_active = 1;
304 3
        $usersAssociatedCompany->user_role = 'admin';
305 3
        if (!$usersAssociatedCompany->save()) {
306
            throw new Exception((string)current($usersAssociatedCompany->getMessages()));
307
        }
308
309
        //now thta we setup de company and associated with the user we need to setup this as its default company
310 3
        if (!UserConfig::findFirst(['conditions' => 'users_id = ?0 and name = ?1', 'bind' => [$this->user->getId(), self::DEFAULT_COMPANY]])) {
311 1
            $userConfig = new UserConfig();
312 1
            $userConfig->users_id = $this->user->getId();
313 1
            $userConfig->name = self::DEFAULT_COMPANY;
314 1
            $userConfig->value = $this->getId();
315
316 1
            if (!$userConfig->save()) {
317
                throw new Exception((string)current($userConfig->getMessages()));
318
            }
319
        }
320
321
        /**
322
         * @var CompaniesBranches
323
         */
324 3
        $branch = new CompaniesBranches();
325 3
        $branch->companies_id = $this->getId();
326 3
        $branch->users_id = $this->user->getId();
327 3
        $branch->name = 'Default';
328 3
        $branch->is_default = 1;
329 3
        $branch->description = '';
330 3
        if (!$branch->save()) {
331
            throw new ServerErrorHttpException((string)current($branch->getMessages()));
332
        }
333
334
        //look for the default plan for this app
335 3
        $companyApps = new UserCompanyApps();
336 3
        $companyApps->companies_id = $this->getId();
337 3
        $companyApps->apps_id = $this->di->getApp()->getId();
338 3
        $companyApps->subscriptions_id = 0;
339
340
        //we need to assign this company to a plan
341 3
        if (empty($this->appPlanId)) {
342 3
            $plan = AppsPlans::getDefaultPlan();
343 3
            $companyApps->stripe_id = $plan->stripe_id;
344
        }
345
346
        //If the newly created company is not the default then we create a new subscription with the same user
347 3
        if ($this->userData->default_company != $this->getId()) {
0 ignored issues
show
Bug Best Practice introduced by
The property userData does not exist on Gewaer\Models\Companies. Since you implemented __get, consider adding a @property annotation.
Loading history...
Bug introduced by
The property default_company does not seem to exist on Phalcon\Mvc\Model\Resultset.
Loading history...
348 3
            $subscription = $this->startCompanySubscription();
349
350 3
            if (!is_object($subscription)) {
351
                throw new Exception('Subscription for new company could not be created');
352
            }
353
        }
354
355 3
        $companyApps->created_at = date('Y-m-d H:i:s');
356 3
        $companyApps->is_deleted = 0;
357
358 3
        if (!$companyApps->save()) {
359
            throw new ServerErrorHttpException((string)current($companyApps->getMessages()));
360
        }
361 3
    }
362
363
    /**
364
     * Get the default company the users has selected
365
     *
366
     * @param  Users  $user
367
     * @return Companies
368
     */
369
    public static function getDefaultByUser(Users $user): Companies
370
    {
371
        //verify the user has a default company
372
        $defaultCompany = UserConfig::findFirst([
373
            'conditions' => 'users_id = ?0 and name = ?1',
374
            'bind' => [$user->getId(), self::DEFAULT_COMPANY],
375
        ]);
376
377
        //found it
378
        if (is_object($defaultCompany)) {
379
            return self::findFirst($defaultCompany->value);
380
        }
381
382
        //second try
383
        $defaultCompany = UsersAssociatedCompany::findFirst([
384
            'conditions' => 'users_id = ?0 and user_active =?1',
385
            'bind' => [$user->getId(), 1],
386
        ]);
387
388
        if (is_object($defaultCompany)) {
389
            return self::findFirst($defaultCompany->companies_id);
390
        }
391
392
        throw new Exception(_("User doesn't have an active company"));
393
    }
394
395
    /**
396
     * After the model was update we need to update its custom fields
397
     *
398
     * @return void
399
     */
400 2
    public function afterUpdate()
401
    {
402
        //only clean and change custom fields if they are been sent
403 2
        if (!empty($this->customFields)) {
404
            //replace old custom with new
405 1
            $allCustomFields = $this->getAllCustomFields();
406 1
            if (is_array($allCustomFields)) {
407 1
                foreach ($this->customFields as $key => $value) {
408 1
                    $allCustomFields[$key] = $value;
409
                }
410
            }
411
412 1
            if (!empty($allCustomFields)) {
413
                //set
414 1
                $this->setCustomFields($allCustomFields);
415
                //clean old
416 1
                $this->cleanCustomFields($this->getId());
417
                //save new
418 1
                $this->saveCustomFields();
419
            }
420
        }
421 2
    }
422
423
    /**
424
     * Start a free trial for a new company
425
     *
426
     * @return Subscription
427
     */
428 3
    public function startCompanySubscription() : Subscription
429
    {
430 3
        $defaultPlan = AppsPlans::getDefaultPlan();
431 3
        $trialEndsAt = Carbon::now()->addDays($this->di->getApp()->plan->free_trial_dates);
432
433 3
        $subscription = new Subscription();
434 3
        $subscription->user_id = $this->di->getUserData()->getId();
435 3
        $subscription->companies_id = $this->getId();
436 3
        $subscription->apps_id = $this->di->getApp()->getId();
437 3
        $subscription->apps_plans_id = $this->di->getApp()->default_apps_plan_id;
438 3
        $subscription->name = $defaultPlan->name;
439 3
        $subscription->stripe_id = $defaultPlan->stripe_id;
440 3
        $subscription->stripe_plan = $defaultPlan->stripe_plan;
441 3
        $subscription->quantity = 1;
442 3
        $subscription->trial_ends_at = $trialEndsAt->toDateTimeString();
443 3
        $subscription->trial_ends_days = $trialEndsAt->diffInDays(Carbon::now());
444 3
        $subscription->is_freetrial = 1;
445 3
        $subscription->is_active = 1;
446
447 3
        if (!$subscription->save()) {
448
            throw new ServerErrorHttpException((string)current($this->getMessages()));
449
        }
450
451 3
        $this->trial_ends_at = $subscription->trial_ends_at;
0 ignored issues
show
Bug Best Practice introduced by
The property trial_ends_at does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
452 3
        $this->update();
453
454 3
        return $subscription;
455
    }
456
}
457