Failed Conditions
Pull Request — master (#271)
by Rafael
04:04
created

AppsPlansController::delete()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 1
dl 0
loc 20
ccs 0
cts 11
cp 0
crap 12
rs 9.6
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Canvas\Api\Controllers;
6
7
use Canvas\Models\AppsPlans;
8
use Stripe\Token as StripeToken;
9
use Phalcon\Http\Response;
10
use Stripe\Customer as StripeCustomer;
11
use Phalcon\Validation\Validator\PresenceOf;
12
use Canvas\Http\Exception\NotFoundException;
13
use Canvas\Http\Exception\UnauthorizedException;
14
use Canvas\Http\Exception\UnprocessableEntityException;
15
use Canvas\Models\Subscription as CanvasSubscription;
16
use Phalcon\Cashier\Subscription;
17
use Canvas\Models\UserCompanyApps;
18
use function Canvas\Core\paymentGatewayIsActive;
19
use Canvas\Validation as CanvasValidation;
20
21
/**
22
 * Class LanguagesController.
23
 *
24
 * @package Canvas\Api\Controllers
25
 *
26
 * @property Users $userData
27
 * @property Request $request
28
 * @property Config $config
29
 * @property Apps $app
30
 * @property \Phalcon\Db\Adapter\Pdo\Mysql $db
31
 */
32
class AppsPlansController extends BaseController
33
{
34
    /*
35
     * fields we accept to create
36
     *
37
     * @var array
38
     */
39
    protected $createFields = [];
40
41
    /*
42
     * fields we accept to create
43
     *
44
     * @var array
45
     */
46
    protected $updateFields = [];
47
48
    /**
49
     * set objects.
50
     *
51
     * @return void
52
     */
53
    public function onConstruct()
54
    {
55
        $this->model = new AppsPlans();
56
        $this->additionalSearchFields = [
57
            ['is_deleted', ':', '0'],
58
            ['apps_id', ':', $this->app->getId()],
59
        ];
60
    }
61
62
    // /**
63
    //  * Given the app plan stripe id , subscribe the current company to this aps.
64
    //  *
65
    //  * @return Response
66
    //  */
67
    // public function create(): Response
68
    // {
69
    //     if (!$this->userData->hasRole('Default.Admins')) {
70
    //         throw new UnauthorizedException(_('You dont have permission to subscribe this apps'));
71
    //     }
72
73
    //     //Ok let validate user password
74
    //     $validation = new CanvasValidation();
75
    //     $validation->add('stripe_id', new PresenceOf(['message' => _('The plan is required.')]));
76
    //     $validation->add('card_number', new PresenceOf(['message' => _('Credit Card Number is required.')]));
77
    //     $validation->add('card_exp_month', new PresenceOf(['message' => _('Credit Card expiration month is required.')]));
78
    //     $validation->add('card_exp_year', new PresenceOf(['message' => _('Credit Card expiration year is required.')]));
79
    //     $validation->add('card_cvc', new PresenceOf(['message' => _('CVC is required.')]));
80
81
    //     //validate this form for password
82
    //     $validation->validate($this->request->getPost());
83
84
    //     $stripeId = $this->request->getPost('stripe_id');
85
    //     $company = $this->userData->getDefaultCompany();
86
    //     $cardNumber = $this->request->getPost('card_number');
87
    //     $expMonth = $this->request->getPost('card_exp_month');
88
    //     $expYear = $this->request->getPost('card_exp_year');
89
    //     $cvc = $this->request->getPost('card_cvc');
90
91
    //     $appPlan = $this->model->findFirstByStripeId($stripeId);
92
93
    //     if (!$appPlan) {
94
    //         throw new NotFoundException(_('This plan doesnt exist'));
95
    //     }
96
97
    //     $userSubscription = CanvasSubscription::getActiveForThisApp();
98
99
    //     //we can only run stripe paymenta gateway if we have the key
100
    //     if (paymentGatewayIsActive()) {
101
    //         $card = StripeToken::create([
102
    //             'card' => [
103
    //                 'number' => $cardNumber,
104
    //                 'exp_month' => $expMonth,
105
    //                 'exp_year' => $expYear,
106
    //                 'cvc' => $cvc,
107
    //             ],
108
    //         ], [
109
    //             'api_key' => $this->config->stripe->secret
110
    //         ])->id;
111
112
    //         $this->db->begin();
113
114
    //         if ($appPlan->free_trial_dates == 0) {
115
    //             $this->userData
116
    //                 ->newSubscription($appPlan->name, $appPlan->stripe_id, $company, $this->app)
117
    //                 ->create($card);
118
    //         } else {
119
    //             $this->userData
120
    //                 ->newSubscription($appPlan->name, $appPlan->stripe_id, $company, $this->app)
121
    //                 ->trialDays($appPlan->free_trial_dates)
122
    //                 ->create($card);
123
    //         }
124
125
    //         //update company app
126
    //         $companyApp = UserCompanyApps::getCurrentApp();
127
128
    //         if ($userSubscription) {
129
    //             $userSubscription->stripe_id = $this->userData->active_subscription_id;
130
    //             if (!$userSubscription->update()) {
131
    //                 $this->db->rollback();
132
    //                 throw new UnprocessableEntityException((string) current($userSubscription->getMessages()));
133
    //             }
134
    //         }
135
136
    //         //update the company app to the new plan
137
    //         if ($companyApp) {
138
    //             $subscription = $this->userData->subscription($appPlan->stripe_plan);
139
    //             $companyApp->stripe_id = $stripeId;
140
    //             $companyApp->subscriptions_id = $subscription->getId();
141
142
    //             if (!$companyApp->update()) {
143
    //                 $this->db->rollback();
144
    //                 throw new UnprocessableEntityException((string) current($companyApp->getMessages()));
145
    //             }
146
147
    //             //update the subscription with the plan
148
    //             $subscription->apps_plans_id = $appPlan->getId();
149
    //             if (!$subscription->update()) {
150
    //                 $this->db->rollback();
151
    //                 throw new UnprocessableEntityException((string) current($subscription->getMessages()));
152
    //             }
153
    //         }
154
155
    //         $this->db->commit();
156
    //     }
157
158
    //     //sucess
159
    //     return $this->response($appPlan);
160
    // }
161
162
    /**
163
     * Update a given subscription.
164
     *
165
     * @param string $stripeId
166
     * @return Response
167
     */
168
    public function edit($stripeId) : Response
169
    {
170
        $appPlan = $this->model->findFirstByStripeId($stripeId);
171
172
        if (!is_object($appPlan)) {
173
            throw new NotFoundException(_('This plan doesnt exist'));
174
        }
175
176
        $userSubscription = CanvasSubscription::getActiveForThisApp();
177
178
        $this->db->begin();
179
180
        $subscription = $this->userData->subscription($userSubscription->name);
181
182
        if ($subscription->onTrial()) {
183
            $subscription->name = $appPlan->name;
184
            $subscription->stripe_plan = $appPlan->stripe_plan;
185
        } else {
186
            $subscription->swap($stripeId);
187
        }
188
189
        //update company app
190
        $companyApp = UserCompanyApps::getCurrentApp();
191
192
        //update the company app to the new plan
193
        if (is_object($companyApp)) {
194
            $subscription->name = $stripeId;
195
            $subscription->save();
196
197
            $companyApp->stripe_id = $stripeId;
198
            $companyApp->subscriptions_id = $subscription->getId();
199
            if (!$companyApp->update()) {
200
                $this->db->rollback();
201
                throw new UnprocessableEntityException((string) current($companyApp->getMessages()));
202
            }
203
204
            //update the subscription with the plan
205
            $subscription->apps_plans_id = $appPlan->getId();
206
            if (!$subscription->update()) {
207
                $this->db->rollback();
208
209
                throw new UnprocessableEntityException((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
    public function delete($stripeId): Response
226
    {
227
        $appPlan = $this->model->findFirstByStripeId($stripeId);
228
229
        if (!is_object($appPlan)) {
230
            throw new NotFoundException(_('This plan doesnt exist'));
231
        }
232
233
        $subscription = CanvasSubscription::getActiveSubscription();
234
235
        //if on trial you can cancel without going to stripe
236
        if (!$subscription->onTrial()) {
237
            $subscription->cancel();
238
        }
239
240
        $subscription->is_cancelled = 1;
241
        $subscription->update();
242
243
        return $this->response($appPlan);
244
    }
245
246
    /**
247
     * Reactivate a given subscription.
248
     *
249
     * @param string $stripeId
250
     * @return Response
251
     */
252
    public function reactivateSubscription($stripeId): Response
253
    {
254
        $appPlan = $this->model->findFirstByStripeId($stripeId);
255
256
        if (!is_object($appPlan)) {
257
            throw new NotFoundException(_('This plan doesnt exist'));
258
        }
259
260
        $subscription = CanvasSubscription::getActiveSubscription();
261
262
        //if on trial you can cancel without going to stripe
263
        if (!$subscription->onTrial()) {
264
            $subscription->reactivate();
265
        }
266
267
        $subscription->is_cancelled = 0;
268
        $subscription->update();
269
270
        return $this->response($appPlan);
271
    }
272
273
    /**
274
     * Update payment method.
275
     * @param integer $id
0 ignored issues
show
Documentation introduced by
Should the type for parameter $id not be string|integer?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
276
     * @return Response
277
     */
278
    public function updatePaymentMethod(string $id): Response
279
    {
280
        if (empty($this->request->hasPut('card_token'))) {
281
            $validation = new CanvasValidation();
282
            $validation->add('card_number', new PresenceOf(['message' => _('Credit Card Number is required.')]));
283
            $validation->add('card_exp_month', new PresenceOf(['message' => _('Credit Card expiration month is required.')]));
284
            $validation->add('card_exp_year', new PresenceOf(['message' => _('Credit Card expiration year is required.')]));
285
            $validation->add('card_cvc', new PresenceOf(['message' => _('CVC is required.')]));
286
287
            //validate this form for password
288
            $validation->validate($this->request->getPut());
289
290
            $cardNumber = $this->request->getPut('card_number', 'string');
291
            $expMonth = $this->request->getPut('card_exp_month', 'string');
292
            $expYear = $this->request->getPut('card_exp_year', 'string');
293
            $cvc = $this->request->getPut('card_cvc', 'string');
294
295
            //Create a new card token
296
            $token = StripeToken::create([
297
                'card' => [
298
                    'number' => $cardNumber,
299
                    'exp_month' => $expMonth,
300
                    'exp_year' => $expYear,
301
                    'cvc' => $cvc,
302
                ],
303
            ], [
304
                'api_key' => $this->config->stripe->secret
305
            ])->id;
306
        } else {
307
            $token = $this->request->getPut('card_token');
308
        }
309
310
        $address = $this->request->getPut('address', 'string');
311
        $zipcode = $this->request->getPut('zipcode', 'string');
312
313
        //update the default company info
314
        $this->userData->getDefaultCompany()->address = $address;
315
        $this->userData->getDefaultCompany()->zipcode = $zipcode;
316
        $this->userData->getDefaultCompany()->update();
317
318
        $customerId = $this->userData->stripe_id;
319
320
        //Update default payment method with new card.
321
        $stripeCustomer = $this->userData->updatePaymentMethod($customerId, $token);
322
323
        $subscription = CanvasSubscription::getActiveForThisApp();
324
325
        //not valid? ok then lets charge the credit card to active your subscription
326
        if (!$subscription->valid()) {
327
            $subscription->activate();
328
        }
329
330
        if (is_object($stripeCustomer) && $stripeCustomer instanceof StripeCustomer) {
331
            return $this->response($subscription);
332
        }
333
        return $this->response('Card could not be updated');
334
    }
335
}
336