Failed Conditions
Push — master ( 214663...e72ee0 )
by Maximo
01:01 queued 10s
created

AppsPlansController::reactivateSubscription()   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 10
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
     * Update a given subscription.
64
     *
65
     * @param string $stripeId
66
     * @return Response
67
     */
68
    public function edit($stripeId) : Response
69
    {
70
        $appPlan = $this->model->findFirstByStripeId($stripeId);
71
72
        if (!is_object($appPlan)) {
73
            throw new NotFoundException(_('This plan doesnt exist'));
74
        }
75
76
        $userSubscription = CanvasSubscription::getActiveForThisApp();
77
78
        $this->db->begin();
79
80
        $subscription = $this->userData->subscription($userSubscription->name);
81
82
        if ($subscription->onTrial()) {
83
            $subscription->name = $appPlan->name;
84
            $subscription->stripe_plan = $appPlan->stripe_plan;
85
        } else {
86
            $subscription->swap($stripeId);
87
        }
88
89
        //update company app
90
        $companyApp = UserCompanyApps::getCurrentApp();
91
92
        //update the company app to the new plan
93
        if (is_object($companyApp)) {
94
            $subscription->name = $stripeId;
95
            $subscription->save();
96
97
            $companyApp->stripe_id = $stripeId;
98
            $companyApp->subscriptions_id = $subscription->getId();
99
            if (!$companyApp->update()) {
100
                $this->db->rollback();
101
                throw new UnprocessableEntityException((string) current($companyApp->getMessages()));
102
            }
103
104
            //update the subscription with the plan
105
            $subscription->apps_plans_id = $appPlan->getId();
106
            if (!$subscription->update()) {
107
                $this->db->rollback();
108
109
                throw new UnprocessableEntityException((string) current($subscription->getMessages()));
110
            }
111
        }
112
113
        $this->db->commit();
114
115
        //return the new subscription plan
116
        return $this->response($appPlan);
117
    }
118
119
    /**
120
     * Cancel a given subscription.
121
     *
122
     * @param string $stripeId
123
     * @return Response
124
     */
125
    public function delete($stripeId): Response
126
    {
127
        $appPlan = $this->model->findFirstByStripeId($stripeId);
128
129
        if (!is_object($appPlan)) {
130
            throw new NotFoundException(_('This plan doesnt exist'));
131
        }
132
133
        $subscription = CanvasSubscription::getActiveSubscription();
134
135
        //if on trial you can cancel without going to stripe
136
        if (!$subscription->onTrial()) {
137
            $subscription->cancel();
138
        }
139
140
        $subscription->is_cancelled = 1;
141
        $subscription->update();
142
143
        return $this->response($appPlan);
144
    }
145
146
    /**
147
     * Reactivate a given subscription.
148
     *
149
     * @param string $stripeId
150
     * @return Response
151
     */
152
    public function reactivateSubscription($stripeId): Response
153
    {
154
        $appPlan = $this->model->findFirstByStripeId($stripeId);
155
156
        if (!is_object($appPlan)) {
157
            throw new NotFoundException(_('This plan doesnt exist'));
158
        }
159
160
        $subscription = CanvasSubscription::getActiveSubscription();
161
162
        //if on trial you can cancel without going to stripe
163
        if (!$subscription->onTrial()) {
164
            $subscription->reactivate();
165
        }
166
167
        $subscription->is_cancelled = 0;
168
        $subscription->update();
169
170
        return $this->response($appPlan);
171
    }
172
173
    /**
174
     * Update payment method.
175
     * @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...
176
     * @return Response
177
     */
178
    public function updatePaymentMethod(string $id): Response
179
    {
180
        if (empty($this->request->hasPut('card_token'))) {
181
            $validation = new CanvasValidation();
182
            $validation->add('card_number', new PresenceOf(['message' => _('Credit Card Number is required.')]));
183
            $validation->add('card_exp_month', new PresenceOf(['message' => _('Credit Card expiration month is required.')]));
184
            $validation->add('card_exp_year', new PresenceOf(['message' => _('Credit Card expiration year is required.')]));
185
            $validation->add('card_cvc', new PresenceOf(['message' => _('CVC is required.')]));
186
187
            //validate this form for password
188
            $validation->validate($this->request->getPut());
189
190
            $cardNumber = $this->request->getPut('card_number', 'string');
191
            $expMonth = $this->request->getPut('card_exp_month', 'string');
192
            $expYear = $this->request->getPut('card_exp_year', 'string');
193
            $cvc = $this->request->getPut('card_cvc', 'string');
194
195
            //Create a new card token
196
            $token = StripeToken::create([
197
                'card' => [
198
                    'number' => $cardNumber,
199
                    'exp_month' => $expMonth,
200
                    'exp_year' => $expYear,
201
                    'cvc' => $cvc,
202
                ],
203
            ], [
204
                'api_key' => $this->config->stripe->secret
205
            ])->id;
206
        } else {
207
            $token = $this->request->getPut('card_token');
208
        }
209
210
        $address = $this->request->getPut('address', 'string');
211
        $zipcode = $this->request->getPut('zipcode', 'string');
212
213
        //update the default company info
214
        $this->userData->getDefaultCompany()->address = $address;
215
        $this->userData->getDefaultCompany()->zipcode = $zipcode;
216
        $this->userData->getDefaultCompany()->update();
217
218
        $customerId = $this->userData->stripe_id;
219
220
        //Update default payment method with new card.
221
        $stripeCustomer = $this->userData->updatePaymentMethod($customerId, $token);
222
223
        $subscription = CanvasSubscription::getActiveForThisApp();
224
225
        //not valid? ok then lets charge the credit card to active your subscription
226
        if (!$subscription->valid()) {
227
            $subscription->activate();
228
        }
229
230
        if (is_object($stripeCustomer) && $stripeCustomer instanceof StripeCustomer) {
231
            return $this->response($subscription);
232
        }
233
        return $this->response('Card could not be updated');
234
    }
235
}
236