PaymentController.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  1. <?php
  2. namespace App\Http\Controllers\Admin;
  3. use App\Events\UserUpdateCreditsEvent;
  4. use App\Http\Controllers\Controller;
  5. use App\Models\InvoiceSettings;
  6. use App\Models\Payment;
  7. use App\Models\ShopProduct;
  8. use App\Models\Settings;
  9. use App\Models\User;
  10. use App\Notifications\InvoiceNotification;
  11. use App\Notifications\ConfirmPaymentNotification;
  12. use Exception;
  13. use Illuminate\Contracts\Foundation\Application;
  14. use Illuminate\Contracts\View\Factory;
  15. use Illuminate\Contracts\View\View;
  16. use Illuminate\Http\JsonResponse;
  17. use Illuminate\Http\RedirectResponse;
  18. use Illuminate\Http\Request;
  19. use Illuminate\Support\Facades\Auth;
  20. use Illuminate\Support\Facades\DB;
  21. use Illuminate\Support\Facades\Log;
  22. use Illuminate\Support\Facades\Storage;
  23. use LaravelDaily\Invoices\Classes\Buyer;
  24. use LaravelDaily\Invoices\Classes\InvoiceItem;
  25. use LaravelDaily\Invoices\Classes\Party;
  26. use LaravelDaily\Invoices\Invoice;
  27. use PayPalCheckoutSdk\Core\PayPalHttpClient;
  28. use PayPalCheckoutSdk\Core\ProductionEnvironment;
  29. use PayPalCheckoutSdk\Core\SandboxEnvironment;
  30. use PayPalCheckoutSdk\Orders\OrdersCaptureRequest;
  31. use PayPalCheckoutSdk\Orders\OrdersCreateRequest;
  32. use PayPalHttp\HttpException;
  33. use Stripe\Stripe;
  34. use Symfony\Component\Intl\Currencies;
  35. class PaymentController extends Controller
  36. {
  37. /**
  38. * @return Application|Factory|View
  39. */
  40. public function index()
  41. {
  42. return view('admin.payments.index')->with([
  43. 'payments' => Payment::paginate(15)
  44. ]);
  45. }
  46. /**
  47. * @param Request $request
  48. * @param ShopProduct $shopProduct
  49. * @return Application|Factory|View
  50. */
  51. public function checkOut(Request $request, ShopProduct $shopProduct)
  52. {
  53. return view('store.checkout')->with([
  54. 'product' => $shopProduct,
  55. 'taxvalue' => $shopProduct->getTaxValue(),
  56. 'taxpercent' => $shopProduct->getTaxPercent(),
  57. 'total' => $shopProduct->getTotalPrice()
  58. ]);
  59. }
  60. /**
  61. * @param Request $request
  62. * @param ShopProduct $shopProduct
  63. * @return RedirectResponse
  64. */
  65. public function PaypalPay(Request $request, ShopProduct $shopProduct)
  66. {
  67. $request = new OrdersCreateRequest();
  68. $request->prefer('return=representation');
  69. $request->body = [
  70. "intent" => "CAPTURE",
  71. "purchase_units" => [
  72. [
  73. "reference_id" => uniqid(),
  74. "description" => $shopProduct->description,
  75. "amount" => [
  76. "value" => $shopProduct->getTotalPrice(),
  77. 'currency_code' => strtoupper($shopProduct->currency_code),
  78. 'breakdown' => [
  79. 'item_total' =>
  80. [
  81. 'currency_code' => strtoupper($shopProduct->currency_code),
  82. 'value' => $shopProduct->price,
  83. ],
  84. 'tax_total' =>
  85. [
  86. 'currency_code' => strtoupper($shopProduct->currency_code),
  87. 'value' => $shopProduct->getTaxValue(),
  88. ]
  89. ]
  90. ]
  91. ]
  92. ],
  93. "application_context" => [
  94. "cancel_url" => route('payment.Cancel'),
  95. "return_url" => route('payment.PaypalSuccess', ['product' => $shopProduct->id]),
  96. 'brand_name' => config('app.name', 'Laravel'),
  97. 'shipping_preference' => 'NO_SHIPPING'
  98. ]
  99. ];
  100. try {
  101. // Call API with your client and get a response for your call
  102. $response = $this->getPayPalClient()->execute($request);
  103. return redirect()->away($response->result->links[1]->href);
  104. // If call returns body in response, you can get the deserialized version from the result attribute of the response
  105. } catch (HttpException $ex) {
  106. echo $ex->statusCode;
  107. dd(json_decode($ex->getMessage()));
  108. }
  109. }
  110. /**
  111. * @return PayPalHttpClient
  112. */
  113. protected function getPayPalClient()
  114. {
  115. $environment = env('APP_ENV') == 'local'
  116. ? new SandboxEnvironment($this->getPaypalClientId(), $this->getPaypalClientSecret())
  117. : new ProductionEnvironment($this->getPaypalClientId(), $this->getPaypalClientSecret());
  118. return new PayPalHttpClient($environment);
  119. }
  120. /**
  121. * @return string
  122. */
  123. protected function getPaypalClientId()
  124. {
  125. return env('APP_ENV') == 'local' ? config("SETTINGS::PAYMENTS:PAYPAL:SANDBOX_CLIENT_ID") : config("SETTINGS::PAYMENTS:PAYPAL:CLIENT_ID");
  126. }
  127. /**
  128. * @return string
  129. */
  130. protected function getPaypalClientSecret()
  131. {
  132. return env('APP_ENV') == 'local' ? config("SETTINGS::PAYMENTS:PAYPAL:SANDBOX_SECRET") : config("SETTINGS::PAYMENTS:PAYPAL:SECRET");
  133. }
  134. /**
  135. * @param Request $laravelRequest
  136. */
  137. public function PaypalSuccess(Request $laravelRequest)
  138. {
  139. /** @var ShopProduct $shopProduct */
  140. $shopProduct = ShopProduct::findOrFail($laravelRequest->input('product'));
  141. /** @var User $user */
  142. $user = Auth::user();
  143. $request = new OrdersCaptureRequest($laravelRequest->input('token'));
  144. $request->prefer('return=representation');
  145. try {
  146. // Call API with your client and get a response for your call
  147. $response = $this->getPayPalClient()->execute($request);
  148. if ($response->statusCode == 201 || $response->statusCode == 200) {
  149. //update server limit
  150. if (config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE') !== 0) {
  151. if ($user->server_limit < config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE')) {
  152. $user->update(['server_limit' => config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE')]);
  153. }
  154. }
  155. //update User with bought item
  156. if ($shopProduct->type=="Credits") {
  157. $user->increment('credits', $shopProduct->quantity);
  158. }elseif ($shopProduct->type=="Server slots"){
  159. $user->increment('server_limit', $shopProduct->quantity);
  160. }
  161. //update role give Referral-reward
  162. if ($user->role == 'member') {
  163. $user->update(['role' => 'client']);
  164. if((config("SETTINGS::REFERRAL:MODE") == "commission" || config("SETTINGS::REFERRAL:MODE" == "both")) && $shopProduct->type=="Credits"){
  165. if($ref_user = DB::table("user_referrals")->where('registered_user_id', '=', $user->id)->first()){
  166. $ref_user = User::findOrFail($ref_user->referral_id);
  167. $increment = number_format($shopProduct->quantity/100*config("SETTINGS::REFERRAL:PERCENTAGE"),0,"","");
  168. $ref_user->increment('credits', $increment);
  169. }
  170. }
  171. }
  172. //store payment
  173. $payment = Payment::create([
  174. 'user_id' => $user->id,
  175. 'payment_id' => $response->result->id,
  176. 'payment_method' => 'paypal',
  177. 'type' => $shopProduct->type,
  178. 'status' => 'paid',
  179. 'amount' => $shopProduct->quantity,
  180. 'price' => $shopProduct->price,
  181. 'tax_value' => $shopProduct->getTaxValue(),
  182. 'tax_percent' => $shopProduct->getTaxPercent(),
  183. 'total_price' => $shopProduct->getTotalPrice(),
  184. 'currency_code' => $shopProduct->currency_code,
  185. 'shop_item_product_id' => $shopProduct->id,
  186. ]);
  187. event(new UserUpdateCreditsEvent($user));
  188. //only create invoice if SETTINGS::INVOICE:ENABLED is true
  189. if (config('SETTINGS::INVOICE:ENABLED') == 'true') {
  190. $this->createInvoice($user, $payment, 'paid', $shopProduct->currency_code);
  191. }
  192. //redirect back to home
  193. return redirect()->route('home')->with('success', __('Your credit balance has been increased!'));
  194. }
  195. // If call returns body in response, you can get the deserialized version from the result attribute of the response
  196. if (env('APP_ENV') == 'local') {
  197. dd($response);
  198. } else {
  199. abort(500);
  200. }
  201. } catch (HttpException $ex) {
  202. if (env('APP_ENV') == 'local') {
  203. echo $ex->statusCode;
  204. dd($ex->getMessage());
  205. } else {
  206. abort(422);
  207. }
  208. }
  209. }
  210. /**
  211. * @param Request $request
  212. */
  213. public function Cancel(Request $request)
  214. {
  215. return redirect()->route('store.index')->with('success', 'Payment was Canceled');
  216. }
  217. /**
  218. * @param Request $request
  219. * @param ShopProduct $shopProduct
  220. * @return RedirectResponse
  221. */
  222. public function StripePay(Request $request, ShopProduct $shopProduct)
  223. {
  224. $stripeClient = $this->getStripeClient();
  225. $request = $stripeClient->checkout->sessions->create([
  226. 'line_items' => [
  227. [
  228. 'price_data' => [
  229. 'currency' => $shopProduct->currency_code,
  230. 'product_data' => [
  231. 'name' => $shopProduct->display,
  232. 'description' => $shopProduct->description,
  233. ],
  234. 'unit_amount_decimal' => round($shopProduct->price * 100, 2),
  235. ],
  236. 'quantity' => 1,
  237. ],
  238. [
  239. 'price_data' => [
  240. 'currency' => $shopProduct->currency_code,
  241. 'product_data' => [
  242. 'name' => 'Product Tax',
  243. 'description' => $shopProduct->getTaxPercent() . "%",
  244. ],
  245. 'unit_amount_decimal' => round($shopProduct->getTaxValue(), 2) * 100,
  246. ],
  247. 'quantity' => 1,
  248. ]
  249. ],
  250. 'mode' => 'payment',
  251. "payment_method_types" => str_getcsv(config("SETTINGS::PAYMENTS:STRIPE:METHODS")),
  252. 'success_url' => route('payment.StripeSuccess', ['product' => $shopProduct->id]) . '&session_id={CHECKOUT_SESSION_ID}',
  253. 'cancel_url' => route('payment.Cancel'),
  254. ]);
  255. return redirect($request->url, 303);
  256. }
  257. /**
  258. * @param Request $request
  259. */
  260. public function StripeSuccess(Request $request)
  261. {
  262. /** @var ShopProduct $shopProduct */
  263. $shopProduct = ShopProduct::findOrFail($request->input('product'));
  264. /** @var User $user */
  265. $user = Auth::user();
  266. $stripeClient = $this->getStripeClient();
  267. try {
  268. //get stripe data
  269. $paymentSession = $stripeClient->checkout->sessions->retrieve($request->input('session_id'));
  270. $paymentIntent = $stripeClient->paymentIntents->retrieve($paymentSession->payment_intent);
  271. //get DB entry of this payment ID if existing
  272. $paymentDbEntry = Payment::where('payment_id', $paymentSession->payment_intent)->count();
  273. // check if payment is 100% completed and payment does not exist in db already
  274. if ($paymentSession->status == "complete" && $paymentIntent->status == "succeeded" && $paymentDbEntry == 0) {
  275. //update server limit
  276. if (config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE') !== 0) {
  277. if ($user->server_limit < config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE')) {
  278. $user->update(['server_limit' => config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE')]);
  279. }
  280. }
  281. //update User with bought item
  282. if ($shopProduct->type=="Credits") {
  283. $user->increment('credits', $shopProduct->quantity);
  284. }elseif ($shopProduct->type=="Server slots"){
  285. $user->increment('server_limit', $shopProduct->quantity);
  286. }
  287. //update role give Referral-reward
  288. if ($user->role == 'member') {
  289. $user->update(['role' => 'client']);
  290. if((config("SETTINGS::REFERRAL:MODE") == "commission" || config("SETTINGS::REFERRAL:MODE" == "both")) && $shopProduct->type=="Credits"){
  291. if($ref_user = DB::table("user_referrals")->where('registered_user_id', '=', $user->id)->first()){
  292. $ref_user = User::findOrFail($ref_user->referral_id);
  293. $increment = number_format($shopProduct->quantity/100*config("SETTINGS::REFERRAL:PERCENTAGE"),0,"","");
  294. $ref_user->increment('credits', $increment);
  295. }
  296. }
  297. }
  298. //store paid payment
  299. $payment = Payment::create([
  300. 'user_id' => $user->id,
  301. 'payment_id' => $paymentSession->payment_intent,
  302. 'payment_method' => 'stripe',
  303. 'type' => $shopProduct->type,
  304. 'status' => 'paid',
  305. 'amount' => $shopProduct->quantity,
  306. 'price' => $shopProduct->price,
  307. 'tax_value' => $shopProduct->getTaxValue(),
  308. 'total_price' => $shopProduct->getTotalPrice(),
  309. 'tax_percent' => $shopProduct->getTaxPercent(),
  310. 'currency_code' => $shopProduct->currency_code,
  311. 'shop_item_product_id' => $shopProduct->id,
  312. ]);
  313. //payment notification
  314. $user->notify(new ConfirmPaymentNotification($payment));
  315. event(new UserUpdateCreditsEvent($user));
  316. //only create invoice if SETTINGS::INVOICE:ENABLED is true
  317. if (config('SETTINGS::INVOICE:ENABLED') == 'true') {
  318. $this->createInvoice($user, $payment, 'paid', $shopProduct->currency_code);
  319. }
  320. //redirect back to home
  321. return redirect()->route('home')->with('success', __('Your credit balance has been increased!'));
  322. } else {
  323. if ($paymentIntent->status == "processing") {
  324. //store processing payment
  325. $payment = Payment::create([
  326. 'user_id' => $user->id,
  327. 'payment_id' => $paymentSession->payment_intent,
  328. 'payment_method' => 'stripe',
  329. 'type' => $shopProduct->type,
  330. 'status' => 'processing',
  331. 'amount' => $shopProduct->quantity,
  332. 'price' => $shopProduct->price,
  333. 'tax_value' => $shopProduct->getTaxValue(),
  334. 'total_price' => $shopProduct->getTotalPrice(),
  335. 'tax_percent' => $shopProduct->getTaxPercent(),
  336. 'currency_code' => $shopProduct->currency_code,
  337. 'shop_item_product_id' => $shopProduct->id,
  338. ]);
  339. //only create invoice if SETTINGS::INVOICE:ENABLED is true
  340. if (config('SETTINGS::INVOICE:ENABLED') == 'true') {
  341. $this->createInvoice($user, $payment, 'paid', $shopProduct->currency_code);
  342. }
  343. //redirect back to home
  344. return redirect()->route('home')->with('success', __('Your payment is being processed!'));
  345. }
  346. if ($paymentDbEntry == 0 && $paymentIntent->status != "processing") {
  347. $stripeClient->paymentIntents->cancel($paymentIntent->id);
  348. //redirect back to home
  349. return redirect()->route('home')->with('success', __('Your payment has been canceled!'));
  350. } else {
  351. abort(402);
  352. }
  353. }
  354. } catch (HttpException $ex) {
  355. if (env('APP_ENV') == 'local') {
  356. echo $ex->statusCode;
  357. dd($ex->getMessage());
  358. } else {
  359. abort(422);
  360. }
  361. }
  362. }
  363. /**
  364. * @param Request $request
  365. */
  366. protected function handleStripePaymentSuccessHook($paymentIntent)
  367. {
  368. try {
  369. // Get payment db entry
  370. $payment = Payment::where('payment_id', $paymentIntent->id)->first();
  371. $user = User::where('id', $payment->user_id)->first();
  372. if ($paymentIntent->status == 'succeeded' && $payment->status == 'processing') {
  373. //update server limit
  374. if (config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE') !== 0) {
  375. if ($user->server_limit < config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE')) {
  376. $user->update(['server_limit' => config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE')]);
  377. }
  378. }
  379. //update User with bought item
  380. if ($shopProduct->type=="Credits") {
  381. $user->increment('credits', $shopProduct->quantity);
  382. }elseif ($shopProduct->type=="Server slots"){
  383. $user->increment('server_limit', $shopProduct->quantity);
  384. }
  385. //update role give Referral-reward
  386. if ($user->role == 'member') {
  387. $user->update(['role' => 'client']);
  388. if((config("SETTINGS::REFERRAL:MODE") == "commission" || config("SETTINGS::REFERRAL:MODE" == "both"))&& $shopProduct->type=="Credits"){
  389. if($ref_user = DB::table("user_referrals")->where('registered_user_id', '=', $user->id)->first()){
  390. $ref_user = User::findOrFail($ref_user->referral_id);
  391. $increment = number_format($shopProduct->quantity/100*config("SETTINGS::REFERRAL:PERCENTAGE"),0,"","");
  392. $ref_user->increment('credits', $increment);
  393. }
  394. }
  395. }
  396. //update payment db entry status
  397. $payment->update(['status' => 'paid']);
  398. //payment notification
  399. $user->notify(new ConfirmPaymentNotification($payment));
  400. event(new UserUpdateCreditsEvent($user));
  401. //only create invoice if SETTINGS::INVOICE:ENABLED is true
  402. if (config('SETTINGS::INVOICE:ENABLED') == 'true') {
  403. $this->createInvoice($user, $payment, 'paid', strtoupper($paymentIntent->currency));
  404. }
  405. }
  406. } catch (HttpException $ex) {
  407. abort(422);
  408. }
  409. }
  410. /**
  411. * @param Request $request
  412. */
  413. public function StripeWebhooks(Request $request)
  414. {
  415. \Stripe\Stripe::setApiKey($this->getStripeSecret());
  416. try {
  417. $payload = @file_get_contents('php://input');
  418. $sig_header = $request->header('Stripe-Signature');
  419. $event = null;
  420. $event = \Stripe\Webhook::constructEvent(
  421. $payload,
  422. $sig_header,
  423. $this->getStripeEndpointSecret()
  424. );
  425. } catch (\UnexpectedValueException $e) {
  426. // Invalid payload
  427. abort(400);
  428. } catch (\Stripe\Exception\SignatureVerificationException $e) {
  429. // Invalid signature
  430. abort(400);
  431. }
  432. // Handle the event
  433. switch ($event->type) {
  434. case 'payment_intent.succeeded':
  435. $paymentIntent = $event->data->object; // contains a \Stripe\PaymentIntent
  436. $this->handleStripePaymentSuccessHook($paymentIntent);
  437. break;
  438. default:
  439. echo 'Received unknown event type ' . $event->type;
  440. }
  441. }
  442. /**
  443. * @return \Stripe\StripeClient
  444. */
  445. protected function getStripeClient()
  446. {
  447. return new \Stripe\StripeClient($this->getStripeSecret());
  448. }
  449. /**
  450. * @return string
  451. */
  452. protected function getStripeSecret()
  453. {
  454. return env('APP_ENV') == 'local'
  455. ? config("SETTINGS::PAYMENTS:STRIPE:TEST_SECRET")
  456. : config("SETTINGS::PAYMENTS:STRIPE:SECRET");
  457. }
  458. /**
  459. * @return string
  460. */
  461. protected function getStripeEndpointSecret()
  462. {
  463. return env('APP_ENV') == 'local'
  464. ? config("SETTINGS::PAYMENTS:STRIPE:ENDPOINT_TEST_SECRET")
  465. : config("SETTINGS::PAYMENTS:STRIPE:ENDPOINT_SECRET");
  466. }
  467. protected function createInvoice($user, $payment, $paymentStatus, $currencyCode)
  468. {
  469. $shopProduct = ShopProduct::where('id', $payment->shop_item_product_id)->first();
  470. //create invoice
  471. $lastInvoiceID = \App\Models\Invoice::where("invoice_name", "like", "%" . now()->format('mY') . "%")->count("id");
  472. $newInvoiceID = $lastInvoiceID + 1;
  473. $logoPath = storage_path('app/public/logo.png');
  474. $seller = new Party([
  475. 'name' => config("SETTINGS::INVOICE:COMPANY_NAME"),
  476. 'phone' => config("SETTINGS::INVOICE:COMPANY_PHONE"),
  477. 'address' => config("SETTINGS::INVOICE:COMPANY_ADDRESS"),
  478. 'vat' => config("SETTINGS::INVOICE:COMPANY_VAT"),
  479. 'custom_fields' => [
  480. 'E-Mail' => config("SETTINGS::INVOICE:COMPANY_MAIL"),
  481. "Web" => config("SETTINGS::INVOICE:COMPANY_WEBSITE")
  482. ],
  483. ]);
  484. $customer = new Buyer([
  485. 'name' => $user->name,
  486. 'custom_fields' => [
  487. 'E-Mail' => $user->email,
  488. 'Client ID' => $user->id,
  489. ],
  490. ]);
  491. $item = (new InvoiceItem())
  492. ->title($shopProduct->description)
  493. ->pricePerUnit($shopProduct->price);
  494. $notes = [
  495. __("Payment method") . ": " . $payment->payment_method,
  496. ];
  497. $notes = implode("<br>", $notes);
  498. $invoice = Invoice::make()
  499. ->template('controlpanel')
  500. ->name(__("Invoice"))
  501. ->buyer($customer)
  502. ->seller($seller)
  503. ->discountByPercent(0)
  504. ->taxRate(floatval($shopProduct->getTaxPercent()))
  505. ->shipping(0)
  506. ->addItem($item)
  507. ->status(__($paymentStatus))
  508. ->series(now()->format('mY'))
  509. ->delimiter("-")
  510. ->sequence($newInvoiceID)
  511. ->serialNumberFormat(config("SETTINGS::INVOICE:PREFIX") . '{DELIMITER}{SERIES}{SEQUENCE}')
  512. ->currencyCode($currencyCode)
  513. ->currencySymbol(Currencies::getSymbol($currencyCode))
  514. ->notes($notes);
  515. if (file_exists($logoPath)) {
  516. $invoice->logo($logoPath);
  517. }
  518. //Save the invoice in "storage\app\invoice\USER_ID\YEAR"
  519. $invoice->filename = $invoice->getSerialNumber() . '.pdf';
  520. $invoice->render();
  521. Storage::disk("local")->put("invoice/" . $user->id . "/" . now()->format('Y') . "/" . $invoice->filename, $invoice->output);
  522. \App\Models\Invoice::create([
  523. 'invoice_user' => $user->id,
  524. 'invoice_name' => $invoice->getSerialNumber(),
  525. 'payment_id' => $payment->payment_id,
  526. ]);
  527. //Send Invoice per Mail
  528. $user->notify(new InvoiceNotification($invoice, $user, $payment));
  529. }
  530. /**
  531. * @return JsonResponse|mixed
  532. * @throws Exception
  533. */
  534. public function dataTable()
  535. {
  536. $query = Payment::with('user');
  537. return datatables($query)
  538. ->editColumn('user', function (Payment $payment) {
  539. return $payment->user->name;
  540. })
  541. ->editColumn('price', function (Payment $payment) {
  542. return $payment->formatToCurrency($payment->price);
  543. })
  544. ->editColumn('tax_value', function (Payment $payment) {
  545. return $payment->formatToCurrency($payment->tax_value);
  546. })
  547. ->editColumn('tax_percent', function (Payment $payment) {
  548. return $payment->tax_percent . ' %';
  549. })
  550. ->editColumn('total_price', function (Payment $payment) {
  551. return $payment->formatToCurrency($payment->total_price);
  552. })
  553. ->editColumn('created_at', function (Payment $payment) {
  554. return $payment->created_at ? $payment->created_at->diffForHumans() : '';
  555. })
  556. ->addColumn('actions', function (Payment $payment) {
  557. return '<a data-content="' . __("Download") . '" data-toggle="popover" data-trigger="hover" data-placement="top" href="' . route('admin.invoices.downloadSingleInvoice', "id=" . $payment->payment_id) . '" class="btn btn-sm text-white btn-info mr-1"><i class="fas fa-file-download"></i></a>';
  558. })
  559. ->rawColumns(['actions'])
  560. ->make(true);
  561. }
  562. }