Test Failed
Pull Request — master (#21)
by Maximo
04:17
created

AppsPlansController::onConstruct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 0
dl 0
loc 6
ccs 5
cts 5
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gewaer\Api\Controllers;
6
7
use Gewaer\Models\AppsPlans;
8
use Gewaer\Exception\UnauthorizedHttpException;
9
use Gewaer\Exception\NotFoundHttpException;
10
use Stripe\Token as StripeToken;
11
use Phalcon\Http\Response;
12
use Phalcon\Validation;
13
use Phalcon\Validation\Validator\PresenceOf;
14
use Gewaer\Exception\UnprocessableEntityHttpException;
15
use Phalcon\Cashier\Subscription;
16
use Baka\Auth\Models\UserCompanyApps;
17
18
/**
19
 * Class LanguagesController
20
 *
21
 * @package Gewaer\Api\Controllers
22
 *
23
 * @property Users $userData
24
 * @property Request $request
25
 * @property Config $config
26
 * @property Apps $app
27
 * @property \Phalcon\Db\Adapter\Pdo\Mysql $db
28
 */
29
class AppsPlansController extends BaseController
30
{
31
    /*
32
     * fields we accept to create
33
     *
34
     * @var array
35
     */
36
    protected $createFields = [];
37
38
    /*
39
     * fields we accept to create
40
     *
41
     * @var array
42
     */
43
    protected $updateFields = [];
44
45
    /**
46
     * set objects
47
     *
48
     * @return void
49
     */
50 4
    public function onConstruct()
51
    {
52 4
        $this->model = new AppsPlans();
53 4
        $this->additionalSearchFields = [
54 4
            ['is_deleted', ':', 0],
55 4
            ['apps_id', ':', $this->app->getId()],
56
        ];
57 4
    }
58
59
    /**
60
     * Given the app plan stripe id , subscribe the current company to this aps
61
     *
62
     * @return Response
63
     */
64 1
    public function create(): Response
65
    {
66 1
        if (!$this->userData->hasRole('Default.Admins')) {
67 1
            throw new UnauthorizedHttpException(_('You dont have permission to subscribe this apps'));
68
        }
69
70
        //Ok let validate user password
71
        $validation = new Validation();
72
        $validation->add('stripe_id', new PresenceOf(['message' => _('The plan is required.')]));
73
        $validation->add('number', new PresenceOf(['message' => _('Credit Card Number is required.')]));
74
        $validation->add('exp_month', new PresenceOf(['message' => _('Credit Card Number is required.')]));
75
        $validation->add('exp_year', new PresenceOf(['message' => _('Credit Card Number is required.')]));
76
        $validation->add('cvc', new PresenceOf(['message' => _('CVC is required.')]));
77
78
        //validate this form for password
79
        $messages = $validation->validate($this->request->getPost());
80
        if (count($messages)) {
81
            foreach ($messages as $message) {
82
                throw new UnprocessableEntityHttpException($message);
83
            }
84
        }
85
86
        $stripeId = $this->request->getPost('stripe_id');
87
        $company = $this->userData->defaultCompany;
88
        $cardNumber = $this->request->getPost('number');
89
        $expMonth = $this->request->getPost('exp_month');
90
        $expYear = $this->request->getPost('exp_year');
91
        $cvc = $this->request->getPost('cvc');
92
93
        $appPlan = $this->model->findFirstByStripeId($stripeId);
94
95
        if (!is_object($appPlan)) {
96
            throw new NotFoundHttpException(_('This plan doesnt exist'));
97
        }
98
99
        $userSubscription = Subscription::findFirst([
100
            'conditions' => 'user_id = ?0 and company_id = ?1 and apps_id = ?2 and is_deleted  = 0',
101
            'bind' => [$this->userData->getId(), $this->userData->default_company, $this->app->getId()]
102
        ]);
103
104
        if (is_object($userSubscription)) {
105
            throw new NotFoundHttpException(_('You are already subscribed to this plan'));
106
        }
107
108
        $card = StripeToken::create([
109
            'card' => [
110
                'number' => $cardNumber,
111
                'exp_month' => $expMonth,
112
                'exp_year' => $expYear,
113
                'cvc' => $cvc,
114
            ],
115
        ], [
116
            'api_key' => $this->config->stripe->secret
117
        ])->id;
118
119
        $this->db->begin();
120
121
        //if fails it will throw exception
122
        if ($appPlan->free_trial_dates == 0) {
123
            $this->userData->newSubscription($appPlan->name, $appPlan->stripe_id, $company, $this->app)->create($card);
124
        } else {
125
            $this->userData->newSubscription($appPlan->name, $appPlan->stripe_id, $company, $this->app)->trialDays($appPlan->free_trial_dates)->create($card);
126
        }
127
128
        //update company app
129
        $companyApp = UserCompanyApps::findFirst([
130
            'conditions' => 'company_id = ?0 and apps_id = ?1',
131
            'bind' => [$this->userData->defaultCompany->getId(), $this->app->getId()]
132
        ]);
133
134
        //update the company app to the new plan
135
        if (is_object($companyApp)) {
136
            $subscription = $this->userData->subscription($appPlan->stripe_plan);
137
            $companyApp->strip_id = $stripeId;
138
            $companyApp->subscriptions_id = $subscription->getId();
139
            if (!$companyApp->update()) {
140
                $this->db->rollback();
141
                throw new UnprocessableEntityHttpException((string) current($companyApp->getMessages()));
142
            }
143
144
            //update the subscription with the plan
145
            $subscription->apps_plans_id = $appPlan->getId();
146
            if (!$subscription->update()) {
147
                $this->db->rollback();
148
                throw new UnprocessableEntityHttpException((string) current($subscription->getMessages()));
149
            }
150
        }
151
152
        $this->db->commit();
153
154
        //sucess
155
        return $this->response($appPlan);
156
    }
157
158
    /**
159
     * Update a given subscription
160
     *
161
     * @param string $stripeId
162
     * @return Response
163
     */
164 2
    public function edit($stripeId) : Response
165
    {
166 2
        $appPlan = $this->model->findFirstByStripeId($stripeId);
167
168 2
        if (!is_object($appPlan)) {
169 1
            throw new NotFoundHttpException(_('This plan doesnt exist'));
170
        }
171
172 1
        $userSubscription = Subscription::findFirst([
173 1
            'conditions' => 'user_id = ?0 and company_id = ?1 and apps_id = ?2 and is_deleted  = 0',
174 1
            'bind' => [$this->userData->getId(), $this->userData->default_company, $this->app->getId()]
175
        ]);
176
177 1
        if (!is_object($userSubscription)) {
178 1
            throw new NotFoundHttpException(_('No current subscription found'));
179
        }
180
181
        $this->db->begin();
182
183
        $subscription = $this->userData->subscription($userSubscription->name)->swap($stripeId);
184
185
        //update company app
186
        $companyApp = UserCompanyApps::findFirst([
187
            'conditions' => 'company_id = ?0 and apps_id = ?1',
188
            'bind' => [$this->userData->defaultCompany->getId(), $this->app->getId()]
189
        ]);
190
191
        //update the company app to the new plan
192
        if (is_object($companyApp)) {
193
            $subscription->name = $stripeId;
194
            $subscription->save();
195
196
            $companyApp->strip_id = $stripeId;
197
            $companyApp->subscriptions_id = $subscription->getId();
198
            if (!$companyApp->update()) {
199
                $this->db->rollback();
200
                throw new UnprocessableEntityHttpException((string) current($companyApp->getMessages()));
201
            }
202
203
            //update the subscription with the plan
204
205
            $subscription->apps_plans_id = $appPlan->getId();
206
            if (!$subscription->update()) {
207
                $this->db->rollback();
208
209
                throw new UnprocessableEntityHttpException((string) current($subscription->getMessages()));
210
            }
211
        }
212
213
        $this->db->commit();
214
215
        //return the new subscription plan
216
        return $this->response($appPlan);
217
    }
218
219
    /**
220
     * Cancel a given subscription
221
     *
222
     * @param string $stripeId
223
     * @return Response
224
     */
225 1
    public function delete($stripeId): Response
226
    {
227 1
        $appPlan = $this->model->findFirstByStripeId($stripeId);
228
229 1
        if (!is_object($appPlan)) {
230
            throw new NotFoundHttpException(_('This plan doesnt exist'));
231
        }
232
233 1
        $userSubscription = Subscription::findFirst([
234 1
            'conditions' => 'user_id = ?0 and company_id = ?1 and apps_id = ?2 and is_deleted  = 0',
235 1
            'bind' => [$this->userData->getId(), $this->userData->default_company, $this->app->getId()]
236
        ]);
237
238 1
        if (!is_object($userSubscription)) {
239 1
            throw new NotFoundHttpException(_('No current subscription found'));
240
        }
241
242
        $subscription = $this->userData->subscription($userSubscription->name)->cancel();
243
        $subscription->is_deleted = 1;
244
        $subscription->update();
245
246
        return $this->response($appPlan);
247
    }
248
}
249