Completed
Push — development ( 877883...280d38 )
by Ashutosh
10:04
created

BaseOrderController::addOrderInvoiceRelation()   A

Complexity

Conditions 2
Paths 3

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 9
rs 10
c 0
b 0
f 0
cc 2
nc 3
nop 2
1
<?php
2
3
namespace App\Http\Controllers\Order;
4
5
use App\Http\Controllers\License\LicensePermissionsController;
6
use App\Model\Common\StatusSetting;
7
use App\Model\Order\Order;
8
use App\Model\Product\Product;
9
use App\Traits\Order\UpdateDates;
10
use App\User;
11
use Bugsnag;
12
use Crypt;
13
use DateTime;
14
use DateTimeZone;
15
16
class BaseOrderController extends ExtendedOrderController
17
{
18
    use UpdateDates;
0 ignored issues
show
introduced by
The trait App\Traits\Order\UpdateDates requires some properties which are not provided by App\Http\Controllers\Order\BaseOrderController: $number, $update_ends_at, $support_ends_at, $serial_key, $product, $ends_at
Loading history...
19
20
    public function getEndDate($model)
21
    {
22
        $end = '--';
23
        $ends = $model->subscription()->first();
24
        if ($ends) {
25
            if (strtotime($ends->update_ends_at) > 1) {
26
                $date1 = new DateTime($ends->update_ends_at);
27
                $tz = \Auth::user()->timezone()->first()->name;
28
                $date1->setTimezone(new DateTimeZone($tz));
29
                $end = $date1->format('M j, Y, g:i a ');
30
            }
31
        }
32
33
        return $end;
34
    }
35
36
    public function getUrl($model, $status, $sub)
37
    {
38
        $url = '';
39
        if ($status == 'success') {
40
            if ($sub) {
41
                $url = '<a href='.url('renew/'.$sub->id)." 
42
                class='btn btn-sm btn-primary btn-xs'><i class='fa fa-refresh'
43
                 style='color:white;'> </i>&nbsp;&nbsp;Renew</a>";
44
            }
45
        }
46
47
        return '<p><a href='.url('orders/'.$model->id)." 
48
        class='btn btn-sm btn-primary btn-xs'><i class='fa fa-eye'
49
         style='color:white;'> </i>&nbsp;&nbsp;View</a> $url</p>";
50
    }
51
52
    /**
53
     * inserting the values to orders table.
54
     *
55
     * @param type $invoiceid
56
     * @param type $order_status
57
     *
58
     * @throws \Exception
59
     *
60
     * @return string
61
     */
62
    public function executeOrder($invoiceid, $order_status = 'executed')
63
    {
64
        try {
65
            $invoice_items = $this->invoice_items->where('invoice_id', $invoiceid)->get();
66
            $user_id = $this->invoice->find($invoiceid)->user_id;
67
            if (count($invoice_items) > 0) {
68
                foreach ($invoice_items as $item) {
69
                    if ($item) {
70
                        $items = $this->getIfItemPresent($item, $invoiceid, $user_id, $order_status);
71
                    }
72
                }
73
            }
74
75
            return 'success';
76
        } catch (\Exception $ex) {
77
            Bugsnag::notifyException($ex);
78
79
            throw new \Exception($ex->getMessage());
80
        }
81
    }
82
83
    public function getIfItemPresent($item, $invoiceid, $user_id, $order_status)
84
    {
85
        try {
86
            $product = $this->product->where('name', $item->product_name)->first()->id;
87
            $version = $this->product->where('name', $item->product_name)->first()->version;
88
            if ($version == null) {
89
                //Get Version from Product Upload Table
90
                $version = $this->product_upload->where('product_id', $product)->pluck('version')->first();
91
            }
92
            $serial_key = $this->generateSerialKey($product, $item->agents); //Send Product Id and Agents to generate Serial Key
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 128 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
93
            $domain = $item->domain;
94
            $plan_id = $this->plan($item->id);
95
            $order = $this->order->create([
96
97
            'invoice_id'      => $invoiceid,
98
            'invoice_item_id' => $item->id,
99
            'client'          => $user_id,
100
            'order_status'    => $order_status,
101
            'serial_key'      => Crypt::encrypt($serial_key),
102
            'product'         => $product,
103
            'price_override'  => $item->subtotal,
104
            'qty'             => $item->quantity,
105
            'domain'          => $domain,
106
            'number'          => $this->generateNumber(),
107
            ]);
108
            $this->addOrderInvoiceRelation($invoiceid, $order->id);
109
            if ($planid != 0) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $planid does not exist. Did you maybe mean $plan_id?
Loading history...
110
            $this->addSubscription($order->id, $plan_id, $version, $product, $serial_key);
111
           }
112
            $this->sendOrderMail($user_id, $order->id, $item->id);
113
            //Update Subscriber To Mailchimp
114
            $mailchimpStatus = StatusSetting::pluck('mailchimp_status')->first();
115
            if ($mailchimpStatus == 1) {
116
            $this->addtoMailchimp($product, $user_id, $item);
117
        }
118
        } catch (\Exception $ex) {
119
            Bugsnag::notifyException($ex);
120
            app('log')->error($ex->getMessage());
121
            throw new \Exception($ex->getMessage());
122
        }
123
    }
124
125
    public function addToMailchimp($product, $user_id, $item)
126
    {
127
        try {
128
                $mailchimp = new \App\Http\Controllers\Common\MailChimpController();
129
                $email = User::where('id', $user_id)->pluck('email')->first();
130
                if ($item->subtotal > 0) {
131
                    $r = $mailchimp->updateSubscriberForPaidProduct($email, $product);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $r is correct as $mailchimp->updateSubscr...oduct($email, $product) targeting App\Http\Controllers\Com...scriberForPaidProduct() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
132
                } else {
133
                    $r = $mailchimp->updateSubscriberForFreeProduct($email, $product);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $r is correct as $mailchimp->updateSubscr...oduct($email, $product) targeting App\Http\Controllers\Com...scriberForFreeProduct() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
134
                }
135
            
136
        } catch (\Exception $ex) {
137
            Bugsnag::notifyException($ex);
138
            app('log')->info($ex->getMessage());
139
            throw new \Exception('User not Updated to Mailchimp');
140
        }
141
    }
142
143
    
144
145
    /**
146
     * inserting the values to subscription table.
147
     *
148
     * @param int    $orderid
149
     * @param int    $planid
150
     * @param string $version
151
     * @param int    $product
152
     * @param string $serial_key
153
     *
154
     * @throws \Exception
155
     *
156
     * @author Ashutosh Pathak <[email protected]>
157
     */
158
    public function addSubscription($orderid, $planid, $version, $product, $serial_key)
159
    {
160
        try {
161
            $permissions = LicensePermissionsController::getPermissionsForProduct($product);
162
            if ($version == null) {
163
                $version = '';
164
            }
165
                $days = $this->plan->where('id', $planid)->first()->days;
166
                $licenseExpiry = $this->getLicenseExpiryDate($permissions['generateLicenseExpiryDate'], $days);
167
                $updatesExpiry = $this->getUpdatesExpiryDate($permissions['generateUpdatesxpiryDate'], $days);
168
                $supportExpiry = $this->getSupportExpiryDate($permissions['generateSupportExpiryDate'], $days);
169
                $user_id = $this->order->find($orderid)->client;
170
                $this->subscription->create(['user_id' => $user_id,
171
                'plan_id'                              => $planid, 'order_id' => $orderid, 'update_ends_at' =>$updatesExpiry, 'ends_at' => $licenseExpiry, 'support_ends_at'=>$supportExpiry, 'version'=> $version, 'product_id' =>$product, ]);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 240 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
172
            
173
            $licenseStatus = StatusSetting::pluck('license_status')->first();
174
            if ($licenseStatus == 1) {
175
                $cont = new \App\Http\Controllers\License\LicenseController();
176
                $createNewLicense = $cont->createNewLicene($orderid, $product, $user_id, $licenseExpiry, $updatesExpiry, $supportExpiry, $serial_key);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $createNewLicense is correct as $cont->createNewLicene($...ortExpiry, $serial_key) targeting App\Http\Controllers\Lic...ller::createNewLicene() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 150 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
177
            }
178
        } catch (\Exception $ex) {
179
            Bugsnag::notifyException($ex);
180
            app('log')->error($ex->getMessage());
181
182
            throw new \Exception('Can not Generate Subscription');
183
        }
184
    }
185
186
    /**
187
     *  Get the Expiry Date for License.
188
     *
189
     * @param bool $permissions [Whether Permissons for generating License Expiry Date are there or not]
190
     * @param int  $days        [No of days that would get addeed to the current date ]
191
     *
192
     * @return string [The final License Expiry date that is generated]
193
     */
194
    protected function getLicenseExpiryDate(bool $permissions, int $days)
195
    {
196
        $ends_at = '';
197
        if ($days > 0 && $permissions == 1) {
198
            $dt = \Carbon\Carbon::now();
199
            $ends_at = $dt->addDays($days);
200
        }
201
202
        return $ends_at;
203
    }
204
205
    /**
206
     *  Get the Expiry Date for Updates.
207
     *
208
     * @param bool $permissions [Whether Permissons for generating Updates Expiry Date are there or not]
209
     * @param int  $days        [No of days that would get added to the current date ]
210
     *
211
     * @return string [The final Updates Expiry date that is generated]
212
     */
213
    protected function getUpdatesExpiryDate(bool $permissions, int $days)
214
    {
215
        $update_ends_at = '';
216
        if ($days > 0 && $permissions == 1) {
217
            $dt = \Carbon\Carbon::now();
218
            $update_ends_at = $dt->addDays($days);
219
        }
220
221
        return $update_ends_at;
222
    }
223
224
    /**
225
     *  Get the Expiry Date for Support.
226
     *
227
     * @param bool $permissions [Whether Permissons for generating Updates Expiry Date are there or not]
228
     * @param int  $days        [No of days that would get added to the current date ]
229
     *
230
     * @return string [The final Suport Expiry date that is generated]
231
     */
232
    protected function getSupportExpiryDate(bool $permissions, int $days)
233
    {
234
        $support_ends_at = '';
235
        if ($days > 0 && $permissions == 1) {
236
            $dt = \Carbon\Carbon::now();
237
            $support_ends_at = $dt->addDays($days);
238
        }
239
240
        return $support_ends_at;
241
    }
242
243
    public function addOrderInvoiceRelation($invoiceid, $orderid)
244
    {
245
        try {
246
            $relation = new \App\Model\Order\OrderInvoiceRelation();
247
            $relation->create(['order_id' => $orderid, 'invoice_id' => $invoiceid]);
248
        } catch (\Exception $ex) {
249
            Bugsnag::notifyException($ex);
250
251
            throw new \Exception($ex->getMessage());
252
        }
253
    }
254
255
    public function sendOrderMail($userid, $orderid, $itemid)
256
    {
257
        //order
258
        $order = $this->order->find($orderid);
259
        //product
260
        $product = $this->product($itemid);
0 ignored issues
show
Bug introduced by
The call to App\Http\Controllers\Ord...erController::product() has too few arguments starting with join. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

260
        /** @scrutinizer ignore-call */ 
261
        $product = $this->product($itemid);

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
261
        //user
262
        $productId = Product::where('name', $product)->pluck('id')->first();
263
        $users = new User();
264
        $user = $users->find($userid);
265
        //check in the settings
266
        $settings = new \App\Model\Common\Setting();
267
        $setting = $settings->where('id', 1)->first();
268
        $orders = new Order();
269
        $order = $orders->where('id', $orderid)->first();
270
        $invoice = $this->invoice->find($order->invoice_id);
271
        $number = $invoice->number;
272
        $downloadurl = '';
273
        if ($user && $order->order_status == 'Executed') {
274
            $downloadurl = url('product/'.'download'.'/'.$productId.'/'.$number);
275
        }
276
        // $downloadurl = $this->downloadUrl($userid, $orderid,$productId);
277
        $myaccounturl = url('my-order/'.$orderid);
278
        $invoiceurl = $this->invoiceUrl($orderid);
279
        //template
280
        $mail = $this->getMail($setting, $user, $downloadurl, $invoiceurl, $order, $product, $orderid, $myaccounturl);
281
    }
282
283
    public function getMail($setting, $user, $downloadurl, $invoiceurl, $order, $product, $orderid, $myaccounturl)
284
    {
285
        $templates = new \App\Model\Common\Template();
286
        $temp_id = $setting->order_mail;
287
        $template = $templates->where('id', $temp_id)->first();
288
        $knowledgeBaseUrl = $setting->company_url;
289
        $from = $setting->email;
290
        $to = $user->email;
291
        $subject = $template->name;
292
        $data = $template->data;
293
        $replace = [
294
            'name'          => $user->first_name.' '.$user->last_name,
295
             'serialkeyurl' => $myaccounturl,
296
            'downloadurl'   => $downloadurl,
297
            'invoiceurl'    => $invoiceurl,
298
            'product'       => $product,
299
            'number'        => $order->number,
300
            'expiry'        => $this->expiry($orderid),
0 ignored issues
show
Bug introduced by
The call to App\Http\Controllers\Ord...derController::expiry() has too few arguments starting with expiry. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

300
            'expiry'        => $this->/** @scrutinizer ignore-call */ expiry($orderid),

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
301
            'url'           => $this->renew($orderid),
302
            'knowledge_base'=> $knowledgeBaseUrl,
303
304
            ];
305
        $type = '';
306
        if ($template) {
307
            $type_id = $template->type;
308
            $temp_type = new \App\Model\Common\TemplateType();
309
            $type = $temp_type->where('id', $type_id)->first()->name;
310
        }
311
        $templateController = new \App\Http\Controllers\Common\TemplateController();
312
        $mail = $templateController->mailing($from, $to, $data, $subject, $replace, $type);
313
314
        return $mail;
315
    }
316
317
    public function invoiceUrl($orderid)
318
    {
319
        $orders = new Order();
320
        $order = $orders->where('id', $orderid)->first();
321
        $invoiceid = $order->invoice_id;
322
        $url = url('my-invoice/'.$invoiceid);
323
324
        return $url;
325
    }
326
327
    /**
328
     * get the price of a product by id.
329
     *
330
     * @param type $product_id
331
     *
332
     * @throws \Exception
333
     *
334
     * @return type collection
335
     */
336
    public function getPrice($product_id)
337
    {
338
        try {
339
            return $this->price->where('product_id', $product_id)->first();
340
        } catch (\Exception $ex) {
341
            Bugsnag::notifyException($ex);
342
343
            throw new \Exception($ex->getMessage());
344
        }
345
    }
346
347
    public function downloadUrl($userid, $orderid)
348
    {
349
        $orders = new Order();
350
        $order = $orders->where('id', $orderid)->first();
351
        $invoice = $this->invoice->find($order->invoice_id);
352
        $number = $invoice->number;
353
        $url = url('download/'.$userid.'/'.$number);
354
355
        return $url;
356
    }
357
}
358