Invoices.php
30.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
<?php
namespace App\Http\Controllers\Incomes;
use App\Events\InvoiceCreated;
use App\Events\InvoicePrinting;
use App\Events\InvoiceUpdated;
use App\Http\Controllers\Controller;
use App\Http\Requests\Income\Invoice as Request;
use App\Http\Requests\Income\InvoicePayment as PaymentRequest;
use App\Models\Banking\Account;
use App\Models\Common\Media;
use App\Models\Income\Customer;
use App\Models\Income\Invoice;
use App\Models\Income\InvoiceHistory;
use App\Models\Income\InvoiceItem;
use App\Models\Income\InvoiceTotal;
use App\Models\Income\InvoicePayment;
use App\Models\Income\InvoiceStatus;
use App\Models\Common\Item;
use App\Models\Setting\Category;
use App\Models\Setting\Currency;
use App\Models\Setting\Tax;
use App\Notifications\Income\Invoice as Notification;
use App\Notifications\Common\Item as ItemNotification;
use App\Traits\Currencies;
use App\Traits\DateTime;
use App\Traits\Incomes;
use App\Traits\Uploads;
use App\Utilities\Import;
use App\Utilities\ImportFile;
use App\Utilities\Modules;
use Date;
use File;
use Illuminate\Http\Request as ItemRequest;
use Image;
use Storage;
class Invoices extends Controller
{
use DateTime, Currencies, Incomes, Uploads;
/**
* Display a listing of the resource.
*
* @return Response
*/
public function index()
{
$invoices = Invoice::with(['customer', 'status', 'items', 'payments', 'histories'])->collect(['invoice_number'=> 'desc']);
$customers = collect(Customer::enabled()->orderBy('name')->pluck('name', 'id'))
->prepend(trans('general.all_type', ['type' => trans_choice('general.customers', 2)]), '');
$status = collect(InvoiceStatus::all()->pluck('name', 'code'))
->prepend(trans('general.all_type', ['type' => trans_choice('general.statuses', 2)]), '');
return view('incomes.invoices.index', compact('invoices', 'customers', 'status'));
}
/**
* Show the form for viewing the specified resource.
*
* @param Invoice $invoice
*
* @return Response
*/
public function show(Invoice $invoice)
{
$paid = 0;
// Get Invoice Payments
if ($invoice->payments->count()) {
$_currencies = Currency::enabled()->pluck('rate', 'code')->toArray();
foreach ($invoice->payments as $item) {
$default_amount = $item->amount;
if ($invoice->currency_code == $item->currency_code) {
$amount = (double)$default_amount;
} else {
$default_amount_model = new InvoicePayment();
$default_amount_model->default_currency_code = $invoice->currency_code;
$default_amount_model->amount = $default_amount;
$default_amount_model->currency_code = $item->currency_code;
$default_amount_model->currency_rate = $_currencies[$item->currency_code];
$default_amount = (double) $default_amount_model->getDivideConvertedAmount();
$convert_amount = new InvoicePayment();
$convert_amount->default_currency_code = $item->currency_code;
$convert_amount->amount = $default_amount;
$convert_amount->currency_code = $invoice->currency_code;
$convert_amount->currency_rate = $_currencies[$invoice->currency_code];
$amount = (double) $convert_amount->getDynamicConvertedAmount();
}
$paid += $amount;
}
}
$invoice->paid = $paid;
$accounts = Account::enabled()->orderBy('name')->pluck('name', 'id');
$currencies = Currency::enabled()->orderBy('name')->pluck('name', 'code')->toArray();
$account_currency_code = Account::where('id', setting('general.default_account'))->pluck('currency_code')->first();
$customers = Customer::enabled()->orderBy('name')->pluck('name', 'id');
$categories = Category::enabled()->type('income')->orderBy('name')->pluck('name', 'id');
$payment_methods = Modules::getPaymentMethods();
return view('incomes.invoices.show', compact('invoice', 'accounts', 'currencies', 'account_currency_code', 'customers', 'categories', 'payment_methods'));
}
/**
* Show the form for creating a new resource.
*
* @return Response
*/
public function create()
{
$customers = Customer::enabled()->orderBy('name')->pluck('name', 'id');
$currencies = Currency::enabled()->orderBy('name')->pluck('name', 'code');
$currency = Currency::where('code', '=', setting('general.default_currency'))->first();
$items = Item::enabled()->orderBy('name')->pluck('name', 'id');
$taxes = Tax::enabled()->orderBy('rate')->get()->pluck('title', 'id');
$categories = Category::enabled()->type('income')->orderBy('name')->pluck('name', 'id');
$number = $this->getNextInvoiceNumber();
return view('incomes.invoices.create', compact('customers', 'currencies', 'currency', 'items', 'taxes', 'categories', 'number'));
}
/**
* Store a newly created resource in storage.
*
* @param Request $request
*
* @return Response
*/
public function store(Request $request)
{
$invoice = Invoice::create($request->input());
// Upload attachment
if ($request->file('attachment')) {
$media = $this->getMedia($request->file('attachment'), 'invoices');
$invoice->attachMedia($media, 'attachment');
}
$taxes = [];
$tax_total = 0;
$sub_total = 0;
$discount_total = 0;
$discount = $request['discount'];
$invoice_item = [];
$invoice_item['company_id'] = $request['company_id'];
$invoice_item['invoice_id'] = $invoice->id;
if ($request['item']) {
foreach ($request['item'] as $item) {
$item_sku = '';
if (!empty($item['item_id'])) {
$item_object = Item::find($item['item_id']);
$item['name'] = $item_object->name;
$item_sku = $item_object->sku;
// Decrease stock (item sold)
$item_object->quantity -= $item['quantity'];
$item_object->save();
// Notify users if out of stock
if ($item_object->quantity == 0) {
foreach ($item_object->company->users as $user) {
if (!$user->can('read-notifications')) {
continue;
}
$user->notify(new ItemNotification($item_object));
}
}
}
$tax = $tax_id = 0;
if (!empty($item['tax_id'])) {
$tax_object = Tax::find($item['tax_id']);
$tax_id = $item['tax_id'];
$tax = (((double) $item['price'] * (double) $item['quantity']) / 100) * $tax_object->rate;
// Apply discount to tax
if ($discount) {
$tax = $tax - ($tax * ($discount / 100));
}
}
$invoice_item['item_id'] = $item['item_id'];
$invoice_item['name'] = str_limit($item['name'], 180, '');
$invoice_item['sku'] = $item_sku;
$invoice_item['quantity'] = (double) $item['quantity'];
$invoice_item['price'] = (double) $item['price'];
$invoice_item['tax'] = $tax;
$invoice_item['tax_id'] = $tax_id;
$invoice_item['total'] = (double) $item['price'] * (double) $item['quantity'];
InvoiceItem::create($invoice_item);
// Set taxes
if (isset($tax_object)) {
if (array_key_exists($tax_object->id, $taxes)) {
$taxes[$tax_object->id]['amount'] += $tax;
} else {
$taxes[$tax_object->id] = [
'name' => $tax_object->name,
'amount' => $tax
];
}
}
// Calculate totals
$tax_total += $tax;
$sub_total += $invoice_item['total'];
unset($tax_object);
}
}
$s_total = $sub_total;
// Apply discount to total
if ($discount) {
$s_discount = $s_total * ($discount / 100);
$discount_total += $s_discount;
$s_total = $s_total - $s_discount;
}
$amount = $s_total + $tax_total;
$request['amount'] = money($amount, $request['currency_code'])->getAmount();
$invoice->update($request->input());
// Add invoice totals
$this->addTotals($invoice, $request, $taxes, $sub_total, $discount_total, $tax_total);
// Add invoice history
InvoiceHistory::create([
'company_id' => session('company_id'),
'invoice_id' => $invoice->id,
'status_code' => 'draft',
'notify' => 0,
'description' => trans('messages.success.added', ['type' => $invoice->invoice_number]),
]);
// Update next invoice number
$this->increaseNextInvoiceNumber();
// Recurring
$invoice->createRecurring();
// Fire the event to make it extendible
event(new InvoiceCreated($invoice));
$message = trans('messages.success.added', ['type' => trans_choice('general.invoices', 1)]);
flash($message)->success();
return redirect('incomes/invoices/' . $invoice->id);
}
/**
* Duplicate the specified resource.
*
* @param Invoice $invoice
*
* @return Response
*/
public function duplicate(Invoice $invoice)
{
$clone = $invoice->duplicate();
// Add invoice history
InvoiceHistory::create([
'company_id' => session('company_id'),
'invoice_id' => $clone->id,
'status_code' => 'draft',
'notify' => 0,
'description' => trans('messages.success.added', ['type' => $clone->invoice_number]),
]);
// Update next invoice number
$this->increaseNextInvoiceNumber();
$message = trans('messages.success.duplicated', ['type' => trans_choice('general.invoices', 1)]);
flash($message)->success();
return redirect('incomes/invoices/' . $clone->id . '/edit');
}
/**
* Import the specified resource.
*
* @param ImportFile $import
*
* @return Response
*/
public function import(ImportFile $import)
{
$success = true;
$allowed_sheets = ['invoices', 'invoice_items', 'invoice_histories', 'invoice_payments', 'invoice_totals'];
// Loop through all sheets
$import->each(function ($sheet) use (&$success, $allowed_sheets) {
$sheet_title = $sheet->getTitle();
if (!in_array($sheet_title, $allowed_sheets)) {
$message = trans('messages.error.import_sheet');
flash($message)->error()->important();
return false;
}
$slug = 'Income\\' . str_singular(studly_case($sheet_title));
if (!$success = Import::createFromSheet($sheet, $slug)) {
return false;
}
});
if (!$success) {
return redirect('common/import/incomes/invoices');
}
$message = trans('messages.success.imported', ['type' => trans_choice('general.invoices', 2)]);
flash($message)->success();
return redirect('incomes/invoices');
}
/**
* Show the form for editing the specified resource.
*
* @param Invoice $invoice
*
* @return Response
*/
public function edit(Invoice $invoice)
{
$customers = Customer::enabled()->orderBy('name')->pluck('name', 'id');
$currencies = Currency::enabled()->orderBy('name')->pluck('name', 'code');
$currency = Currency::where('code', '=', $invoice->currency_code)->first();
$items = Item::enabled()->orderBy('name')->pluck('name', 'id');
$taxes = Tax::enabled()->orderBy('rate')->get()->pluck('title', 'id');
$categories = Category::enabled()->type('income')->orderBy('name')->pluck('name', 'id');
return view('incomes.invoices.edit', compact('invoice', 'customers', 'currencies', 'currency', 'items', 'taxes', 'categories'));
}
/**
* Update the specified resource in storage.
*
* @param Invoice $invoice
* @param Request $request
*
* @return Response
*/
public function update(Invoice $invoice, Request $request)
{
$taxes = [];
$tax_total = 0;
$sub_total = 0;
$discount_total = 0;
$discount = $request['discount'];
$invoice_item = [];
$invoice_item['company_id'] = $request['company_id'];
$invoice_item['invoice_id'] = $invoice->id;
if ($request['item']) {
$this->deleteRelationships($invoice, 'items');
foreach ($request['item'] as $item) {
unset($tax_object);
$item_sku = '';
if (!empty($item['item_id'])) {
$item_object = Item::find($item['item_id']);
$item['name'] = $item_object->name;
$item_sku = $item_object->sku;
}
$tax = $tax_id = 0;
if (!empty($item['tax_id'])) {
$tax_object = Tax::find($item['tax_id']);
$tax_id = $item['tax_id'];
$tax = (((double) $item['price'] * (double) $item['quantity']) / 100) * $tax_object->rate;
// Apply discount to tax
if ($discount) {
$tax = $tax - ($tax * ($discount / 100));
}
}
$invoice_item['item_id'] = $item['item_id'];
$invoice_item['name'] = str_limit($item['name'], 180, '');
$invoice_item['sku'] = $item_sku;
$invoice_item['quantity'] = (double) $item['quantity'];
$invoice_item['price'] = (double) $item['price'];
$invoice_item['tax'] = $tax;
$invoice_item['tax_id'] = $tax_id;
$invoice_item['total'] = (double) $item['price'] * (double) $item['quantity'];
if (isset($tax_object)) {
if (array_key_exists($tax_object->id, $taxes)) {
$taxes[$tax_object->id]['amount'] += $tax;
} else {
$taxes[$tax_object->id] = [
'name' => $tax_object->name,
'amount' => $tax
];
}
}
$tax_total += $tax;
$sub_total += $invoice_item['total'];
InvoiceItem::create($invoice_item);
}
}
$s_total = $sub_total;
// Apply discount to total
if ($discount) {
$s_discount = $s_total * ($discount / 100);
$discount_total += $s_discount;
$s_total = $s_total - $s_discount;
}
$amount = $s_total + $tax_total;
$request['amount'] = money($amount, $request['currency_code'])->getAmount();
$invoice->update($request->input());
// Upload attachment
if ($request->file('attachment')) {
$media = $this->getMedia($request->file('attachment'), 'invoices');
$invoice->attachMedia($media, 'attachment');
}
// Delete previous invoice totals
$this->deleteRelationships($invoice, 'totals');
// Add invoice totals
$this->addTotals($invoice, $request, $taxes, $sub_total, $discount_total, $tax_total);
// Recurring
$invoice->updateRecurring();
// Fire the event to make it extendible
event(new InvoiceUpdated($invoice));
$message = trans('messages.success.updated', ['type' => trans_choice('general.invoices', 1)]);
flash($message)->success();
return redirect('incomes/invoices/' . $invoice->id);
}
/**
* Remove the specified resource from storage.
*
* @param Invoice $invoice
*
* @return Response
*/
public function destroy(Invoice $invoice)
{
$this->deleteRelationships($invoice, ['items', 'histories', 'payments', 'recurring', 'totals']);
$invoice->delete();
$message = trans('messages.success.deleted', ['type' => trans_choice('general.invoices', 1)]);
flash($message)->success();
return redirect('incomes/invoices');
}
/**
* Export the specified resource.
*
* @return Response
*/
public function export()
{
\Excel::create('invoices', function ($excel) {
$invoices = Invoice::with(['items', 'histories', 'payments', 'totals'])->filter(request()->input())->get();
$excel->sheet('invoices', function ($sheet) use ($invoices) {
$sheet->fromModel($invoices->makeHidden([
'company_id', 'parent_id', 'created_at', 'updated_at', 'deleted_at', 'attachment', 'discount', 'items', 'histories', 'payments', 'totals', 'media'
]));
});
$tables = ['items', 'histories', 'payments', 'totals'];
foreach ($tables as $table) {
$excel->sheet('invoice_' . $table, function ($sheet) use ($invoices, $table) {
$hidden_fields = ['id', 'company_id', 'created_at', 'updated_at', 'deleted_at', 'title'];
$i = 1;
foreach ($invoices as $invoice) {
$model = $invoice->$table->makeHidden($hidden_fields);
if ($i == 1) {
$sheet->fromModel($model, null, 'A1', false);
} else {
// Don't put multiple heading columns
$sheet->fromModel($model, null, 'A1', false, false);
}
$i++;
}
});
}
})->download('xlsx');
}
/**
* Mark the invoice as sent.
*
* @param Invoice $invoice
*
* @return Response
*/
public function markSent(Invoice $invoice)
{
$invoice->invoice_status_code = 'sent';
$invoice->save();
// Add invoice history
InvoiceHistory::create([
'company_id' => $invoice->company_id,
'invoice_id' => $invoice->id,
'status_code' => 'sent',
'notify' => 0,
'description' => trans('invoices.mark_sent'),
]);
flash(trans('invoices.messages.marked_sent'))->success();
return redirect()->back();
}
/**
* Download the PDF file of invoice.
*
* @param Invoice $invoice
*
* @return Response
*/
public function emailInvoice(Invoice $invoice)
{
if (empty($invoice->customer_email)) {
return redirect()->back();
}
$invoice = $this->prepareInvoice($invoice);
$html = view($invoice->template_path, compact('invoice'))->render();
$pdf = \App::make('dompdf.wrapper');
$pdf->loadHTML($html);
$file = storage_path('app/temp/invoice_'.time().'.pdf');
$invoice->pdf_path = $file;
// Save the PDF file into temp folder
$pdf->save($file);
// Notify the customer
$invoice->customer->notify(new Notification($invoice));
// Delete temp file
File::delete($file);
unset($invoice->paid);
unset($invoice->template_path);
unset($invoice->pdf_path);
// Mark invoice as sent
if ($invoice->invoice_status_code != 'partial') {
$invoice->invoice_status_code = 'sent';
$invoice->save();
}
// Add invoice history
InvoiceHistory::create([
'company_id' => $invoice->company_id,
'invoice_id' => $invoice->id,
'status_code' => 'sent',
'notify' => 1,
'description' => trans('invoices.send_mail'),
]);
flash(trans('invoices.messages.email_sent'))->success();
return redirect()->back();
}
/**
* Print the invoice.
*
* @param Invoice $invoice
*
* @return Response
*/
public function printInvoice(Invoice $invoice)
{
$invoice = $this->prepareInvoice($invoice);
return view($invoice->template_path, compact('invoice'));
}
/**
* Download the PDF file of invoice.
*
* @param Invoice $invoice
*
* @return Response
*/
public function pdfInvoice(Invoice $invoice)
{
$invoice = $this->prepareInvoice($invoice);
$html = view($invoice->template_path, compact('invoice'))->render();
$pdf = app('dompdf.wrapper');
$pdf->loadHTML($html);
//$pdf->setPaper('A4', 'portrait');
$file_name = 'invoice_'.time().'.pdf';
return $pdf->download($file_name);
}
/**
* Mark the invoice as paid.
*
* @param Invoice $invoice
*
* @return Response
*/
public function markPaid(Invoice $invoice)
{
$paid = 0;
foreach ($invoice->payments as $item) {
$amount = $item->amount;
if ($invoice->currency_code != $item->currency_code) {
$item->default_currency_code = $invoice->currency_code;
$amount = $item->getDynamicConvertedAmount();
}
$paid += $amount;
}
$amount = $invoice->amount - $paid;
if (!empty($amount)) {
$request = new PaymentRequest();
$request['company_id'] = $invoice->company_id;
$request['invoice_id'] = $invoice->id;
$request['account_id'] = setting('general.default_account');
$request['payment_method'] = setting('general.default_payment_method', 'offlinepayment.cash.1');
$request['currency_code'] = $invoice->currency_code;
$request['amount'] = $amount;
$request['paid_at'] = Date::now()->format('Y-m-d');
$request['_token'] = csrf_token();
$this->payment($request);
} else {
$invoice->invoice_status_code = 'paid';
$invoice->save();
}
return redirect()->back();
}
/**
* Add payment to the invoice.
*
* @param PaymentRequest $request
*
* @return Response
*/
public function payment(PaymentRequest $request)
{
// Get currency object
$currency = Currency::where('code', $request['currency_code'])->first();
$request['currency_code'] = $currency->code;
$request['currency_rate'] = $currency->rate;
$invoice = Invoice::find($request['invoice_id']);
$total_amount = $invoice->amount;
$amount = (double) $request['amount'];
if ($request['currency_code'] != $invoice->currency_code) {
$request_invoice = new Invoice();
$request_invoice->amount = (float) $request['amount'];
$request_invoice->currency_code = $currency->code;
$request_invoice->currency_rate = $currency->rate;
$amount = $request_invoice->getConvertedAmount();
}
if ($invoice->payments()->count()) {
$total_amount -= $invoice->payments()->paid();
}
// For amount cover integer
$multiplier = 1;
for ($i = 0; $i < $currency->precision; $i++) {
$multiplier *= 10;
}
$amount *= $multiplier;
$total_amount *= $multiplier;
if ($amount > $total_amount) {
$message = trans('messages.error.over_payment');
return response()->json([
'success' => false,
'error' => true,
'message' => $message,
]);
} elseif ($amount == $total_amount) {
$invoice->invoice_status_code = 'paid';
} else {
$invoice->invoice_status_code = 'partial';
}
$invoice->save();
$invoice_payment_request = [
'company_id' => $request['company_id'],
'invoice_id' => $request['invoice_id'],
'account_id' => $request['account_id'],
'paid_at' => $request['paid_at'],
'amount' => $request['amount'],
'currency_code' => $request['currency_code'],
'currency_rate' => $request['currency_rate'],
'description' => $request['description'],
'payment_method' => $request['payment_method'],
'reference' => $request['reference']
];
$invoice_payment = InvoicePayment::create($invoice_payment_request);
// Upload attachment
if ($request->file('attachment')) {
$media = $this->getMedia($request->file('attachment'), 'invoices');
$invoice_payment->attachMedia($media, 'attachment');
}
$request['status_code'] = $invoice->invoice_status_code;
$request['notify'] = 0;
$desc_amount = money((float) $request['amount'], (string) $request['currency_code'], true)->format();
$request['description'] = $desc_amount . ' ' . trans_choice('general.payments', 1);
InvoiceHistory::create($request->input());
$message = trans('messages.success.added', ['type' => trans_choice('general.payments', 1)]);
return response()->json([
'success' => true,
'error' => false,
'message' => $message,
]);
}
/**
* Remove the specified resource from storage.
*
* @param InvoicePayment $payment
*
* @return Response
*/
public function paymentDestroy(InvoicePayment $payment)
{
$invoice = Invoice::find($payment->invoice_id);
if ($invoice->payments()->count() > 1) {
$invoice->invoice_status_code = 'partial';
} else {
$invoice->invoice_status_code = 'sent';
}
$invoice->save();
$desc_amount = money((float) $payment->amount, (string) $payment->currency_code, true)->format();
$description = $desc_amount . ' ' . trans_choice('general.payments', 1);
// Add invoice history
InvoiceHistory::create([
'company_id' => $invoice->company_id,
'invoice_id' => $invoice->id,
'status_code' => $invoice->invoice_status_code,
'notify' => 0,
'description' => trans('messages.success.deleted', ['type' => $description]),
]);
$payment->delete();
$message = trans('messages.success.deleted', ['type' => trans_choice('general.invoices', 1)]);
flash($message)->success();
return redirect()->back();
}
public function addItem(ItemRequest $request)
{
if ($request['item_row']) {
$item_row = $request['item_row'];
$taxes = Tax::enabled()->orderBy('rate')->get()->pluck('title', 'id');
$currency = Currency::where('code', '=', $request['currency_code'])->first();
// it should be integer for amount mask
$currency->precision = (int) $currency->precision;
$html = view('incomes.invoices.item', compact('item_row', 'taxes', 'currency'))->render();
return response()->json([
'success' => true,
'error' => false,
'data' => [
'currency' => $currency
],
'message' => 'null',
'html' => $html,
]);
}
return response()->json([
'success' => false,
'error' => true,
'data' => 'null',
'message' => trans('issue'),
'html' => 'null',
]);
}
protected function prepareInvoice(Invoice $invoice)
{
$paid = 0;
foreach ($invoice->payments as $item) {
$amount = $item->amount;
if ($invoice->currency_code != $item->currency_code) {
$item->default_currency_code = $invoice->currency_code;
$amount = $item->getDynamicConvertedAmount();
}
$paid += $amount;
}
$invoice->paid = $paid;
$invoice->template_path = 'incomes.invoices.invoice';
event(new InvoicePrinting($invoice));
return $invoice;
}
protected function addTotals($invoice, $request, $taxes, $sub_total, $discount_total, $tax_total)
{
$sort_order = 1;
// Added invoice sub total
InvoiceTotal::create([
'company_id' => $request['company_id'],
'invoice_id' => $invoice->id,
'code' => 'sub_total',
'name' => 'invoices.sub_total',
'amount' => $sub_total,
'sort_order' => $sort_order,
]);
$sort_order++;
// Added invoice discount
if ($discount_total) {
InvoiceTotal::create([
'company_id' => $request['company_id'],
'invoice_id' => $invoice->id,
'code' => 'discount',
'name' => 'invoices.discount',
'amount' => $discount_total,
'sort_order' => $sort_order,
]);
// This is for total
$sub_total = $sub_total - $discount_total;
}
$sort_order++;
// Added invoice taxes
if ($taxes) {
foreach ($taxes as $tax) {
InvoiceTotal::create([
'company_id' => $request['company_id'],
'invoice_id' => $invoice->id,
'code' => 'tax',
'name' => $tax['name'],
'amount' => $tax['amount'],
'sort_order' => $sort_order,
]);
$sort_order++;
}
}
// Added invoice total
InvoiceTotal::create([
'company_id' => $request['company_id'],
'invoice_id' => $invoice->id,
'code' => 'total',
'name' => 'invoices.total',
'amount' => $sub_total + $tax_total,
'sort_order' => $sort_order,
]);
}
}