Test Failed
Pull Request — master (#52)
by Rafael
05:00
created

Companies::afterCreate()   B

Complexity

Conditions 10
Paths 25

Size

Total Lines 75
Code Lines 45

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 36
CRAP Score 11.0274

Importance

Changes 0
Metric Value
cc 10
eloc 45
nc 25
nop 0
dl 0
loc 75
ccs 36
cts 46
cp 0.7826
crap 11.0274
rs 7.3333
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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