Failed Conditions
Push — master ( 55bfad...b74acd )
by Maximo
02:48
created

Companies::afterUpdate()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 19
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 9
nc 5
nop 0
dl 0
loc 19
ccs 10
cts 10
cp 1
crap 5
rs 9.6111
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 27
    public function initialize()
92
    {
93 27
        $this->setSource('companies');
94
95 27
        $this->belongsTo('users_id', 'Baka\Auth\Models\Users', 'id', ['alias' => 'user']);
96 27
        $this->hasMany('id', 'Baka\Auth\Models\CompanySettings', 'id', ['alias' => 'settings']);
97
98 27
        $this->belongsTo(
99 27
            'users_id',
100 27
            'Gewaer\Models\Users',
101 27
            'id',
102 27
            ['alias' => 'user']
103
        );
104
105 27
        $this->hasMany(
106 27
            'id',
107 27
            'Gewaer\Models\CompaniesBranches',
108 27
            'companies_id',
109 27
            ['alias' => 'branches']
110
        );
111
112 27
        $this->hasMany(
113 27
            'id',
114 27
            'Gewaer\Models\CompaniesCustomFields',
115 27
            'companies_id',
116 27
            ['alias' => 'fields']
117
        );
118
119 27
        $this->hasMany(
120 27
            'id',
121 27
            'Gewaer\CustomFields\CustomFields',
122 27
            'companies_id',
123 27
            ['alias' => 'custom-fields']
124
        );
125
126 27
        $this->hasMany(
127 27
            'id',
128 27
            'Gewaer\Models\UsersAssociatedCompany',
129 27
            'companies_id',
130 27
            ['alias' => 'UsersAssociatedCompany']
131
        );
132
133 27
        $this->hasOne(
134 27
            'id',
135 27
            'Gewaer\Models\CompaniesBranches',
136 27
            'companies_id',
137
            [
138 27
                'alias' => 'branch',
139
            ]
140
        );
141
142 27
        $this->hasOne(
143 27
            'id',
144 27
            'Gewaer\Models\UserCompanyApps',
145 27
            'companies_id',
146
            [
147 27
                'alias' => 'app',
148
                'params' => [
149 27
                    'conditions' => 'apps_id = ' . $this->di->getApp()->getId()
150
                ]
151
            ]
152
        );
153
154 27
        $this->hasOne(
155 27
            'id',
156 27
            'Gewaer\Models\UserCompanyApps',
157 27
            'companies_id',
158
            [
159 27
                'alias' => 'apps',
160
                'params' => [
161 27
                    'conditions' => 'apps_id = ' . $this->di->getApp()->getId()
162
                ]
163
            ]
164
        );
165
166 27
        $this->hasOne(
167 27
            'id',
168 27
            'Gewaer\Models\Subscription',
169 27
            'companies_id',
170
            [
171 27
                'alias' => 'subscription',
172
                'params' => [
173 27
                    'conditions' => 'apps_id = ' . $this->di->getApp()->getId() . ' AND ends_at is null AND is_deleted = 0 ',
174 27
                    'order' => 'id DESC'
175
                ]
176
            ]
177
        );
178
179 27
        $this->hasMany(
180 27
            'id',
181 27
            'Gewaer\Models\Subscription',
182 27
            'companies_id',
183
            [
184 27
                'alias' => 'subscriptions',
185
                'params' => [
186 27
                    'conditions' => 'apps_id = ' . $this->di->getApp()->getId() . ' AND is_deleted = 0',
187 27
                    'order' => 'id DESC'
188
                ]
189
            ]
190
        );
191 27
    }
192
193
    /**
194
     * Model validation
195
     *
196
     * @return void
197
     */
198 4
    public function validation()
199
    {
200 4
        $validator = new Validation();
201
202 4
        $validator->add(
203 4
            'name',
204 4
            new PresenceOf([
205 4
                'model' => $this,
206
                'required' => true,
207
            ])
208
        );
209
210 4
        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 19
    public function getSource() : string
239
    {
240 19
        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 3
    public function afterCreate()
260
    {
261 3
        parent::afterCreate();
262
263
        //setup the user notificatoin setting
264 3
        $companySettings = new CompaniesSettings();
265 3
        $companySettings->companies_id = $this->getId();
266 3
        $companySettings->name = 'notifications';
267 3
        $companySettings->value = $this->user->email;
268 3
        if (!$companySettings->save()) {
269
            throw new Exception((string)current($companySettings->getMessages()));
270
        }
271
272
        //multi user asociation
273 3
        $usersAssociatedCompany = new UsersAssociatedCompany();
274 3
        $usersAssociatedCompany->users_id = $this->user->getId();
275 3
        $usersAssociatedCompany->companies_id = $this->getId();
276 3
        $usersAssociatedCompany->identify_id = $this->user->getId();
277 3
        $usersAssociatedCompany->user_active = 1;
278 3
        $usersAssociatedCompany->user_role = 'admin';
279 3
        if (!$usersAssociatedCompany->save()) {
280
            throw new Exception((string)current($usersAssociatedCompany->getMessages()));
281
        }
282
283
        //now thta we setup de company and associated with the user we need to setup this as its default company
284 3
        if (!UserConfig::findFirst(['conditions' => 'users_id = ?0 and name = ?1', 'bind' => [$this->user->getId(), self::DEFAULT_COMPANY]])) {
285 1
            $userConfig = new UserConfig();
286 1
            $userConfig->users_id = $this->user->getId();
287 1
            $userConfig->name = self::DEFAULT_COMPANY;
288 1
            $userConfig->value = $this->getId();
289
290 1
            if (!$userConfig->save()) {
291
                throw new Exception((string)current($userConfig->getMessages()));
292
            }
293
        }
294
295
        /**
296
         * @var CompaniesBranches
297
         */
298 3
        $branch = new CompaniesBranches();
299 3
        $branch->companies_id = $this->getId();
300 3
        $branch->users_id = $this->user->getId();
301 3
        $branch->name = 'Default';
302 3
        $branch->is_default = 1;
303 3
        $branch->description = '';
304 3
        if (!$branch->save()) {
305
            throw new ServerErrorHttpException((string)current($branch->getMessages()));
306
        }
307
308
        //look for the default plan for this app
309 3
        $companyApps = new UserCompanyApps();
310 3
        $companyApps->companies_id = $this->getId();
311 3
        $companyApps->apps_id = $this->di->getApp()->getId();
312 3
        $companyApps->subscriptions_id = 0;
313
314
        //we need to assign this company to a plan
315 3
        if (empty($this->appPlanId)) {
316 3
            $plan = AppsPlans::getDefaultPlan();
317 3
            $companyApps->stripe_id = $plan->stripe_id;
318
        }
319
320 3
        $companyApps->created_at = date('Y-m-d H:i:s');
321 3
        $companyApps->is_deleted = 0;
322
323 3
        if (!$companyApps->save()) {
324
            throw new ServerErrorHttpException((string)current($companyApps->getMessages()));
325
        }
326 3
    }
327
328
    /**
329
     * Get the default company the users has selected
330
     *
331
     * @param  Users  $user
332
     * @return Companies
333
     */
334
    public static function getDefaultByUser(Users $user): Companies
335
    {
336
        //verify the user has a default company
337
        $defaultCompany = UserConfig::findFirst([
338
            'conditions' => 'users_id = ?0 and name = ?1',
339
            'bind' => [$user->getId(), self::DEFAULT_COMPANY],
340
        ]);
341
342
        //found it
343
        if (is_object($defaultCompany)) {
344
            return self::findFirst($defaultCompany->value);
345
        }
346
347
        //second try
348
        $defaultCompany = UsersAssociatedCompany::findFirst([
349
            'conditions' => 'users_id = ?0 and user_active =?1',
350
            'bind' => [$user->getId(), 1],
351
        ]);
352
353
        if (is_object($defaultCompany)) {
354
            return self::findFirst($defaultCompany->companies_id);
355
        }
356
357
        throw new Exception(_("User doesn't have an active company"));
358
    }
359
360
    /**
361
     * After the model was update we need to update its custom fields
362
     *
363
     * @return void
364
     */
365 2
    public function afterUpdate()
366
    {
367
        //only clean and change custom fields if they are been sent
368 2
        if (!empty($this->customFields)) {
369
            //replace old custom with new
370 1
            $allCustomFields = $this->getAllCustomFields();
371 1
            if (is_array($allCustomFields)) {
372 1
                foreach ($this->customFields as $key => $value) {
373 1
                    $allCustomFields[$key] = $value;
374
                }
375
            }
376
377 1
            if (!empty($allCustomFields)) {
378
                //set
379 1
                $this->setCustomFields($allCustomFields);
380
                //clean old
381 1
                $this->cleanCustomFields($this->getId());
382
                //save new
383 1
                $this->saveCustomFields();
384
            }
385
        }
386 2
    }
387
}
388