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

Companies::userAssociatedToCompany()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 1
nc 2
nop 1
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 6
rs 10
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
use Exception;
10
11
/**
12
 * Class Companies
13
 *
14
 * @package Gewaer\Models
15
 *
16
 * @property Users $user
17
 * @property CompaniesBranches $branch
18
 * @property CompaniesBranches $branches
19
 * @property Config $config
20
 * @property UserCompanyApps $app
21
 * @property \Phalcon\Di $di
22
 */
23
class Companies extends \Gewaer\CustomFields\AbstractCustomFieldsModel
24
{
25
    const DEFAULT_COMPANY = 'DefaulCompany';
26
27
    /**
28
     *
29
     * @var integer
30
     */
31
    public $id;
32
33
    /**
34
     *
35
     * @var string
36
     */
37
    public $name;
38
39
    /**
40
     *
41
     * @var string
42
     */
43
    public $profile_image;
44
45
    /**
46
     *
47
     * @var string
48
     */
49
    public $website;
50
51
    /**
52
     *
53
     * @var integer
54
     */
55
    public $users_id;
56
57
    /**
58
     *
59
     * @var integer
60
     */
61
    public $has_activities;
62
63
    /**
64
     *
65
     * @var string
66
     */
67
    public $created_at;
68
69
    /**
70
     *
71
     * @var string
72
     */
73
    public $updated_at;
74
75
    /**
76
     *
77
     * @var integer
78
     */
79
    public $is_deleted;
80
81
    /**
82
     * Provide the app plan id
83
     *
84
     * @var integer
85
     */
86
    public $appPlanId = null;
87
88
    /**
89
     * Initialize method for model.
90
     */
91 21
    public function initialize()
92
    {
93 21
        $this->setSource('companies');
94
95 21
        $this->belongsTo('users_id', 'Baka\Auth\Models\Users', 'id', ['alias' => 'user']);
96 21
        $this->hasMany('id', 'Baka\Auth\Models\CompanySettings', 'id', ['alias' => 'settings']);
97
98 21
        $this->belongsTo(
99 21
            'users_id',
100 21
            'Gewaer\Models\Users',
101 21
            'id',
102 21
            ['alias' => 'user']
103
        );
104
105 21
        $this->hasMany(
106 21
            'id',
107 21
            'Gewaer\Models\CompaniesBranches',
108 21
            'companies_id',
109 21
            ['alias' => 'branches']
110
        );
111
112 21
        $this->hasMany(
113 21
            'id',
114 21
            'Gewaer\Models\CompaniesCustomFields',
115 21
            'companies_id',
116 21
            ['alias' => 'fields']
117
        );
118
119 21
        $this->hasMany(
120 21
            'id',
121 21
            'Gewaer\CustomFields\CustomFields',
122 21
            'companies_id',
123 21
            ['alias' => 'custom-fields']
124
        );
125
126 21
        $this->hasMany(
127 21
            'id',
128 21
            'Gewaer\Models\UsersAssociatedCompany',
129 21
            'company_id',
130 21
            ['alias' => 'UsersAssociatedCompany']
131
        );
132
133 21
        $this->hasOne(
134 21
            'id',
135 21
            'Gewaer\Models\CompaniesBranches',
136 21
            'companies_id',
137
            [
138 21
                'alias' => 'branch',
139
            ]
140
        );
141
142 21
        $this->hasOne(
143 21
            'id',
144 21
            'Gewaer\Models\UserCompanyApps',
145 21
            'company_id',
146
            [
147 21
                'alias' => 'app',
148
                'params' => [
149 21
                    'conditions' => 'apps_id = ' . $this->di->getApp()->getId()
150
                ]
151
            ]
152
        );
153
154 21
        $this->hasOne(
155 21
            'id',
156 21
            'Gewaer\Models\UserCompanyApps',
157 21
            'company_id',
158
            [
159 21
                'alias' => 'apps',
160
                'params' => [
161 21
                    'conditions' => 'apps_id = ' . $this->di->getApp()->getId()
162
                ]
163
            ]
164
        );
165
166 21
        $this->hasOne(
167 21
            'id',
168 21
            'Gewaer\Models\Subscription',
169 21
            'company_id',
170
            [
171 21
                'alias' => 'subscription',
172
                'params' => [
173 21
                    'conditions' => 'apps_id = ' . $this->di->getApp()->getId() . ' AND ends_at is null AND is_deleted = 0 ',
174 21
                    'order' => 'id DESC'
175
                ]
176
            ]
177
        );
178
179 21
        $this->hasMany(
180 21
            'id',
181 21
            'Gewaer\Models\Subscription',
182 21
            'company_id',
183
            [
184 21
                'alias' => 'subscriptions',
185
                'params' => [
186 21
                    'conditions' => 'apps_id = ' . $this->di->getApp()->getId() . ' AND is_deleted = 0',
187 21
                    'order' => 'id DESC'
188
                ]
189
            ]
190
        );
191 21
    }
192
193
    /**
194
     * Model validation
195
     *
196
     * @return void
197
     */
198 1
    public function validation()
199
    {
200 1
        $validator = new Validation();
201
202 1
        $validator->add(
203 1
            'name',
204 1
            new PresenceOf([
205 1
                'model' => $this,
206
                'required' => true,
207
            ])
208
        );
209
210 1
        return $this->validate($validator);
211
    }
212
213
    /**
214
    * Register a company given a user and name
215
    *
216
    * @param  Users  $user
217
    * @param  string $name
218
    * @return Companies
219
    */
220
    public static function register(Users $user, string $name): Companies
221
    {
222
        $company = new self();
223
        $company->name = $name;
224
        $company->users_id = $user->getId();
225
226
        if (!$company->save()) {
227
            throw new Exception(current($company->getMessages()));
228
        }
229
230
        return $company;
231
    }
232
233
    /**
234
     * Returns table name mapped in the model.
235
     *
236
     * @return string
237
     */
238 15
    public function getSource() : string
239
    {
240 15
        return 'companies';
241
    }
242
243
    /**
244
     * Confirm if a user belongs to this current company
245
     *
246
     * @param Users $user
247
     * @return boolean
248
     */
249
    public function userAssociatedToCompany(Users $user): bool
250
    {
251
        return is_object($this->getUsersAssociatedCompany('users_id =' . $user->getId())) ? true : false;
252
    }
253
254
    /**
255
     * After creating the company
256
     *
257
     * @return void
258
     */
259
    public function afterCreate()
260
    {
261
        //setup the user notificatoin setting
262
        $companySettings = new CompaniesSettings();
263
        $companySettings->company_id = $this->getId();
264
        $companySettings->name = 'notifications';
265
        $companySettings->value = $this->user->email;
266
        if (!$companySettings->save()) {
267
            throw new Exception(current($companySettings->getMessages()));
268
        }
269
270
        //multi user asociation
271
        $usersAssociatedCompany = new UsersAssociatedCompany();
272
        $usersAssociatedCompany->users_id = $this->user->getId();
273
        $usersAssociatedCompany->company_id = $this->getId();
274
        $usersAssociatedCompany->identify_id = $this->user->getId();
275
        $usersAssociatedCompany->user_active = 1;
276
        $usersAssociatedCompany->user_role = 'admin';
277
        if (!$usersAssociatedCompany->save()) {
278
            throw new Exception(current($usersAssociatedCompany->getMessages()));
279
        }
280
281
        //now thta we setup de company and associated with the user we need to setup this as its default company
282
        if (!UserConfig::findFirst(['conditions' => 'users_id = ?0 and name = ?1', 'bind' => [$this->user->getId(), self::DEFAULT_COMPANY]])) {
283
            $userConfig = new UserConfig();
284
            $userConfig->users_id = $this->user->getId();
285
            $userConfig->name = self::DEFAULT_COMPANY;
286
            $userConfig->value = $this->getId();
287
288
            if (!$userConfig->save()) {
289
                throw new Exception(current($userConfig->getMessages()));
290
            }
291
        }
292
293
        /**
294
         * @var CompaniesBranches
295
         */
296
        $branch = new CompaniesBranches();
297
        $branch->companies_id = $this->getId();
298
        $branch->users_id = $this->user->getId();
299
        $branch->name = 'Default';
300
        $branch->is_default = 1;
301
        $branch->description = '';
302
        if (!$branch->save()) {
303
            throw new ServerErrorHttpException((string)current($branch->getMessages()));
304
        }
305
306
        //look for the default plan for this app
307
        $companyApps = new UserCompanyApps();
308
        $companyApps->company_id = $this->getId();
309
        $companyApps->apps_id = $this->di->getApp()->getId();
310
        $companyApps->subscriptions_id = 0;
311
312
        //we need to assign this company to a plan
313
        if (empty($this->appPlanId)) {
314
            $plan = AppsPlans::getDefaultPlan();
315
            $companyApps->stripe_id = $plan->stripe_id;
316
        }
317
318
        $companyApps->created_at = date('Y-m-d H:i:s');
319
        $companyApps->is_deleted = 0;
320
321
        if (!$companyApps->save()) {
322
            throw new ServerErrorHttpException((string)current($companyApps->getMessages()));
323
        }
324
    }
325
326
    /**
327
     * Get the default company the users has selected
328
     *
329
     * @param  Users  $user
330
     * @return Companies
331
     */
332
    public static function getDefaultByUser(Users $user): Companies
333
    {
334
        //verify the user has a default company
335
        $defaultCompany = UserConfig::findFirst([
336
            'conditions' => 'users_id = ?0 and name = ?1',
337
            'bind' => [$user->getId(), self::DEFAULT_COMPANY],
338
        ]);
339
340
        //found it
341
        if ($defaultCompany) {
0 ignored issues
show
introduced by
$defaultCompany is of type Phalcon\Mvc\Model, thus it always evaluated to true.
Loading history...
342
            return self::findFirst($defaultCompany->value);
343
        }
344
345
        //second try
346
        $defaultCompany = UsersAssociatedCompany::findFirst([
347
            'conditions' => 'users_id = ?0 and user_active =?1',
348
            'bind' => [$user->getId(), 1],
349
        ]);
350
351
        if ($defaultCompany) {
352
            return self::findFirst($defaultCompany->company_id);
353
        }
354
355
        throw new Exception(_("User doesn't have an active company"));
356
    }
357
358
    /**
359
     * After the model was update we need to update its custom fields
360
     *
361
     * @return void
362
     */
363 1
    public function afterUpdate()
364
    {
365
        //only clean and change custom fields if they are been sent
366 1
        if (!empty($this->customFields)) {
367
            //replace old custom with new
368 1
            $allCustomFields = $this->getAllCustomFields();
369 1
            if (is_array($allCustomFields)) {
1 ignored issue
show
introduced by
The condition is_array($allCustomFields) is always true.
Loading history...
370 1
                foreach ($this->customFields as $key => $value) {
371 1
                    $allCustomFields[$key] = $value;
372
                }
373
            }
374
375 1
            if (!empty($allCustomFields)) {
376
                //set
377 1
                $this->setCustomFields($allCustomFields);
378
                //clean old
379 1
                $this->cleanCustomFields($this->getId());
380
                //save new
381 1
                $this->saveCustomFields();
382
            }
383
        }
384
    }
385
}
386