Test Failed
Pull Request — master (#20)
by
unknown
03:44
created

Companies::getDefaultByUser()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 24
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
eloc 11
nc 3
nop 1
dl 0
loc 24
ccs 0
cts 12
cp 0
crap 12
rs 9.9
c 0
b 0
f 0
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
10
/**
11
 * Class Companies
12
 *
13
 * @package Gewaer\Models
14
 *
15
 * @property Users $user
16
 * @property CompanyBranches $branch
17
 * @property CompanyBranches $branches
18
 * @property Config $config
19
 * @property UserCompanyApps $app
20
 * @property \Phalcon\Di $di
21
 */
22
class Companies extends \Gewaer\CustomFields\AbstractCustomFieldsModel
23
{
24
    /**
25
     *
26
     * @var integer
27
     */
28
    public $id;
29
30
    /**
31
     *
32
     * @var string
33
     */
34
    public $name;
35
36
    /**
37
     *
38
     * @var string
39
     */
40
    public $profile_image;
41
42
    /**
43
     *
44
     * @var string
45
     */
46
    public $website;
47
48
    /**
49
     *
50
     * @var integer
51
     */
52
    public $users_id;
53
54
    /**
55
     *
56
     * @var integer
57
     */
58
    public $has_activities;
59
60
    /**
61
     *
62
     * @var string
63
     */
64
    public $created_at;
65
66
    /**
67
     *
68
     * @var string
69
     */
70
    public $updated_at;
71
72
    /**
73
     *
74
     * @var integer
75
     */
76
    public $is_deleted;
77
78
    /**
79
     * Provide the app plan id
80
     *
81
     * @var integer
82
     */
83
    public $appPlanId = null;
84
85
    /**
86
     * Initialize method for model.
87
     */
88 21
    public function initialize()
89
    {
90 21
        $this->setSource('companies');
91
92 21
        $this->belongsTo('users_id', 'Baka\Auth\Models\Users', 'id', ['alias' => 'user']);
93 21
        $this->hasMany('id', 'Baka\Auth\Models\CompanySettings', 'id', ['alias' => 'settings']);
94
95 21
        $this->belongsTo(
96 21
            'users_id',
97 21
            'Gewaer\Models\Users',
98 21
            'id',
99 21
            ['alias' => 'user']
100
        );
101
102 21
        $this->hasMany(
103 21
            'id',
104 21
            'Gewaer\Models\CompaniesBranches',
105 21
            'companies_id',
106 21
            ['alias' => 'branches']
107
        );
108
109 21
        $this->hasMany(
110 21
            'id',
111 21
            'Gewaer\Models\CompaniesCustomFields',
112 21
            'companies_id',
113 21
            ['alias' => 'fields']
114
        );
115
116 21
        $this->hasMany(
117 21
            'id',
118 21
            'Gewaer\CustomFields\CustomFields',
119 21
            'companies_id',
120 21
            ['alias' => 'custom-fields']
121
        );
122
123 21
        $this->hasMany(
124 21
            'id',
125 21
            'Gewaer\Models\UsersAssociatedCompany',
126 21
            'company_id',
127 21
            ['alias' => 'UsersAssociatedCompany']
128
        );
129
130 21
        $this->hasOne(
131 21
            'id',
132 21
            'Gewaer\Models\CompaniesBranches',
133 21
            'companies_id',
134
            [
135 21
                'alias' => 'branch',
136
            ]
137
        );
138
139 21
        $this->hasOne(
140 21
            'id',
141 21
            'Gewaer\Models\UserCompanyApps',
142 21
            'company_id',
143
            [
144 21
                'alias' => 'app',
145
                'params' => [
146 21
                    'conditions' => 'apps_id = ' . $this->di->getApp()->getId()
147
                ]
148
            ]
149
        );
150
151 21
        $this->hasOne(
152 21
            'id',
153 21
            'Gewaer\Models\UserCompanyApps',
154 21
            'company_id',
155
            [
156 21
                'alias' => 'apps',
157
                'params' => [
158 21
                    'conditions' => 'apps_id = ' . $this->di->getApp()->getId()
159
                ]
160
            ]
161
        );
162
163 21
        $this->hasOne(
164 21
            'id',
165 21
            'Gewaer\Models\Subscription',
166 21
            'company_id',
167
            [
168 21
                'alias' => 'subscription',
169
                'params' => [
170 21
                    'conditions' => 'apps_id = ' . $this->di->getApp()->getId() . ' AND ends_at is null AND is_deleted = 0 ',
171 21
                    'order' => 'id DESC'
172
                ]
173
            ]
174
        );
175
176 21
        $this->hasMany(
177 21
            'id',
178 21
            'Gewaer\Models\Subscription',
179 21
            'company_id',
180
            [
181 21
                'alias' => 'subscriptions',
182
                'params' => [
183 21
                    'conditions' => 'apps_id = ' . $this->di->getApp()->getId() . ' AND is_deleted = 0',
184 21
                    'order' => 'id DESC'
185
                ]
186
            ]
187
        );
188 21
    }
189
190
    /**
191
     * Model validation
192
     *
193
     * @return void
194
     */
195 1
    public function validation()
196
    {
197 1
        $validator = new Validation();
198
199 1
        $validator->add(
200 1
            'name',
201 1
            new PresenceOf([
202 1
                'model' => $this,
203
                'required' => true,
204
            ])
205
        );
206
207 1
        return $this->validate($validator);
208
    }
209
210
    /**
211
    * Register a company given a user and name
212
    *
213
    * @param  Users  $user
214
    * @param  string $name
215
    * @return Companies
216
    */
217
    public static function register(Users $user, string $name): Companies
218
    {
219
        $company = new self();
220
        $company->name = $name;
221
        $company->users_id = $user->getId();
222
223
        if (!$company->save()) {
224
            throw new Exception(current($company->getMessages()));
0 ignored issues
show
Bug introduced by
The type Gewaer\Models\Exception was not found. Did you mean Exception? If so, make sure to prefix the type with \.
Loading history...
225
        }
226
227
        return $company;
228
    }
229
230
    /**
231
     * Returns table name mapped in the model.
232
     *
233
     * @return string
234
     */
235 15
    public function getSource() : string
236
    {
237 15
        return 'companies';
238
    }
239
240
    /**
241
     * Confirm if a user belongs to this current company
242
     *
243
     * @param Users $user
244
     * @return boolean
245
     */
246
    public function userAssociatedToCompany(Users $user): bool
247
    {
248
        return is_object($this->getUsersAssociatedCompany('users_id =' . $user->getId())) ? true : false;
249
    }
250
251
    /**
252
     * After creating the company
253
     *
254
     * @return void
255
     */
256
    public function afterCreate()
257
    {
258
        //setup the user notificatoin setting
259
        $companySettings = new CompaniesSettings();
260
        $companySettings->company_id = $this->getId();
261
        $companySettings->name = 'notifications';
262
        $companySettings->value = $this->user->email;
263
        if (!$companySettings->save()) {
264
            throw new Exception(current($companySettings->getMessages()));
265
        }
266
267
        //multi user asociation
268
        $usersAssociatedCompany = new UsersAssociatedCompany();
269
        $usersAssociatedCompany->users_id = $this->user->getId();
270
        $usersAssociatedCompany->company_id = $this->getId();
271
        $usersAssociatedCompany->identify_id = $this->user->getId();
272
        $usersAssociatedCompany->user_active = 1;
273
        $usersAssociatedCompany->user_role = 'admin';
274
        if (!$usersAssociatedCompany->save()) {
275
            throw new Exception(current($usersAssociatedCompany->getMessages()));
276
        }
277
278
        //now thta we setup de company and associated with the user we need to setup this as its default company
279
        if (!UserConfig::findFirst(['conditions' => 'users_id = ?0 and name = ?1', 'bind' => [$this->user->getId(), self::DEFAULT_COMPANY]])) {
0 ignored issues
show
Bug introduced by
The constant Gewaer\Models\Companies::DEFAULT_COMPANY was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
280
            $userConfig = new UserConfig();
281
            $userConfig->users_id = $this->user->getId();
282
            $userConfig->name = self::DEFAULT_COMPANY;
283
            $userConfig->value = $this->getId();
284
285
            if (!$userConfig->save()) {
286
                throw new Exception(current($userConfig->getMessages()));
287
            }
288
        }
289
290
        /**
291
         * @var CompanyBranches
292
         */
293
        $branch = new CompanyBranches();
0 ignored issues
show
Bug introduced by
The type Gewaer\Models\CompanyBranches was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
294
        $branch->companies_id = $this->getId();
295
        $branch->users_id = $this->user->getId();
296
        $branch->name = 'Default';
297
        $branch->is_default = 1;
298
        $branch->description = '';
299
        if (!$branch->save()) {
300
            throw new ServerErrorHttpException((string)current($branch->getMessages()));
301
        }
302
303
        //look for the default plan for this app
304
        $companyApps = new UserCompanyApps();
305
        $companyApps->company_id = $this->getId();
306
        $companyApps->apps_id = $this->di->getApp()->getId();
307
        $companyApps->subscriptions_id = 0;
308
309
        //we need to assign this company to a plan
310
        if (empty($this->appPlanId)) {
311
            $plan = AppsPlans::getDefaultPlan();
312
            $companyApps->stripe_id = $plan->stripe_id;
313
        }
314
315
        $companyApps->created_at = date('Y-m-d H:i:s');
316
        $companyApps->is_deleted = 0;
317
318
        if (!$companyApps->save()) {
319
            throw new ServerErrorHttpException((string)current($companyApps->getMessages()));
320
        }
321
    }
322
323
    /**
324
     * Get the default company the users has selected
325
     *
326
     * @param  Users  $user
327
     * @return Companies
328
     */
329
    public static function getDefaultByUser(Users $user): Companies
330
    {
331
        //verify the user has a default company
332
        $defaultCompany = UserConfig::findFirst([
333
            'conditions' => 'users_id = ?0 and name = ?1',
334
            'bind' => [$user->getId(), self::DEFAULT_COMPANY],
0 ignored issues
show
Bug introduced by
The constant Gewaer\Models\Companies::DEFAULT_COMPANY was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
335
        ]);
336
337
        //found it
338
        if ($defaultCompany) {
0 ignored issues
show
introduced by
$defaultCompany is of type Phalcon\Mvc\Model, thus it always evaluated to true.
Loading history...
339
            return self::findFirst($defaultCompany->value);
340
        }
341
342
        //second try
343
        $defaultCompany = UsersAssociatedCompany::findFirst([
344
            'conditions' => 'users_id = ?0 and user_active =?1',
345
            'bind' => [$user->getId(), 1],
346
        ]);
347
348
        if ($defaultCompany) {
349
            return self::findFirst($defaultCompany->company_id);
350
        }
351
352
        throw new Exception(_("User doesn't have an active company"));
353
    }
354
355
    /**
356
     * After the model was update we need to update its custom fields
357
     *
358
     * @return void
359
     */
360 1
    public function afterUpdate()
361
    {
362
        //only clean and change custom fields if they are been sent
363 1
        if (!empty($this->customFields)) {
364
            //replace old custom with new
365 1
            $allCustomFields = $this->getAllCustomFields();
366 1
            if (is_array($allCustomFields)) {
0 ignored issues
show
introduced by
The condition is_array($allCustomFields) is always false.
Loading history...
367 1
                foreach ($this->customFields as $key => $value) {
368 1
                    $allCustomFields[$key] = $value;
369
                }
370
            }
371
372 1
            if (!empty($allCustomFields)) {
373
                //set
374 1
                $this->setCustomFields($allCustomFields);
0 ignored issues
show
Bug introduced by
$allCustomFields of type Phalcon\Mvc\Model is incompatible with the type array expected by parameter $fields of Baka\Database\ModelCustomFields::setCustomFields(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

374
                $this->setCustomFields(/** @scrutinizer ignore-type */ $allCustomFields);
Loading history...
375
                //clean old
376 1
                $this->cleanCustomFields($this->getId());
377
                //save new
378 1
                $this->saveCustomFields();
379
            }
380
        }
381 1
    }
382
}
383