Failed Conditions
Pull Request — master (#72)
by Rafael
05:31
created

library/Models/Companies.php (1 issue)

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