PaymentController.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  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. //LOGS REFERRALS IN THE ACTIVITY LOG
  170. activity()
  171. ->performedOn($user)
  172. ->causedBy($ref_user)
  173. ->log('gained '. $increment.' '.config("SETTINGS::SYSTEM:CREDITS_DISPLAY_NAME").' for commission-referral of '.$user->name.' (ID:'.$user->id.')');
  174. }
  175. }
  176. }
  177. //store payment
  178. $payment = Payment::create([
  179. 'user_id' => $user->id,
  180. 'payment_id' => $response->result->id,
  181. 'payment_method' => 'paypal',
  182. 'type' => $shopProduct->type,
  183. 'status' => 'paid',
  184. 'amount' => $shopProduct->quantity,
  185. 'price' => $shopProduct->price,
  186. 'tax_value' => $shopProduct->getTaxValue(),
  187. 'tax_percent' => $shopProduct->getTaxPercent(),
  188. 'total_price' => $shopProduct->getTotalPrice(),
  189. 'currency_code' => $shopProduct->currency_code,
  190. 'shop_item_product_id' => $shopProduct->id,
  191. ]);
  192. event(new UserUpdateCreditsEvent($user));
  193. //only create invoice if SETTINGS::INVOICE:ENABLED is true
  194. if (config('SETTINGS::INVOICE:ENABLED') == 'true') {
  195. $this->createInvoice($user, $payment, 'paid', $shopProduct->currency_code);
  196. }
  197. //redirect back to home
  198. return redirect()->route('home')->with('success', __('Your credit balance has been increased!'));
  199. }
  200. // If call returns body in response, you can get the deserialized version from the result attribute of the response
  201. if (env('APP_ENV') == 'local') {
  202. dd($response);
  203. } else {
  204. abort(500);
  205. }
  206. } catch (HttpException $ex) {
  207. if (env('APP_ENV') == 'local') {
  208. echo $ex->statusCode;
  209. dd($ex->getMessage());
  210. } else {
  211. abort(422);
  212. }
  213. }
  214. }
  215. /**
  216. * @param Request $request
  217. */
  218. public function Cancel(Request $request)
  219. {
  220. return redirect()->route('store.index')->with('success', 'Payment was Canceled');
  221. }
  222. /**
  223. * @param Request $request
  224. * @param ShopProduct $shopProduct
  225. * @return RedirectResponse
  226. */
  227. public function StripePay(Request $request, ShopProduct $shopProduct)
  228. {
  229. $stripeClient = $this->getStripeClient();
  230. $request = $stripeClient->checkout->sessions->create([
  231. 'line_items' => [
  232. [
  233. 'price_data' => [
  234. 'currency' => $shopProduct->currency_code,
  235. 'product_data' => [
  236. 'name' => $shopProduct->display,
  237. 'description' => $shopProduct->description,
  238. ],
  239. 'unit_amount_decimal' => round($shopProduct->price * 100, 2),
  240. ],
  241. 'quantity' => 1,
  242. ],
  243. [
  244. 'price_data' => [
  245. 'currency' => $shopProduct->currency_code,
  246. 'product_data' => [
  247. 'name' => 'Product Tax',
  248. 'description' => $shopProduct->getTaxPercent() . "%",
  249. ],
  250. 'unit_amount_decimal' => round($shopProduct->getTaxValue(), 2) * 100,
  251. ],
  252. 'quantity' => 1,
  253. ]
  254. ],
  255. 'mode' => 'payment',
  256. "payment_method_types" => str_getcsv(config("SETTINGS::PAYMENTS:STRIPE:METHODS")),
  257. 'success_url' => route('payment.StripeSuccess', ['product' => $shopProduct->id]) . '&session_id={CHECKOUT_SESSION_ID}',
  258. 'cancel_url' => route('payment.Cancel'),
  259. ]);
  260. return redirect($request->url, 303);
  261. }
  262. /**
  263. * @param Request $request
  264. */
  265. public function StripeSuccess(Request $request)
  266. {
  267. /** @var ShopProduct $shopProduct */
  268. $shopProduct = ShopProduct::findOrFail($request->input('product'));
  269. /** @var User $user */
  270. $user = Auth::user();
  271. $stripeClient = $this->getStripeClient();
  272. try {
  273. //get stripe data
  274. $paymentSession = $stripeClient->checkout->sessions->retrieve($request->input('session_id'));
  275. $paymentIntent = $stripeClient->paymentIntents->retrieve($paymentSession->payment_intent);
  276. //get DB entry of this payment ID if existing
  277. $paymentDbEntry = Payment::where('payment_id', $paymentSession->payment_intent)->count();
  278. // check if payment is 100% completed and payment does not exist in db already
  279. if ($paymentSession->status == "complete" && $paymentIntent->status == "succeeded" && $paymentDbEntry == 0) {
  280. //update server limit
  281. if (config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE') !== 0) {
  282. if ($user->server_limit < config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE')) {
  283. $user->update(['server_limit' => config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE')]);
  284. }
  285. }
  286. //update User with bought item
  287. if ($shopProduct->type=="Credits") {
  288. $user->increment('credits', $shopProduct->quantity);
  289. }elseif ($shopProduct->type=="Server slots"){
  290. $user->increment('server_limit', $shopProduct->quantity);
  291. }
  292. //update role give Referral-reward
  293. if ($user->role == 'member') {
  294. $user->update(['role' => 'client']);
  295. if((config("SETTINGS::REFERRAL:MODE") == "commission" || config("SETTINGS::REFERRAL:MODE") == "both") && $shopProduct->type=="Credits"){
  296. if($ref_user = DB::table("user_referrals")->where('registered_user_id', '=', $user->id)->first()){
  297. $ref_user = User::findOrFail($ref_user->referral_id);
  298. $increment = number_format($shopProduct->quantity/100*config("SETTINGS::REFERRAL:PERCENTAGE"),0,"","");
  299. $ref_user->increment('credits', $increment);
  300. //LOGS REFERRALS IN THE ACTIVITY LOG
  301. activity()
  302. ->performedOn($user)
  303. ->causedBy($ref_user)
  304. ->log('gained '. $increment.' '.config("SETTINGS::SYSTEM:CREDITS_DISPLAY_NAME").' for commission-referral of '.$user->name.' (ID:'.$user->id.')');
  305. }
  306. }
  307. }
  308. //store paid payment
  309. $payment = Payment::create([
  310. 'user_id' => $user->id,
  311. 'payment_id' => $paymentSession->payment_intent,
  312. 'payment_method' => 'stripe',
  313. 'type' => $shopProduct->type,
  314. 'status' => 'paid',
  315. 'amount' => $shopProduct->quantity,
  316. 'price' => $shopProduct->price,
  317. 'tax_value' => $shopProduct->getTaxValue(),
  318. 'total_price' => $shopProduct->getTotalPrice(),
  319. 'tax_percent' => $shopProduct->getTaxPercent(),
  320. 'currency_code' => $shopProduct->currency_code,
  321. 'shop_item_product_id' => $shopProduct->id,
  322. ]);
  323. //payment notification
  324. $user->notify(new ConfirmPaymentNotification($payment));
  325. event(new UserUpdateCreditsEvent($user));
  326. //only create invoice if SETTINGS::INVOICE:ENABLED is true
  327. if (config('SETTINGS::INVOICE:ENABLED') == 'true') {
  328. $this->createInvoice($user, $payment, 'paid', $shopProduct->currency_code);
  329. }
  330. //redirect back to home
  331. return redirect()->route('home')->with('success', __('Your credit balance has been increased!'));
  332. } else {
  333. if ($paymentIntent->status == "processing") {
  334. //store processing payment
  335. $payment = Payment::create([
  336. 'user_id' => $user->id,
  337. 'payment_id' => $paymentSession->payment_intent,
  338. 'payment_method' => 'stripe',
  339. 'type' => $shopProduct->type,
  340. 'status' => 'processing',
  341. 'amount' => $shopProduct->quantity,
  342. 'price' => $shopProduct->price,
  343. 'tax_value' => $shopProduct->getTaxValue(),
  344. 'total_price' => $shopProduct->getTotalPrice(),
  345. 'tax_percent' => $shopProduct->getTaxPercent(),
  346. 'currency_code' => $shopProduct->currency_code,
  347. 'shop_item_product_id' => $shopProduct->id,
  348. ]);
  349. //only create invoice if SETTINGS::INVOICE:ENABLED is true
  350. if (config('SETTINGS::INVOICE:ENABLED') == 'true') {
  351. $this->createInvoice($user, $payment, 'paid', $shopProduct->currency_code);
  352. }
  353. //redirect back to home
  354. return redirect()->route('home')->with('success', __('Your payment is being processed!'));
  355. }
  356. if ($paymentDbEntry == 0 && $paymentIntent->status != "processing") {
  357. $stripeClient->paymentIntents->cancel($paymentIntent->id);
  358. //redirect back to home
  359. return redirect()->route('home')->with('success', __('Your payment has been canceled!'));
  360. } else {
  361. abort(402);
  362. }
  363. }
  364. } catch (HttpException $ex) {
  365. if (env('APP_ENV') == 'local') {
  366. echo $ex->statusCode;
  367. dd($ex->getMessage());
  368. } else {
  369. abort(422);
  370. }
  371. }
  372. }
  373. /**
  374. * @param Request $request
  375. */
  376. protected function handleStripePaymentSuccessHook($paymentIntent)
  377. {
  378. try {
  379. // Get payment db entry
  380. $payment = Payment::where('payment_id', $paymentIntent->id)->first();
  381. $user = User::where('id', $payment->user_id)->first();
  382. if ($paymentIntent->status == 'succeeded' && $payment->status == 'processing') {
  383. //update server limit
  384. if (config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE') !== 0) {
  385. if ($user->server_limit < config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE')) {
  386. $user->update(['server_limit' => config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE')]);
  387. }
  388. }
  389. //update User with bought item
  390. if ($shopProduct->type=="Credits") {
  391. $user->increment('credits', $shopProduct->quantity);
  392. }elseif ($shopProduct->type=="Server slots"){
  393. $user->increment('server_limit', $shopProduct->quantity);
  394. }
  395. //update role give Referral-reward
  396. if ($user->role == 'member') {
  397. $user->update(['role' => 'client']);
  398. if((config("SETTINGS::REFERRAL:MODE") == "commission" || config("SETTINGS::REFERRAL:MODE") == "both")&& $shopProduct->type=="Credits"){
  399. if($ref_user = DB::table("user_referrals")->where('registered_user_id', '=', $user->id)->first()){
  400. $ref_user = User::findOrFail($ref_user->referral_id);
  401. $increment = number_format($shopProduct->quantity/100*config("SETTINGS::REFERRAL:PERCENTAGE"),0,"","");
  402. $ref_user->increment('credits', $increment);
  403. //LOGS REFERRALS IN THE ACTIVITY LOG
  404. activity()
  405. ->performedOn($user)
  406. ->causedBy($ref_user)
  407. ->log('gained '. $increment.' '.config("SETTINGS::SYSTEM:CREDITS_DISPLAY_NAME").' for commission-referral of '.$user->name.' (ID:'.$user->id.')');
  408. }
  409. }
  410. }
  411. //update payment db entry status
  412. $payment->update(['status' => 'paid']);
  413. //payment notification
  414. $user->notify(new ConfirmPaymentNotification($payment));
  415. event(new UserUpdateCreditsEvent($user));
  416. //only create invoice if SETTINGS::INVOICE:ENABLED is true
  417. if (config('SETTINGS::INVOICE:ENABLED') == 'true') {
  418. $this->createInvoice($user, $payment, 'paid', strtoupper($paymentIntent->currency));
  419. }
  420. }
  421. } catch (HttpException $ex) {
  422. abort(422);
  423. }
  424. }
  425. /**
  426. * @param Request $request
  427. */
  428. public function StripeWebhooks(Request $request)
  429. {
  430. \Stripe\Stripe::setApiKey($this->getStripeSecret());
  431. try {
  432. $payload = @file_get_contents('php://input');
  433. $sig_header = $request->header('Stripe-Signature');
  434. $event = null;
  435. $event = \Stripe\Webhook::constructEvent(
  436. $payload,
  437. $sig_header,
  438. $this->getStripeEndpointSecret()
  439. );
  440. } catch (\UnexpectedValueException $e) {
  441. // Invalid payload
  442. abort(400);
  443. } catch (\Stripe\Exception\SignatureVerificationException $e) {
  444. // Invalid signature
  445. abort(400);
  446. }
  447. // Handle the event
  448. switch ($event->type) {
  449. case 'payment_intent.succeeded':
  450. $paymentIntent = $event->data->object; // contains a \Stripe\PaymentIntent
  451. $this->handleStripePaymentSuccessHook($paymentIntent);
  452. break;
  453. default:
  454. echo 'Received unknown event type ' . $event->type;
  455. }
  456. }
  457. /**
  458. * @return \Stripe\StripeClient
  459. */
  460. protected function getStripeClient()
  461. {
  462. return new \Stripe\StripeClient($this->getStripeSecret());
  463. }
  464. /**
  465. * @return string
  466. */
  467. protected function getStripeSecret()
  468. {
  469. return env('APP_ENV') == 'local'
  470. ? config("SETTINGS::PAYMENTS:STRIPE:TEST_SECRET")
  471. : config("SETTINGS::PAYMENTS:STRIPE:SECRET");
  472. }
  473. /**
  474. * @return string
  475. */
  476. protected function getStripeEndpointSecret()
  477. {
  478. return env('APP_ENV') == 'local'
  479. ? config("SETTINGS::PAYMENTS:STRIPE:ENDPOINT_TEST_SECRET")
  480. : config("SETTINGS::PAYMENTS:STRIPE:ENDPOINT_SECRET");
  481. }
  482. protected function createInvoice($user, $payment, $paymentStatus, $currencyCode)
  483. {
  484. $shopProduct = ShopProduct::where('id', $payment->shop_item_product_id)->first();
  485. //create invoice
  486. $lastInvoiceID = \App\Models\Invoice::where("invoice_name", "like", "%" . now()->format('mY') . "%")->count("id");
  487. $newInvoiceID = $lastInvoiceID + 1;
  488. $logoPath = storage_path('app/public/logo.png');
  489. $seller = new Party([
  490. 'name' => config("SETTINGS::INVOICE:COMPANY_NAME"),
  491. 'phone' => config("SETTINGS::INVOICE:COMPANY_PHONE"),
  492. 'address' => config("SETTINGS::INVOICE:COMPANY_ADDRESS"),
  493. 'vat' => config("SETTINGS::INVOICE:COMPANY_VAT"),
  494. 'custom_fields' => [
  495. 'E-Mail' => config("SETTINGS::INVOICE:COMPANY_MAIL"),
  496. "Web" => config("SETTINGS::INVOICE:COMPANY_WEBSITE")
  497. ],
  498. ]);
  499. $customer = new Buyer([
  500. 'name' => $user->name,
  501. 'custom_fields' => [
  502. 'E-Mail' => $user->email,
  503. 'Client ID' => $user->id,
  504. ],
  505. ]);
  506. $item = (new InvoiceItem())
  507. ->title($shopProduct->description)
  508. ->pricePerUnit($shopProduct->price);
  509. $notes = [
  510. __("Payment method") . ": " . $payment->payment_method,
  511. ];
  512. $notes = implode("<br>", $notes);
  513. $invoice = Invoice::make()
  514. ->template('controlpanel')
  515. ->name(__("Invoice"))
  516. ->buyer($customer)
  517. ->seller($seller)
  518. ->discountByPercent(0)
  519. ->taxRate(floatval($shopProduct->getTaxPercent()))
  520. ->shipping(0)
  521. ->addItem($item)
  522. ->status(__($paymentStatus))
  523. ->series(now()->format('mY'))
  524. ->delimiter("-")
  525. ->sequence($newInvoiceID)
  526. ->serialNumberFormat(config("SETTINGS::INVOICE:PREFIX") . '{DELIMITER}{SERIES}{SEQUENCE}')
  527. ->currencyCode($currencyCode)
  528. ->currencySymbol(Currencies::getSymbol($currencyCode))
  529. ->notes($notes);
  530. if (file_exists($logoPath)) {
  531. $invoice->logo($logoPath);
  532. }
  533. //Save the invoice in "storage\app\invoice\USER_ID\YEAR"
  534. $invoice->filename = $invoice->getSerialNumber() . '.pdf';
  535. $invoice->render();
  536. Storage::disk("local")->put("invoice/" . $user->id . "/" . now()->format('Y') . "/" . $invoice->filename, $invoice->output);
  537. \App\Models\Invoice::create([
  538. 'invoice_user' => $user->id,
  539. 'invoice_name' => $invoice->getSerialNumber(),
  540. 'payment_id' => $payment->payment_id,
  541. ]);
  542. //Send Invoice per Mail
  543. $user->notify(new InvoiceNotification($invoice, $user, $payment));
  544. }
  545. /**
  546. * @return JsonResponse|mixed
  547. * @throws Exception
  548. */
  549. public function dataTable()
  550. {
  551. $query = Payment::with('user');
  552. return datatables($query)
  553. ->editColumn('user', function (Payment $payment) {
  554. return $payment->user->name;
  555. })
  556. ->editColumn('price', function (Payment $payment) {
  557. return $payment->formatToCurrency($payment->price);
  558. })
  559. ->editColumn('tax_value', function (Payment $payment) {
  560. return $payment->formatToCurrency($payment->tax_value);
  561. })
  562. ->editColumn('tax_percent', function (Payment $payment) {
  563. return $payment->tax_percent . ' %';
  564. })
  565. ->editColumn('total_price', function (Payment $payment) {
  566. return $payment->formatToCurrency($payment->total_price);
  567. })
  568. ->editColumn('created_at', function (Payment $payment) {
  569. return $payment->created_at ? $payment->created_at->diffForHumans() : '';
  570. })
  571. ->addColumn('actions', function (Payment $payment) {
  572. 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>';
  573. })
  574. ->rawColumns(['actions'])
  575. ->make(true);
  576. }
  577. }